自定义控件

来源:互联网 发布:understand mac 教程 编辑:程序博客网 时间:2024/06/05 00:31

当一个布局当中许多多次使用到一个类型的组合控件时,可以采用复制粘贴后修改信息的方法来实现。但是这个存在大量的代码冗余,拖慢应用的效率。此时就可以采用定义控件的方法来优化。

  • 将公共部分的代码提取出来放在一个布局文件当中;
  • 设置一个类继承一个相对布局(线性布局/帧布局也是可以的),在这个类中实行初始化页面的时候将其的父类定义成相对布局,
  • 并在这个类中实例化公共部分布局文件当中的组件出来
  • 将自定义组件的全类名拷贝出来后并将其使用需要设置的布局地方

代码实现如下:

1.设置公共部分的布局信息

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="60dp"android:padding="5dp" ><TextView    android:id="@+id/tv_title"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="自动更新设置"    android:textColor="@color/black"    android:textSize="24sp" /><TextView    android:id="@+id/tv_desc"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_below="@id/tv_title"    android:layout_marginTop="3dp"    android:text="自动更新设置开启"    android:textColor="#a000"    android:textSize="10sp" /><CheckBox    android:id="@+id/cb_status"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_alignParentRight="true"    android:layout_centerVertical="true" /><View    android:layout_width="match_parent"    android:layout_height="1dp"    android:layout_alignParentBottom="true"    android:background="#a000" /></RelativeLayout>

2.设置一个类继承相对布局,并将开始布局信息设置给相对布局,则每次初始化相对布局的时候,里面就已经有这些信息

public class SettingItemView extends RelativeLayout {private TextView tvItem;private TextView tvDesc;private CheckBox cbStatus;public SettingItemView(Context context, AttributeSet attrs, int defStyle) {    super(context, attrs, defStyle);    initView();}public SettingItemView(Context context, AttributeSet attrs) {    super(context, attrs);    initView();}public SettingItemView(Context context) {    super(context);    initView();}private void initView(){    View.inflate(getContext(), R.layout.view_setting_item, this);    tvItem = (TextView) findViewById(R.id.tv_item);    tvDesc = (TextView) findViewById(R.id.tv_desc);    cbStatus = (CheckBox) findViewById(R.id.cb_status);}   

3.在需要定义该组件的地方将其定规出来

<com.scau.mobilesafe.view.SettingItemView    android:layout_width="match_parent"    android:layout_height="wrap_content" />

Tips

一.细节:
1.this指代就是本类当中的对象。比方说本类如果是context对象,则此处的this就是将其指代。如果不是context对象,则可以用getContext对象来获取context对象

二.总体
1.本方法initview的目的是将view_setting_item设置给这个类的父控件RelativeLayout。最后一个参数root就是指代的第二个参数的父类。

3.这个方法的目的就是将view_setting_item塞给RelativeLayout,以后每次执行这个方法的时候,RelativeLayout将自动就有了view_setting_item里面的布局信息

0 0
原创粉丝点击