'handling back button android
I have a problem while hitting the back button on an activity, in particular, the back button on the activity closes the application and destroys all the activities, I want to go back in the stack, and in the previously called activity when hitting the back button.
Here is my code:
ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
setSupportActionBar(ChatToolBar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
My AndroidManifest.xml:
<activity
android:name=".ChatActivity"
android:parentActivityName=".ProfileActivity" />
I also tried:
<activity
android:name=".ChatActivity"
android:parentActivityName=".ProfileActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ProfileActivity" />
</activity>
Where should be the problem?
Solution 1:[1]
I just solved it with this code:
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
int id = item.getItemId();
if (id == android.R.id.home)
{
SendUserToMainActivity();
}
return super.onOptionsItemSelected(item);
}
private void SendUserToMainActivity()
{
Intent mainIntent = new Intent(ChatActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(mainIntent);
finish();
}
Solution 2:[2]
you can add button back in action bar
in mainfest.xml
<activity .ActivityB" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ActivityA" />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zain |
Solution 2 | sayed mhmd |