Android自定义控件系列——自定义组合控件案例

自定义控件

自定义组合控件

1 创建自定义布局view_combination.xm,指定text的id值

2 创建自定义属性attrs.xml中的resource节点下

<declare-styleable name="MyView">	//指定MyView为自定义属性名
    //设置文本,format的类型见Andrid提示,注意大小写
	<attr name="MyText" format="reference|string" />	
    <attr name="sivBackground">			//自定义背景,使用enum,本例不体现
        <enum name="start" value="0" />	
        <enum name="middle" value="1" />
    </attr>
</declare-styleable>

2 自定义CombinationView类继承RelativeLayout

public CombinationView(Context context){//java代码中使用自定义控件时使用
    this(context, null);
}
public CombinationView(Context context, AttributeSet attrs){//xml中使用自定义控件时使用
    this(context, attrs, -1);
}
public CombinationView(Context context, AttributeSet attrs, int defStyleAttr){
    super(context, attrs, defStyleAttr);
    init(context, attrs);
}
private TextView tv_text;
private void init(Context context, AttributeSet attrs){
    View.inflate(context, R.layout.view_combination, this);	//挂载view
    //指定自定义属性名:MyView
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyView);
    //获取自定义属性中的值
    String text = ta.getString(R.styleable.MyView_myText);
    //将值设置给控件
    tv_text = findViewById(R.id.tv_first);
    tv_text.setText(text);
    //TypedArray的回收,否则容易内存泄漏
    ta.recycle();	
}
//向外暴露方法,操作组合控件中属性
private void changeText(){
    tv_text.setText("111");
}

4 使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	//自定义命名空间:my。res/包名 或 apk/res-auto
	xmlns:my="http://schemas.android.com/apk/res/com.demo.combinationView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="@color/title_bg"
        my:MyText="222"/>	//必须使用自定义命名空间中设置值:my。属性必须使用自定义属性MyView中对应的MyText。
</LinearLayout>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值