Android自定义UI控件(简单方便版,但不灵活)

智慧并不产生于学历,而是来自对于知识的终生不懈的追求。这篇文章主要讲述Android自定义UI控件(简单方便版,但不灵活)相关的知识,希望能为你提供帮助。
这种方法的优点就是简单,容易理解,适合开发一些不经常用到的自定义UI控件
缺点就是比较不灵活,如果其他应用想使用这个控件的话得改很多
简单来说,这个方法是用来做成品的,下一篇的方法是用来做模板的。
先看成品,这是一个标题栏控件:

Android自定义UI控件(简单方便版,但不灵活)

文章图片

 
由左右两个按钮和中一个TextView组成:
实现方法:
第一步:定义一个xml文件,用来设计你自定义控件的雏形
【Android自定义UI控件(简单方便版,但不灵活)】示例代码:文件名为title
1 < ?xml version="1.0" encoding="utf-8"?> 2 < LinearLayout 3xmlns:android="http://schemas.android.com/apk/res/android" 4android:layout_width="match_parent" 5android:layout_height="wrap_content" 6android:background="#000" > 7< Button 8android:id="@+id/title_back" 9android:layout_width="wrap_content" 10android:layout_height="wrap_content" 11android:layout_gravity="center" 12android:layout_margin="5dip" 13android:background="#000" 14android:text="Back" 15android:textColor="#fff" /> 16< TextView 17android:id="@+id/title_text" 18android:layout_width="0dip" 19android:layout_height="wrap_content" 20android:layout_gravity="center" 21android:layout_weight="1" 22android:gravity="center" 23android:text="Title Text" 24android:textColor="#fff" 25android:textSize="24sp" /> 26< Button 27android:id="@+id/title_edit" 28android:layout_width="wrap_content" 29android:layout_height="wrap_content" 30android:layout_gravity="center" 31android:layout_margin="5dip" 32android:background="#000" 33android:text="Edit" 34android:textColor="#fff" /> 35 < /LinearLayout>

接下来如果不用设置响应事件的话,直接在需要引用该控件的布局文件中写入这个句代码就可以。
< include layout="@layout/title" />
1 < LinearLayout 2xmlns:android="http://schemas.android.com/apk/res/android" 3android:layout_width="match_parent" android:layout_height="match_parent" > 4< include layout="@layout/title" /> 5 < /LinearLayout>

如果要设置响应事件的话就进行下一步
第二步:创建一个Topbar类继承布局类,通过获得title布局文件中的需要设置响应事件的控件的id来设置响应事件。
示例代码:
1 public class TitleLayout extends LinearLayout { 2 3public TitleLayout(Context context, AttributeSet attrs) { 4super(context, attrs); 5LayoutInflater.from(context).inflate(R.layout.title, this); 6Button titleBack = (Button) findViewById(R.id.title_back); 7Button titleEdit = (Button) findViewById(R.id.title_edit); 8titleBack.setOnClickListener(new OnClickListener() { 9@Override 10public void onClick(View v) { 11Toast.makeText(getContext(), "You clicked Back button", 12Toast.LENGTH_SHORT).show(); 13} 14}); 15titleEdit.setOnClickListener(new OnClickListener() { 16 17@Override 18public void onClick(View v) { 19Toast.makeText(getContext(), "You clicked Edit button", 20Toast.LENGTH_SHORT).show(); 21} 22}); 23} 24 }

第三部:在布局文件中这样设置:
1 < LinearLayout 2xmlns:android="http://schemas.android.com/apk/res/android" 3android:layout_width="match_parent" 4android:layout_height="match_parent" > 5< com.example.diy.TitleLayout 6android:layout_width="match_parent" 7android:layout_height="wrap_content"> 8< /com.example.diy.TitleLayout> 9 10 < /LinearLayout>

就完成了所有需要的功能
注意控件需要写入完整的包名!
Android自定义UI控件(简单方便版,但不灵活)

文章图片
   
Android自定义UI控件(简单方便版,但不灵活)

文章图片

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


    推荐阅读