自定义控件

本文介绍了如何在Android应用中创建自定义布局和控件。通过XML定义布局模板,并在Java代码中实现自定义控件类,使得界面设计更加灵活。文章详细展示了从创建到使用的全过程,包括按钮点击事件的添加。

1.自定义布局

新建一个title.xml的Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1">

 

    <Button
        android:id="@+id/title_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:text="Back"
        android:textColor="#fff"
        />

    <TextView
        android:id="@+id/title_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="24sp"
        android:layout_weight="1"
        android:text="Title Text"
        android:gravity="center" />

    <Button
        android:id="@+id/title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Edit"
        android:textColor="#fff"
        android:layout_gravity="center"
        />
</LinearLayout>

显示:

【Back】Title Text 【Edit】

 

在其他Layout中可以使用<include layout="@layout/title" />包含进去

 

2.自定义控件

第一步:新建控件类

public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title, this); //相当于findViewById,获得title.xml

 

第二步:

在MainActivity.xml中添加TitleLayout引用

<com.example.test.test.TitleLayout
        anroid:layout_width="match_parent"
        anroid:layout_height="wrap_content">

  </com.example.test.test.TitleLayout>

第三步:

在TitleLayout类中添加按钮点击事件

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_LONG).show();
            }
        });

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值