Check fragment is presented in framelayout or not in android?

Sugan S picture Sugan S · Aug 26, 2013 · Viewed 13.5k times · Source

Hi friends I have two framelayout in movies.xml namely container, detail_screen.In container will add movies.xml which contains listview ,and in detail_screen will have expandable listview called movie_details.xml.Now want to check programatically in detail_screen is already fragment presented or not.if presented just want remove that fragment.I did by follwing and its working fine.

    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null) {
        getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentByTag("MyFragment")).commit();
}

but is there any other way to find whether fragment is presented or not in frame layout in android by programatically .Thanks in advance

Answer

Sugan S picture Sugan S · Aug 27, 2013

I founded the solution as follows.i.e before adding any fragments to details_screen just checking if already fragment is presented then popping it and then will add the new fragment.

if (getSupportFragmentManager().findFragmentById(R.id.detail_screen) != null) {

        getSupportFragmentManager().popBackStack();

            } //to do add fragment

hope it will work.