Android中的自定义属性和组合式控件

组合式控件

多个零散的控件当一个控件用
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="wrap_content"
    android:paddingLeft="20dp"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:paddingRight="15dp">

    <TextView
        android:id="@+id/tv_auto_updata"
        android:layout_centerVertical="true"
        android:textSize="16sp"
        android:text="自动设置更新"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <ImageView
        android:id="@+id/iv_toggle"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:src="@mipmap/off"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

2。定义一个 类,这个类继承是由规则的,布局的跟标签是什么类型,就必须继承什么类型的;

public class SettingItemView extends RelativeLayout 

3。导入布局,把布局加入到容器中

public SettingItemView(Context context, AttributeSet attrs) {
    super(context, attrs);
    //第三个参数如果为null:则表示不要将布局加入到容器中
    //如果是this:则表示将布局加入到当前容器中
    //容器就是当前类
    View.inflate(context , R.layout.setting_item_view , this);
  }

4。使用组合式控件

<com.myself.mobilesafe.View.SettingItemView
  android:background="@drawable/seletor_siv_first"
  myattrs:title="设置自动更新"
  android:id="@+id/siv_auto_updata"
  android:layout_marginTop="20dp"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"/>

自定义属性

1。首先在values文件夹下创建一个attrs.xml文件
2。在文件中声明属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <!--这里的name,一般情况下写的是类名-->
  <declare-styleable name="SettingItemView">
      <!--属性名为title,属性的数据类型是string类型的-->
      <attr name="title" format="string"/>
  </declare-styleable>
</resources>

3。在布局文件中声明命名空间

//将android换成包名com.myself.mobilesafe
xmlns:myattrs="http://schemas.android.com/apk/res/com.myself.mobilesafe"

4。在控件中使用属性

<com.myself.mobilesafe.View.SettingItemView
        android:background="@drawable/seletor_siv_first"
        myattrs:title="设置自动更新"
        android:id="@+id/siv_auto_updata"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

5。在自定义组合式控件中获取属性值

//得到名为settingitemview下的所有属性
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SettingItemView);
  //得到自己定义的title属性数值
   String title = typedArray.getString(R.styleable.SettingItemView_title);
  mTvAutoUpdata.setText(title);
   //释放资源
   typedArray.recycle();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值