Find Fragment by tag name in Container

2020-02-01 01:36发布

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

6条回答
不美不萌又怎样
2楼-- · 2020-02-01 01:46

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) {
}
查看更多
趁早两清
3楼-- · 2020-02-01 01:47
getSupportFragmentManager().findFragmentById(R.id.container).getClass().getName();
查看更多
成全新的幸福
4楼-- · 2020-02-01 01:50
Fragment fragment = getFragmentManager().findFragmentById(R.id.order_container);
String tag = (String) fragment.getTag();
查看更多
你好瞎i
5楼-- · 2020-02-01 01:51

If you want to get the tag of a fragment you can use the getTag() method. This probably isn't going to be the nicest way to achieve what you are looking to do.

http://developer.android.com/reference/android/app/Fragment.html#getTag()

If you have several fragments and you will change them around, consider using an adapter.

查看更多
Viruses.
6楼-- · 2020-02-01 01:59

You can use findFragmentById in FragmentManager

getFragmentManager().findFragmentById(R.id.order_container)
查看更多
淡お忘
7楼-- · 2020-02-01 02:10

You want the name?? You can get your fragment using the ID and doing:

fragment.getClass().getName();

is it what you want? Or you can use:

fragment.getTag();

it's returns the tag name of the fragment, if specified.

查看更多
登录 后发表回答