自定义控件

2016-04-21  本文已影响267人  TTTqiu

一、控件和布局的继承结构



所有控件都是直接或间接继承自 View 的,所用的所有布局都是直接或间接继承自 ViewGroup 的。
View 是 Android 中一种最基本的 UI 组件,它可以在屏幕上绘制一块矩形区域,并能响应这块区域的各种事件,因此,我们使用的各种控件其实就是在 View 的基础之上又添加了各自特有的功能。而 ViewGroup 则是一种特殊的 View,它可以包含很多的子 View 和子 ViewGroup,是一个用于放置控件和布局的容器。


二、引入布局


新建一个布局 title.xml,修改 activity_main.xml 中的代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <include layout="@layout/title" />

</LinearLayout>

使用这种方式,不管有多少布局需要添加标题栏,只需一行include 语句就可以了。


三、创建自定义控件


引入布局的技巧确实解决了重复编写布局代码的问题,但是如果布局中有一些控件要求能够响应事件,还是需要在每个活动中为这些控件单独编写一次事件注册的代码。比如说标题栏中的返回按钮,其实不管是在哪一个活动中,这个按钮的功能都是相同的,即销毁掉当前活动。而如果在每一个活动中都需要重新注册一遍返回按钮的点击事件,无疑又是增加了很多重复代码,这种情况最好是使用自定义控件的方式来解决。

1. 新建 TitleLayout 继承自 LinearLayout,让它成为我们自定义的标题栏控件:
public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater.from(context).inflate(R.layout.title, this);
    }
}
2. 在布局文件中添加这个自定义控件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.example.uicustomviews.TitleLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </com.example.uicustomviews.TitleLayout>

</LinearLayout>

在添加自定义控件的时候需要指明控件的完整类名,包名在这里是不可以省略的。
重新运行程序,会发现此时效果和使用引入布局方式的效果是一样的。

3. 为标题栏中的按钮注册点击事件:
public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater.from(context).inflate(R.layout.title, this);

        Button titleBack = (Button) findViewById(R.id.title_back);
        Button titleEdit = (Button) findViewById(R.id.title_edit);
        titleBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity) getContext()).finish();
            }
        });

        titleEdit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "You clicked Edit button",Toast.LENGTH_SHORT).show();
            }
        });
    }
}
4. 这样的话,每当在一个布局中引入 TitleLayout,返回按钮和编辑按钮的点击事件就已经自动实现好了,省去了很多编写重复代码的工作。
上一篇 下一篇

猜你喜欢

热点阅读