【学习笔记】Android自定义控件

本文是在学习郭霖大神的《第一行代码-Android》中关于“自定义控件”的总结。

相似的方法,如果新的方法没有什么特别的优势,我还是会用旧的方法。一直以来我都不理解在布局文件中使用包名作为一个控件,也不知道这种方法的好处,所以我从来不用。在以前接触的书中对自定义控件没有讲解,在我看的网上的Demo上,我也感觉不到自定义控件的优势,所以一直以来我还是用系统给的控件。我曾试图从网上搜索学习自定义控件,但是没有讲解很到位的。当我看到《第一行代码-Android》时,我做的第一件事情,就是找找有没有关于“用包名做控件”的介绍。我终于找到了。

自定义的布局能够实现更复杂、更符合我们期望的功能,当然也能提高我们的编程效率。

自定义控件是需要指定完整的类名的,所以我们先新建一个类TitleLayout继承自LinearLayout。

public class TitleLayout(Context context, AttributeSet attrs){
    public TitleLayout(Context context, AttributeSet attrs){
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title, this);
    }
}
在这个类中,我们重新了LinearLayout中的带两个参数的构造函数,在布局中引入TitleLayout控件就会调用这个构造函数。

现在自定义控件已经创建好了,现在我们需要在布局文件中添加这个自定义控件:

<pre name="code" class="java"><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
>
 
 







发布了78 篇原创文章 · 获赞 54 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/chjr1000/article/details/44003387