自定义组件简单应用

自定义组件:

1.创建自定义组件 

2.引入组件

//1.新建TitleLayout.java

public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs) {
        super(context,attrs);
        LayoutInflater.from(context).inflate(R.layout.title,this);
        Button titleBack = (Button)findViewById(R.id.title_back);
        titleBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity)getContext()).finish();
            }
        });
        Button titleEdit = (Button) findViewById(R.id.title_Edit);
        titleEdit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(),"分享到朋友圈",Toast.LENGTH_SHORT).show();
            }
        });
    }
}
// 2. 布局文件

<?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:orientation="horizontal"
    android:background="#ff333333">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/title_back"
        android:text="返回"
        android:gravity="center"
        android:background="#ff333333"
        android:textColor="#ffffffff"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="新闻中心"
        android:gravity="center"
        android:layout_weight="1"
        android:id="@+id/title"
        android:textColor="#ffffffff"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/title_Edit"
        android:gravity="center"
        android:text="分享"
        android:background="#ff333333"
        android:textColor="#ffffffff"
        />
</LinearLayout>
// 3.在需要处引入

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    //引入------
    <com.example.myapplication1.TitleLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    //-------引入
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="产品"/>
</LinearLayout>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值