在这种情况下,您通常会:
-
拥有并包含片段的活动和布局,我们称之为FragmentOwnerActivity。kt和fragment\u owner\u布局。xml
-
一个派生自Fragment的类和与之相关的布局,让我们称它们为MyFragment。kt和my\u fragment\u布局。xml
要在片段中启用工具栏,您需要将以下内容放到my\u fragment\u布局中。xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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/someid"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyFragment">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="0dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="0dp"
>
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="@attr/actionBarSize"
android:background="@attr/colorPrimary"
android:contentInsetEnd="0dp"
android:contentInsetLeft="0dp"
android:contentInsetRight="0dp"
android:contentInsetStart="0dp"
android:elevation="2dp"
app:contentInsetEnd="0dp"
app:contentInsetLeft="0dp"
app:contentInsetRight="0dp"
app:contentInsetStart="0dp"
>
<TextView
android:id="@+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/toolbar_title"
android:textSize="22sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
在MyFragment中。kt您需要启用工具栏:
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(activity as AppCompatActivity).setSupportActionBar(view?.findViewById(R.id.my_toolbar))
在FragmentOwnerActivity中。kt您需要膨胀特定于片段的菜单和处理菜单单击事件
// You'll need to create an xml with a menu for your fragment
// and then use it in inflate function below
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.my_fragment_menu_id, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle item selection
when (item.getItemId()) {
R.id.menu_item1_id -> {
doMenuItem1()
return true
}
R.id.menu_item2_id -> {
doMenuItem2()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
最后,您的fragment\u owner\u布局。xml只是控制其他框架的FrameLayout元素
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyFragmentOwner"/>