android学习笔记——创建自定义控件

来源:互联网 发布:济南公交 大数据 编辑:程序博客网 时间:2024/05/22 05:02
先写一个.XML的布局文件,将你要使用的页面写好,方便之后使用。
这里用一个简单的布局提供展示就好。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <Button
        android:id="@+id/title_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back"
        android:layout_margin="5dip"
        />
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/title_text"
        android:text="Title Text"
        android:textSize="25sp"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="1"
        />
    <Button
        android:id="@+id/title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:text="Edit"
        />
</LinearLayout>
在编写好title.xml文件后,编写TitleLayout继承自LinearLayout,重写LinearLayout中的带有两个参数的构造函数,这样在布局中引入TitleLayout控件的时候就会调用这个构造函数。在构造函数中对标题栏进行动态的加载,需要借助LayoutInflater的动态加载方式
看代码
public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.titlethis);
        //在这里可以对布局中的控件进行加载,并且可以写一些方法来满足特定的需求  
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();
    }
});
 
    }
}

之后我们需要在activity_main.xml中进行一个注册,这样这个TitleLayout才能用的上
<com.example.yawen_li.mlayout.TitleLayout
    android:layout_width="match_parent"
   android:layout_height="match_parent"></com.example.yawen_li.mlayout.TitleLayout>
要记得,在添加自定义控件的时候我们需要指明控件的完整类名,包名,这些都是不可以省略的。

总结一下,之所以要自定义出控件,并且对该控件的活动进行抽象到一起,就是为了方便复用,同一个功能点虽然在不同的页面中,但是我们在实际编写的时候要对其进行拆分与合并,尽力提高代码的复用率,别有太高的冗余,省去很多编写重复代码的工作。多用组合,少用继承原则。
0 0