转载请注明原文地址:http://blog.csdn.net/forwardyzk/article/details/25079743
源码下载:http://download.csdn.net/detail/forwardyzk/7299935
创建自定义控件(含有自定义属性)的步骤
自定义了一个LinearLayout,含有一个titles属性,给里面的两个TextView设置文本。
1. 自定义类MyLinearLayout继承LinearLayout
因为要添加自定义的属性,那么就使用带有两个参数的构造方法。
2. 创建自定义控件对应的布局文件,
my_ll_layout.xml
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv_02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
3.设置自定义的属性
创建attres.xml文件
res/values/attres.xml
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<declare-styleablename="MyLinearLayout">
<attrname="titles"format="string"/>
</declare-styleable>
</resources>
4.在调用处定义声明自定义的命令
main.xml
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/apk/res/com.example.testlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.testlayout.MyLinearLayout
android:id="@+id/my_ll_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
test:titles="one,tow">
</com.example.testlayout.MyLinearLayout>
</LinearLayout>
xmlns:test="http://schemas.android.com/apk/res/com.example.testlayout"
其中com.example.testlayout是应用程序的包名
5.在自定义的类中获得自定义的属性
publicclass MyLinearLayout extends LinearLayout {
private String titles;
private TextView tv_01;
private TextView tv_02;
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
View.inflate(context, R.layout.my_ll_layout, this);
titles = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.example.testlayout", "titles");
String [] ts=titles.split(",");
tv_01 = (TextView)this.findViewById(R.id.tv_01);
tv_02 = (TextView)this.findViewById(R.id.tv_02);
tv_01.setText(ts[0]);
tv_02.setText(ts[1]);
}
}
解释:
attrs.getAttributeValue("http://schemas.android.com/apk/res/com.example.testlayout","titles");
其中:http://schemas.android.com/apk/res/com.example.testlayout是在调用处生命的命名空间
"titles"是自定义属性的名字
这样一个简单的自定义控件的demo就完成了,如果有其他的需求,就可以在此基础之上进行完善,希望对大家有帮助。
如果有不足之处,请大家指出,互相帮助。