Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restart fragment class when back button press

I have a fragment that is part of tab view. I want to restart this fragment when I press back button. but i don't know how to refresh it. i tried some codes like this: Restart fragment inside activity but it didn't work.

here is a code for detecting back button:

    @Override
public void onResume() {

    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                // handle back button




                return true;

            }

            return false;
        }
    });
}

here is a fragment class button:

public class MoviesFragment extends Fragment {

  static ListView list;


static String[] numbers_text = new String[] { "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine", "ten", "eleven",
        "twelve", "thirteen", "fourteen", "fifteen" };
String[] songs = new String[] { "1", "2", "3", "4", "5", "6", "7",
        "8", "9", "10", "11", "12", "13", "14", "15" };



MainCustomList adapter;




@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {



    View view = inflater.inflate(R.layout.fragment_movies, container, false);

    adapter = new MainCustomList(this.getActivity(), numbers_text);
         list=(ListView) view.findViewById(R.id.list);
         list.setAdapter(adapter);


         return view;
}

main:

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // on tab selected
    // show respected fragment view
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

 }
like image 302
user5508330 Avatar asked Nov 01 '15 11:11

user5508330


People also ask

How do you refresh a fragment after onBackPressed from activity?

You can override onBackPressed in Activity and call a function on corresponding fragment to reloadItems().

Which method is called when back button is pressed in fragment?

3. It is very important to first understand how onBackPressed() works by default for fragments... The answer is short: it first searches for any added fragment via addToBackStack, if there is one, it does exactly the same as popBackStack() to pop it, otherwise it does the default onBackPressed() for the activity.

Does fragment have onCreate?

onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.

How can we prevent back in fragment?

Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity: // Disable onBack click requireActivity(). onBackPressedDispatcher. addCallback(this) { // With blank your fragment BackPressed will be disabled. }


1 Answers

Use this code:

YourFragmentClass fragment = (YourFragmentClass) 
getFragmentManager().findFragmentById(R.id.your_fragment_container_id)

getFragmentManager().beginTransaction()
                    .detach(fragment)
                    .attach(fragment)
                    .commit();

& this will cause your fragment's OnCreateView method to be called again & refresh its layout.

UPDATE:

When using the Support Library, you could access your fragment this way:

int YOUR_FRAGMENT_POSITION = 2; // in your case you wanna access the 3rd fragment, 0 indexed

YourFragmentClass fragment = (YourFragmentClass) getSupportFragmentManager().getFragments().get(YOUR_FRAGMENT_POSITION);

And use the same code snippet above:

getSupportFragmentManager().beginTransaction()
                        .detach(fragment)
                        .attach(fragment)
                        .commit();

If you try to access your fragment via the PagerAdapter, you may end up with an IllegalStateException, telling you that the fragment has failed to save its state.

like image 144
Mohammed Aouf Zouag Avatar answered Nov 12 '22 13:11

Mohammed Aouf Zouag