Skip to content Skip to sidebar Skip to footer

Adding Back Button And Override OnBackPressed

I want to add back arrow in my activity,and override back pressed to just doing 'back' function,line button on my device.Can I do this without implementing parent activityA to my A

Solution 1:

make sure to set your activity or fragment in manifest

 assert getSupportActionBar() != null;
 getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and set this code in your manifest file for your fragment or activity

<activity android:name=".yourCurrentFragmentOrActivity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".whichActivityYouWantToGoBack" />
</activity>

your back arrow only work when you set parent activity for it. and there is no need for onBackPressed Event

and your second Answer:-

you extend actionBarActivity that meant your target sdk version is 21, if you want to use appCompat theme then you have to extend AppCompatActivity, and for that your target sdk version should be 22 or 23. and if your platform plugin and sdktool is fully upgraded then you dont have to set anything on your own, it will automatically set everything. so just upgrade your sdk and platform plugin. you can check mine

:updated plugin and sdk version

and its latest till now


Solution 2:

Try

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

May it help...


Solution 3:

use app widget toolbar in xml and copy the following code in your java file.

    Toolbar toolbar=(Toolbar)findviewbyId(R.id.toolbar);

if(toolbar!=null) {

setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

}

// and call method:

@Override

public boolean onOptionsItemSelected(MenuItem item)
{
onBackPressed();
return true;
}

Post a Comment for "Adding Back Button And Override OnBackPressed"