本次以一個的定義title爲例
一、新建一個activity_title.xml 設計佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/back_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"
/>
<TextView
android:id="@+id/text_"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Title"
android:gravity="center"
/>
<Button
android:id="@+id/edit_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="edit"
/>
</LinearLayout>
佈局如下:
二、新建TitleLayout.kt類
重寫構造函數,按鈕點擊監聽事件:
package com.example.myapplication
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_title.view.*
class TitleLayout: LinearLayout{
constructor(content:Context, attrs: AttributeSet):super(content, attrs)
{
LayoutInflater.from(content).inflate(R.layout.activity_title,this)
back_btn.setOnLongClickListener {
Toast.makeText(content,"back",Toast.LENGTH_SHORT).show()
true
}
edit_btn.setOnLongClickListener {
Toast.makeText(content,"edit",Toast.LENGTH_SHORT).show()
true
}
}
}
三、在其它activity中加載自定義部件
<com.example.myapplication.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.example.myapplication.TitleLayout>
運行效果:
完。