自定义控件

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

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

代码实现如下:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值