Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a fragment added in an XML layout

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 !

like image 682
ahmed Avatar asked Dec 17 '12 09:12

ahmed


People also ask

How do I show fragments in activity XML?

You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

Which layout is used to implement fragments?

A FrameLayout is used because it's going to be the container of the Fragment. In other words, the Fragment will be stored inside of this layout.

What is a fragment layout?

A Fragment is a combination of an XML layout file and a java class much like an Activity . Using the support library, fragments are supported back to all relevant Android versions. Fragments encapsulate views and logic so that it is easier to reuse within activities.


2 Answers

You can get the fragment instance as follows:

getSupportFragmentManager().findFragmentById(R.id.yourFragmentId)
like image 184
赏心悦目 Avatar answered Oct 22 '22 19:10

赏心悦目


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();
like image 22
ldehai Avatar answered Oct 22 '22 18:10

ldehai