Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Fragment by tag name in Container

I have a relative layout and i am adding fragment in that relative layout. Like this

     HomeFragment mHomeFragment = new HomeFragment();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();

    if(mHomeFragment!=null&& mHomeFragment.isAdded()){

        fragmentTransaction.show(mHomeFragment);

    }else {

        fragmentTransaction.add(R.id.order_container,mHomeFragment,"Search");


    }
    fragmentTransaction.commit();

I also have a text view where i have to display the name of fragment i added in the relative layout. Like search in case. How to get the name of fragment added in my relative layout suppose with id = R.id.order_container

like image 213
Bora Avatar asked Jun 04 '13 13:06

Bora


People also ask

What is backstack in Fragment?

Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.

What is findFragmentByTag?

This method allows you to retrieve the instance of a previously added fragment with the given tag regardless of the container it was added to.

How do you find current active fragments?

To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.


2 Answers

you can retrieve a Fragment by tag through

Fragment fragment = getFragmentManager().findFragmentByTag("yourstringtag");

then you can check if your fragment is instace of HomeFragment

if (fragment instanceof HomeFragment) {
}
like image 81
Blackbelt Avatar answered Oct 14 '22 08:10

Blackbelt


Fragment fragment = getFragmentManager().findFragmentById(R.id.order_container);
String tag = (String) fragment.getTag();
like image 31
Ken Wolf Avatar answered Oct 14 '22 07:10

Ken Wolf