how to get a fragment added in an XML layout

2019-01-23 22:42发布

问题:

I have a layout which includes a fragment as follows:

<fragment
        android:id="@+id/mainImagesList"
        android:name="com.guc.project.ImagesList"
        android:layout_width="match_parent"
        android:layout_height="62dp"
        android:layout_below="@+id/addimagebutton"
        android:layout_weight="1"
        android:paddingTop="55dp" />

now, I need to get this fragment and cast it so I can manipulate it and the updates appear. How can i do so ?!

EDIT: I think I've managed to get the fragment, but when I change some variables, the changes don't appear !

回答1:

You can get the fragment instance as follows:

getSupportFragmentManager().findFragmentById(R.id.yourFragmentId)


回答2:

If the fragment is embedded in another fragment,you need getChildFragmentManager but not getFragmentManager. For example, in layout xml define the fragment like this:

<fragment 
    android:name="com.aventlabs.ChatFragment"
    android:id="@+id/chatfragment"
    android:background="#ffffff"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:layout_marginTop="50dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp" />

in Code, you can get the fragment instance like this:

FragmentManager f = getChildFragmentManager();
FragmentTransaction transaction = f.beginTransaction();
chatFragment = f.findFragmentById(R.id.chatfragment);

if (chatFragment != null) {
   transaction.hide(chatFragment);
}
transaction.commit();


回答3:

I did exactly the same in android and the simplest way to do this in using interfaces. I had an activity with 6 fragments and i needed to update only 3 of them.

I use this

    final Integer numeroFragments = ((PagerAdapterOfe) mViewPager.getAdapter()).getCount();

    for (int i=0; i<numeroFragments; i++) {
        Object fragment = ((PagerAdapterOfe) mViewPager.getAdapter()).getItem(i);

        // If the fragment implement my interface, update the list
        if (fragment instanceof IOfertaFragment){
        ((IOfertaFragment) fragment).actualizaListaOfertas();
        }
    }

Where, PageAdapterOfe is my activity fragments adapter. I loop all of my fragments and search for those that implement my interface, when i found one, I execute the method defined by my interface and that is!

I use this code inside the activity that holds all the fragments, in response a broadcast signal, you can put it where you need.

The interface:

public interface IOfertaFragment {

    public void actualizaListaOfertas();
}


回答4:

You can find the fragment using findFragmentById (if you know the component it is included in) or by findFragmentByTag (if you know its tag)

I don't know which variables you want to update, but you can replace the fragment with another fragment using the FragmentTransaction API.

See http://developer.android.com/guide/components/fragments.html for examples.