Android 创建自定义控件

创建自定义控件

Android 布局中很多时候系统自带的控件不能满足我们的需求
需要使用自定义控件。

按照以下三个步骤,可以自定义控件:以创建自定义titlebar控件为例
准备工作:创建一个app案例工程,不在赘述。

效果图:

TitleBar

1. 创建自定义控件对应的对象
  • 重写构造方法
  • 加载布局文件
  • 设置监听事件

public class TitleBar extends LinearLayout implements View.OnClickListener {
    private Button bt_title_back;
    private Button bt_title_edit;
    private Button  tv_title_text;

    private Context mycontext;
// 在此构造方法中初始化视图
    public TitleBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.mycontext = context;

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

        bt_title_back = (Button) findViewById(R.id.bt_title_back);
        bt_title_edit = (Button) findViewById(R.id.bt_title_edit);

        bt_title_back.setOnClickListener(this); //通过实现监听接口的方式设置监听
        bt_title_edit.setOnClickListener(this);


    }
//监听方法
    @Override
    public void onClick(View v) {
        if(v==bt_title_back) {
            Toast.makeText(mycontext, "返回", Toast.LENGTH_SHORT).show();
        }else if(v ==bt_title_edit) {
            Toast.makeText(mycontext, "编辑", Toast.LENGTH_SHORT).show();
        }
    }
}
2. 创建自定义控件对应的布局件

布局视图:
TitleBar

布局文件:diy_title.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="wrap_content"
    android:background="@android:color/darker_gray"
    android:orientation="horizontal">


    <Button
        android:id="@+id/bt_title_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="返回" />

    <TextView
        android:id="@+id/tv_title_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="标题栏"
        android:textSize="30sp" />

    <Button

        android:id="@+id/bt_title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="编辑" />


</LinearLayout>
3. 主Activiy中的布局文件中使用 自定义视图:activity_main.xml
<com.example.a02diycontroller.ui.TitleBar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
></com.example.a02diycontroller.ui.TitleBar>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值