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

先写一个.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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值