自定义控件
自定义组合控件
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>