自定义view-自定义布局中引入布局xml

其实自定义这种引入布局的view的好处就是将Activity中view的处理交给自定义view简化了Activity的代码处理,具体步骤如下。

1.首先创建需要引入布局的xml代码如下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    >
    <ImageView
        android:id="@+id/image_jian"
        android:layout_marginTop="2dp"
        android:src="@drawable/clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/editText"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@+id/image_jian"
        android:includeFontPadding="false"
        android:text="11"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

2.之后根据我们需要自定义的内容编写自定义布局逻辑处理代码如下

public class MyChildView extends LinearLayout {
    ImageView image_jian;
    EditText editText;

    public MyChildView(Context context) {
        this(context, null);
    }

    public MyChildView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.item_child, this);
        editText = (EditText) findViewById(R.id.editText);
        image_jian = (ImageView) findViewById(R.id.image_jian);
        image_jian.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                editText.setText("");
            }
        });
    }
}

关键代码LayoutInflater.from(context).inflate(R.layout.item_child, this);这样的话就将布局引入了我们自定义控件中就可以处理控件的逻辑了
调用也是是跟简单的代码如下

    <com.testview.testChlidView.MyChildView
        android:layout_marginTop="30dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值