美文网首页
自定义控件

自定义控件

作者: TTTqiu | 来源:发表于2016-04-21 16:10 被阅读267次

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



所有控件都是直接或间接继承自 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);
    }
}
  • 首先重写了 LinearLayout 中的带有两个参数的构造函数,在布局中引入 TitleLayout 控件就会调用这个构造函数。
  • 然后在构造函数中需要对标题栏布局进行动态加载,通过 LayoutInflater 的 from() 方法可以构建出一个 LayoutInflater 对象,然后调用 inflate() 方法就可以动态加载一个布局文件。
  • inflate() 方法接收两个参数,第一个是要加载的布局文件的 id,这里传入 R.layout.title,第二个是给加载好的布局再添加一个父布局,这里想要指定为 TitleLayout,于是直接传入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,返回按钮和编辑按钮的点击事件就已经自动实现好了,省去了很多编写重复代码的工作。

相关文章

网友评论

      本文标题:自定义控件

      本文链接:https://www.haomeiwen.com/subject/zdmtrttx.html