子活动中缺少工具栏



我正在尝试创建一个简单的Android应用程序,它包含一个用户定义的列表。主活动将显示与列表相关联的一些内容,并且将使用一个单独的活动来让用户管理列表的内容。

MainActivity设置Toolbar并启动辅助活动:

MainActivity.kt:

class MainActivity : AppCompatActivity() {
private val toolbar by lazy { findViewById<Toolbar>(R.id.toolbar) }
private val drawerLayout by lazy { findViewById<DrawerLayout>(R.id.drawerLayout) }
// This button is defined somewhere deep in `activity_main.xml`
private val manageLocationsButton by lazy { findViewById<Button>(R.id.manage_locations) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Connect the action bar and the navigation drawer
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
val toggle =
ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.drawerOpen,
R.string.drawerClose
)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
manageLocationsButton.setOnClickListener {
val intent = Intent(this, ManageLocationsActivity::class.java)
startActivity(intent)
}
}
}

activity_main.xml:

<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:titleTextColor="@android:color/white" />
<androidx.drawerlayout.widget.DrawerLayout
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- contents -->
</androidx.drawerlayout.widget.DrawerLayout>
</LinearLayout>

辅助活动没有做任何特别的事情:ManageLocationsActivity.kt:

class ManageLocationsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_manage_locations)
// The code below will crash, as supportActionBar == null
// supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
}

我希望子活动继承工具栏,但这并没有发生。启动子活动时,该活动中没有任何工具栏。我的应用程序使用Theme.AppCompat.Light.NoActionBar,这对于使用Toolbar是必要的,而不是ActionBar(这是AFAIK的现代方式(

如何使子活动继承操作栏并使用默认的后退导航?

如果只有一个活动和多个片段,则可以使用这种方法。但若你们有多个像你们一样的活动,你们必须在所有活动的布局中都有工具栏
如果您有多个活动,并且不想将工具栏复制并粘贴到所有活动,只需为工具栏创建单独的布局,并将其包含在您希望收费条显示的布局中。

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

最新更新