自定义标题栏
无标题栏界面

创建标题栏布局
<?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/btn_back"
android:layout_width="wrap_content"
android:text="返回"
android:background="@drawable/back_bg"
android:layout_height="60dp" />
<TextView
android:id="@+id/tv_title"
android:layout_width="0dp"
android:text="标题"
android:gravity="center"
android:background="@drawable/title_bg"
android:layout_height="60dp"
android:layout_weight="1" />
<Button
android:id="@+id/btn_edit"
android:text="编辑"
android:background="@drawable/edit_bg"
android:layout_width="wrap_content"
android:layout_height="60dp" />
</LinearLayout>
使用include的方式引用标题栏
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="@layout/title_bar"/>
</LinearLayout>

自定义布局的方式创建标题栏
package com.example.myfiveapp
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
class TitleLayout(context: Context,attrs: AttributeSet) : LinearLayout(context,attrs) {
init {
LayoutInflater.from(context).inflate(R.layout.title_bar,this)
val btnBack = findViewById<Button>(R.id.btn_back)
btnBack.setOnClickListener {
val activity = context as Activity
activity.finish()
}
val btnEdit = findViewById<Button>(R.id.btn_edit)
btnEdit.setOnClickListener {
Toast.makeText(context,"编辑", Toast.LENGTH_SHORT).show()
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.myfiveapp.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
