关于创建自定义控件的那些事(笔记)

  1. public class TitleLayout extends LinearLayout {  
  2.     public TitleLayout(Context context, AttributeSet attrs) {  
  3.         super(context, attrs);  
  4.         LayoutInflater.from(context).inflate(R.layout.title, this);  
  5.     }   

  首先我们重写了 LinearLayout 中的带有两个参数的构造函数,在布局中引入 TitleLayout 控件就会调用这个构造函数。然后在构造函数中需要对标题栏布局进行动态加载,这就要借助 LayoutInflater 来实现了。通过 LayoutInflater 的 from() 方法可以构建出一个 LayoutInflater 对象,然后调用 inflate() 方法就可以动态加载一个布局文件,inflate() 方法接收两个参数,第一个参数是要加载的布局文件的 id,这里我们传入 R.layout.title,第二个参数是给加载好的布局再添加一个父布局,这里我们想要指定为 TitleLayout,于是直接传入 this。

        现在自定义控件已经创建好了,然后我们需要在布局文件中添加这个自定义控件,修改 activity_main.xml 中的代码,如下所示:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent" >  
  4.   
  5.       <com.example.uicustomviews.TitleLayout  
  6.         android:layout_width="match_parent"  
  7.         android:layout_height="wrap_content"  
  8.         ></com.example.uicustomviews.TitleLayout>  
  9.   
  10. </LinearLayout>  

       添加自定义控件和添加普通控件的方式基本是一样的,只不过在添加自定义控件的时候我们需要指明控件的完整类名,包名在这里是不可以省略的。

        然后我们俩尝试为标题栏中的按钮注册点击事件,修改 TitleLayout 中的代码,如下所示:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class TitleLayout extends LinearLayout {  
  2.   
  3.     public TitleLayout(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(new OnClickListener() {  
  9.             @Override  
  10.             public void onClick(View v) {  
  11.                 ((Activity) getContext()).finish();  
  12.             }  
  13.         });  
  14.         titleEdit.setOnClickListener(new OnClickListener() {  
  15.             @Override  
  16.             public void onClick(View v) {  
  17.                 Toast.makeText(getContext(), "You clicked Edit button", Toast.LENGTH_SHORT).show();  
  18.             }  
  19.         });  
  20.     }
  21. }  

        首先还是通过 findViewById() 方法得到按钮的实例,然后分别调用 setOnClickListener() 方法给两个按钮注册了点击事件,当点击返回按钮时销毁掉当前的 Activity,当点击编辑按钮时弹出一段文本。

        这样的话,每当我们在一个布局中引入 TitleLayout,返回按钮和编辑按钮的点击事件就已经自动实现好了,也是省去了很多编写重复代码的工作。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值