Android自定义标题栏控件

2021-06-23  本文已影响0人  别看后面有人

1、新建TitleLayout继承自LinearLayout,让它成为自定义控件,代码如下:

class TitleLayout(context: Context,attrs:AttributeSet): LinearLayout(context,attrs) {
    init {
        LayoutInflater.from(context).inflate(R.layout.title,this)
        titleBack.setOnClickListener {
            val activity=context as Activity
            activity.finish()
        }

        titleEdit.setOnClickListener {
            Toast.makeText(context,"click this",Toast.LENGTH_LONG).show()
        }
    }
}

TitleLayout接收的context参数实际上是一个Activity参数,在点击返回按钮的事件中,我们将它转换成Activity。kotlin中的类型强制转换使用关键字as。
2、定义布局文件,title文件

<?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">

    <Button
        android:id="@+id/titleBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:text="back" />

    <TextView
        android:id="@+id/titleContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="text" />

    <Button
        android:id="@+id/titleEdit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:text="edit" />
</LinearLayout>

3、引用自定义控件的时候,需要指明控件的完整包名,包名不能省略

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 <com.app.activitytest.TitleLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>
</LinearLayout>
上一篇 下一篇

猜你喜欢

热点阅读