Psypher
Psypher

Reputation: 10839

Fragment hiding after back button

I have added a fragment inside an activity, by using below code:

    FragmentManager fragmentManager=getFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    PreferenceFragment preferencefragment=new Preferencefragment();
    fragmentTransaction.add(R.id.maincontainer, preferencefragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

Layout File:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<DigitalClock
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/digitalClock"
    android:layout_gravity="center"
    android:textColor="@color/appcolor"
    android:layout_centerHorizontal="true"
    style="@android:style/TextAppearance.DeviceDefault.Large"
    android:textSize="45dp"/>
<TimePicker
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/timePickersms" />

<FrameLayout
    android:id="@+id/maincontainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

The activity has digital clock and timepicker and below that the fragment gets displayed, now when I click on back button first the fragment disappears and later the previous activity is displayed. How can the previous activity be displayed at one shot?

The next question I have is how can I refresh the fragment when a button is pressed on the screen?

Upvotes: 3

Views: 3741

Answers (1)

Ankit Popli
Ankit Popli

Reputation: 2837

addToBackStack(null) adds the fragment to back stack which is automatically popped out when back is pressed.

So you can fix this by two methods (whichever suits you):

remove addToBackStack(null)

OR

add the following code to your activity:

@Override
public void onBackPressed(){
    finish();
}

EDIT:

As far as refreshing of fragment is concerned, you have two options again: First one is simply replace the old fragment by the older one. Second one is you can maintain a object of your fragment and have setter/getter functions for updating the data inside fragment.

Upvotes: 9

Related Questions