Android自定义控件

本文介绍如何使用XML和自定义View创建一个简单的标题栏布局,包括按钮和文本视图,并展示了如何将该自定义布局应用于应用程序中。

新建一个布局 title.xml 代码如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#000">
    <Button
        android:id="@+id/button_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="back"
        android:background="#fff"
        android:textColor="#000"/>
    <TextView
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Title"
        android:textColor="#fff"
        android:textSize="24sp"/>
    <Button
        android:id="@+id/button_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dip"
        android:background="#fff"
        android:text="Edit"
        android:textColor="#000"/>


</LinearLayout>

在xml中添加< include layout=”@layout/title”/>

新建一个TitleLayout继承LinearLayout,代码如下
首先重写LinearLayout中的带两个参数的构造函数
布局中引入TitleLayout控件就会调用这个构造函数
然后在构造函数中对标题栏布局进行动态加载,需要借助LayoutInfater来进行实现。通过LayoutInfater的from()方法可以构造出一个LayoutInfater对象,调用inflate()方法动态加载一个布局文件
inflate方法需要两个参数 一是id 二是加载好的布局文件再添加一个父布局,这里我们指定为TitleLayout 所以传入this

public class TitleLayout extends LinearLayout {
    public  TitleLayout(Context context, AttributeSet attrs){
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.table_layout,this);
    }
}

再布局文件中添加这个自定义控件 修改xml中的代码

 <com.example.kingshan.uiwidgettest.TitleLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 <com.example.kingshan.uiwidgettest.TitleLayout>

然后就可以注册点击响应事件

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值