七、Android-自定义控件

79 阅读1分钟

7. 自定义控件

7.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:orientation="horizontal"
    >
​
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:id="@+id/backButton"
        android:text="Back"
        android:textColor="#ffffff"
        />
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:text="Title"
        android:gravity="center"
        android:textColor="#00ffff"
        android:textSize="24sp"
        />
​
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:id="@+id/editButton"
        android:text="Edit"
        android:textColor="#ffffff"
        />
​
</LinearLayout>

7.2 引入布局

<include layout="@layout/title"/>

7.3 创建自定义控件

新建TitleLayout继承于LinearLayout

class TitleLayout(context: Context, attrs: AttributeSet): LinearLayout(context, attrs) {
​
    init {
        val view = LayoutInflater.from(context).inflate(R.layout.title, this)
        val backButton = view.findViewById<Button>(R.id.backButton)
        val editButton = view.findViewById<Button>(R.id.editButton)
​
        backButton.setOnClickListener {
            val activity = context as? Activity
            activity?.finish()
        }
        editButton.setOnClickListener {
            Toast.makeText(context, "You clicked edit button", Toast.LENGTH_SHORT).show()
        }
    }
}

自定义控件引用在布局文件中:

    <com.example.uilayouttest.TitleLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>