经过一段时间我发现,主题选项是我代码中的主要问题以下是为我显示工具栏的正确方法
首先在 AndroidManifest 文件中你必须改变你的主题风格
Theme.AppCompat.Light.DarkActionBar
to
Theme.AppCompat.Light.NoActionBar
然后在您的活动 xml 中,您需要调用自己的工具栏,例如
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:id="@+id/toolbar"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:elevation="4dp"/>
然后这个工具栏应该在你的Java文件中被调用
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
对于显示 U 的工具栏,应检查 null 以避免 NullPointerException
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
对于主页活动返回添加此
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
或返回您想要的活动
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), YourActivity.class);
startActivityForResult(myIntent, 0);
return true;
}