Android自定义控件基础

2023-05-16

采用自定义控件解决重复编写代码的问题.
总共分三步.
 1.写好一个自定义模板布局.(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="#121212">

        <Button
            android:id="@+id/btn_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="back"
            android:textColor="#fff" />

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

        <Button
            android:id="@+id/btn_edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="Edit"
            android:textColor="#fff" />
    </LinearLayout>
 2.定义一个类继承LinearLayout,并且在我们自己定义的那个类的构造方法中实现各种逻辑(例如设置点击事件)
public class TitleLayout extends LinearLayout {

    public TitleLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title, this);
        Button back_id = (Button) findViewById(R.id.btn_back);
        back_id.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                ((Activity)getContext()).finish();
            }
        });
        View edit_id = findViewById(R.id.btn_edit);
        edit_id.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext().getApplicationContext(), "您点击了edit", Toast.LENGTH_LONG).show();
            }
        });
    }
}

3.在父亲布局中载入模板布局 (注意引入时要用完整的包名)

 <com.example.mengxin.layout.TitleLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       >
   </com.example.mengxin.layout.TitleLayout>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android自定义控件基础 的相关文章

随机推荐