我的主要活动是这样的:
class MainActivity extends AppCompatActivity {
ActivityMainBinding uiBinding;
@Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
uiBinding = ActivityMainBinding.inflate(getLayoutInflater());
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
样式.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowAnimationStyle">@null</item>
<item name="android:spinnerItemStyle">@style/mySpinnerItemStyle</item>
</style>
<style name="mySpinnerItemStyle" parent="@android:style/Widget.Holo.DropDownItem.Spinner">
<item name="android:textColor">@android:color/black</item>
</style>
</resources>
和AndroidManifest.xml
<application
android:name=".MyApp"
android:allowBackup="false"
android:fullBackupContent="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
tools:replace="android:allowBackup"
android:theme="@style/AppTheme">
活动运行良好,没有崩溃。除了一件事:标题栏上的后退按钮丢失了?这是怎么回事?
确保在 onCreate() 中调用 setDisplayHomeAsUpEnabled(true) 和 setSupportActionBar(toolbar)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
并添加上面的行以在按下后退图标时关闭屏幕。