I have two Activities: MainActivity and OtherActivity. A fragment in MainActivity launches the OtherActivity, but when I press the back button at the top, it returns me to the MainActivity instead of the fragment that launched the OtherActivity.
The end result is the enduser is sent back to the main screen instead of the fragment that they were using.
This is my manifest. I have set MainActivity to be the parent of OtherActivity:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OtherActivity"
android:parentActivityName="com.example.test.MainActivity" >
</activity>
In MainActivity, when a user clicks on a button, it loads a List fragment:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
button.findViewById(R.id.events).setOnClickListener(new View.OnClickListener() {
Fragment ef = new MyItemsFragment();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.content, ef, "my_fragment");
fragmentTransaction.commit();
});
}
public void callOtherActivity() {
Intent i = new Intent(this, OtherActivity.class);
this.startActivity(i);
}
When an item is clicked in the List Fragment, it launches OtherActivity. A lot of the code for this was auto-generated by android studio. I have changed some of it. In MyItemsRecyclerViewAdapter:
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onEventFragmentInteraction(holder.mItem);
MainActivity ma = (MainActivity) holder.mView.getContext();
ma.callOtherActivity();
}
}
});
}
Notice it calls ma.callOtherActivity()
, which is defined in MainActivity and will launch OtherActivity when an item is clicked in the list fragment.
This is OtherActivity:
public class OtherActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
}
}
Now, when I click on the back arrow button in OtherActivity, the app will just show MainActivity, and not the List fragment that the user last saw.
How can I make sure that on return from OtherActivity, the user will see the list fragment again for better user experience?
EDIT: There seems to be confusion about the 'back' button. Maybe they are the same, but I am talking about the one when switching Activities. It is not the back button used to exit the application. See image