创建自定义控件(含有自定义属性)


转载请注明原文地址: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就完成了,如果有其他的需求,就可以在此基础之上进行完善,希望对大家有帮助。

如果有不足之处,请大家指出,互相帮助。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值