这种方法的优点就是简单,容易理解,适合开发一些不经常用到的自定义UI控件

缺点就是比较不灵活,如果其他应用想使用这个控件的话得改很多

简单来说,这个方法是用来做成品的,下一篇的方法是用来做模板的。

先看成品,这是一个标题栏控件:

49bd8a7f71db56adef1d3b83da588c11.png

由左右两个按钮和中一个TextView组成:

实现方法:

第一步:定义一个xml文件,用来设计你自定义控件的雏形

示例代码:文件名为title

1 <?xml version="1.0" encoding="utf-8"?>

2

4 android:layout_width="match_parent"

5 android:layout_height="wrap_content"

6 android:background="#000" >

7

9 android:layout_width="wrap_content"

10 android:layout_height="wrap_content"

11 android:layout_gravity="center"

12 android:layout_margin="5dip"

13 android:background="#000"

14 android:text="Back"

15 android:textColor="#fff" />

16

18 android:layout_width="0dip"

19 android:layout_height="wrap_content"

20 android:layout_gravity="center"

21 android:layout_weight="1"

22 android:gravity="center"

23 android:text="Title Text"

24 android:textColor="#fff"

25 android:textSize="24sp" />

26

28 android:layout_width="wrap_content"

29 android:layout_height="wrap_content"

30 android:layout_gravity="center"

31 android:layout_margin="5dip"

32 android:background="#000"

33 android:text="Edit"

34 android:textColor="#fff" />

35

接下来如果不用设置响应事件的话,直接在需要引用该控件的布局文件中写入这个句代码就可以。

1

3 android:layout_width="match_parent" android:layout_height="match_parent" >

4

5

如果要设置响应事件的话就进行下一步

第二步:创建一个Topbar类继承布局类,通过获得title布局文件中的需要设置响应事件的控件的id来设置响应事件。

示例代码:

1 public class TitleLayout extendsLinearLayout {2

3 publicTitleLayout(Context context, AttributeSet attrs) {4 super(context, attrs);5 LayoutInflater.from(context).inflate(R.layout.title, this);6 Button titleBack =(Button) findViewById(R.id.title_back);7 Button titleEdit =(Button) findViewById(R.id.title_edit);8 titleBack.setOnClickListener(newOnClickListener() {9 @Override10 public voidonClick(View v) {11 Toast.makeText(getContext(), "You clicked Back button",12 Toast.LENGTH_SHORT).show();13 }14 });15 titleEdit.setOnClickListener(newOnClickListener() {16

17 @Override18 public voidonClick(View v) {19 Toast.makeText(getContext(), "You clicked Edit button",20 Toast.LENGTH_SHORT).show();21 }22 });23 }24 }

第三部:在布局文件中这样设置:

1

3 android:layout_width="match_parent"

4 android:layout_height="match_parent" >

5

7 android:layout_height="wrap_content">

8

9

10

就完成了所有需要的功能

注意控件需要写入完整的包名!

993679b1a196566065f1daf05caecdaf.png   

b1de0ca3a09e0bcdefb2e38ee31b2eb9.png

如果有什么错误,或者我理解错误或不当的,恳请大家纠正,谢谢!嘻嘻嘻~

原文:http://www.cnblogs.com/xiaolai1995/p/6515520.html

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐