anta40
anta40

Reputation: 6743

Why back button on title bar isn't shown

My main activity is this:

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);
        }
    }
}

styles.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>

And 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">

The activity runs fine, no crash. Except one thing: the back button on title bar is missing? What's wrong here?

Update: Did some changes to MainActivity:

 protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       uiBinding = ActivityMainBinding.inflate(getLayoutInflater());
       requestWindowFeature(Window.FEATURE_ACTION_BAR);
       setContentView(uiBinding.getRoot());


       ActionBar actionBar = getSupportActionBar();
       Toolbar toolbar = findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);
       actionBar.setDisplayHomeAsUpEnabled(true);
}

Aaannnn.... it crashes:

java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.xxx.xxx.xxx.debug/xxx.xxx.xxx.xxx.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

Why the actionBar object is null?

Upvotes: 1

Views: 40

Answers (0)

Related Questions