how to get a fragment added in an XML layout - android

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 !

You can get the fragment instance as follows:
getSupportFragmentManager().findFragmentById(R.id.yourFragmentId)

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();

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();
}

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.

If Fragment is included inside the layout file of Activity then it can be referenced by SupportFragmentManager like...
MyFragment myFragment= (MyFragment)getSupportFragmentManager().findFragmentById(R.id.FRAGMENTID)
If Fragment is included inside the layout file of another Fragment then it can be referenced by ChildFragmentManager like...
MyFragment myFragment= (MyFragment)getChildFragmentManager().findFragmentById(R.id.FRAGMENTID)

Related

How can I get Fragment from View?

I added some Fragment into a TableLayout and I want to manage them from my container Activity, so I used this:
Fragment fragment = (Fragment) tableLayout.getChildAt(i);
but getChildAt(int) returns a View and a View could NOT cast to Fragment
I don't understand why people are down-voting your question. Fragments can be very confusing at times, especially for beginners. To understand your problem, you must learn what is a Fragment and how they are used.
To start with, a View is something that has an existence on the screen. Examples include: TextView, EditText, Button, etc. They are placed inside "layouts" written in Xml or Java/Kotlin. These layouts are shown using an Activity.
Now, a Fragment is not a View. It does not have any existence on the screen at all. Instead, it's a class that simply manages a "layout" — kinda similar to an Activity. If you need the View returned by your Fragment's onCreateView(), you can directly use findViewById() within your Activity.
If you need a reference to your Fragment, there are two possible ways of doing this:
1) If you added the Fragment programmatically like this
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container_viewgroup, myFragment, FRAGMENT_TAG)
.commit();
You can use:
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
2) If you added the Fragment inside an XML layout like this:
<fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="#+id/fragmentContainer"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
You can use this:
getFragmentManager().findFragmentById(R.id.fragmentContainer);
Basically, each Activity has a FragmentManager class that maintains all the active Fragments, and there are two ways of finding them: Using a unique TAG that you pass while showing a fragment, or passing the container view-ID where the fragment was added.
For people looking how to actually get a reference to the Fragment object from a View there is now a method in FragmentManager called findFragment(View) (reference)
//in Java
FragmentManager.findFragment(view)
//in Kotlin there is an extension function
view.findFragment()
Be careful - it will throw an IllegalStateException if the view was not added via a fragments onCreateView.
You can not get a fragment like this. You will have to add fragment with a tag and retrieve it by that tag.
to add a fragment do following:
getFragmentManager().beginTransaction().add(R.id.container, fragment, "tagTofindFragment");
to get fragment:
fragment = getFragmentManager().findFragmentByTag("tagTofindFragment");
Here tagTofindFragment is that tag that should be unique among your fragments.

Fragment was unable to replace with fragment in viewpager

I'm working with fragments with ViewPager concept. I'm creating a diary app in which I'm using only one fragment which gets all updates from database and show in it. Until this everything is fine...According to my requirement when i click on a button in fragment i need to show another fragment which allows the user to store the images.
My problem is.....
--If i use replace method in fragments it was not replacing properly in the sense if A is fragment which consists of viewpager and B is a fragment i want to replace.
--Then if i use replace B is visible but A also appears under the fragment B
FragmentManager m=getActivity().getSupportFragmentManager();
FragmentTransaction ft = getActivity().getSupportFragmentManager()
.beginTransaction();
Demobutton demobutton = new Demobutton();
ft.replace(R.id.lay, demobutton);
ft.commit();
Hope you guys understand my problem. If you feel my question is incomplete please let me know that.
I have two suggestions depending on how you use the DemoButton Fragment:
1) Maybe your issue is with nested fragments. You get the FragmentManager from the activity but if the Demobutton is already part of an fragment use getChildFragmentManager() of the outer fragment instead.
2) From my experience when using a ViewPager with Fragments the PagerAdapter of the ViewPager should do all the fragment transactions. You could extend and overwrite the class FragmentPagerAdapter from the support library in order to get the correct fragment in your ViewPager when you need it.
I've developed a small example app that achieves this without overwriting native classes.
The point is to use a fragment as a container.
In your ViewPagerAdapter:
#Override
public Fragment getItem(int position) {
/*
* IMPORTANT: This is the point. We create a RootFragment acting as
* a container for other fragments
*/
if (position == 0)
return new RootFragment();
else
return new StaticFragment();
}
RootFragment layout should look like:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/root_frame" >
</FrameLayout>
You could review my complete explanation here: https://stackoverflow.com/a/21453571/1631136

Confused with remove Fragment

I have an Activity with a Button and a FrameLayout in its layout.
When I click the Button I add the fragment to the Activity's View.
If I add the fragment to the Back stack with addToBackStack() when I click the Back button it dissapears.
I want to achieve the same functionality by clicking again the Button.
My code is this :
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AddRemoveFragment Frag_A = new AddRemoveFragment();
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction transaction = fm1.beginTransaction();
if ( state == 0 ) {
Log.i(TAG, "inside IF");
state=1;
transaction.add(R.id.fragment_container_1, Frag_A);
transaction.addToBackStack(null);
transaction.commit();
} else {
state=0;
Log.i(TAG, "inside ELSE");
//transaction.replace(R.id.fragment_container_1, Frag_A);
transaction.remove(Frag_A);
transaction.commit();
}
}
});
Both remove() and hide() do nothing.
From the reference I don't understand something more specific. Just says it removes the fragment from the container. Isn't this what I want?Remove the fragment from FrameLayout?
Edit: hope it has nothing to do with the support library. I saw someone having some problems with that. Here
XML :
<?xml version="1.0" encoding="utf-8"?>
<Button
android:id="#+id/button_frag_1"
android:layout_width="124dp"
android:layout_height="wrap_content"
android:text="#string/button_text_1" />
<FrameLayout
android:id = "#+id/fragment_container_1"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button_frag_1"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/button_frag_1" >
</FrameLayout>
Edit 2: I changed the code inside the else statement from transaction.replace(R.id.fragment_container_1, Frag_A); to transaction.remove(Frag_A); but still got the same functionality.
For fragments, first of all you need to remember one thing:
If you added your fragment in your XML layout, then it can't be removed, it can only be shown using the .show() method and hidden using the .hide() method. If on the other hand you create an instance of your fragment in your code then you should add it using the .add() method or remove it using the .remove() method.
As regard to your question, I dont think you need to add your fragment to back stack if you want to remove your fragment using your button (unless you want to keep the functionality of removing it using the 'back' button).
In addition I don't think you need to use replace, from the documentation of replace:
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
It means that it replaces the content of the container with the new fragment, so all you do is remove your fragment and add it again.
You should .add() you fragment when you want to show it and .remove() it when you dont.
UPDATE:
Following you second question, when I say that you can add you fragment in your xml I mean that you can write this:
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/listfragment"
android:name="com.eadesign.yamba.TimeLineListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In your XML layout file inside your FrameLayout which is your fragment container, in this case you cant remove this fragment you can only hide it.
And just to clarify you will always have to provide some kind of layout which will be the container of your fragment/fragments.
as opposite to that you can do what your are doing in your code:
AddRemoveFragment Frag_A = new AddRemoveFragment();
transaction.add(R.id.fragment_container_1, Frag_A);
transaction.addToBackStack(null);
transaction.commit();
In this case the fragment can be removed.
UPDATE2:
Try to take this line: AddRemoveFragment Frag_A = new AddRemoveFragment(); outside of the setOnClickListener method scope. I think that your problem is the fact that you are creating a new instance of this fragment on every click of your button. In fact I would move this line FragmentManager fm1 = getSupportFragmentManager(); out side as well there is no need to get the instance of a SupportFragmentManager on each click of your button. You should do this once.

Implementing Fragments Androids

I am implementing fragments for the first time so please help me.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
android:id="#+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment"
android:id="#+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
I want that fragment having the id as 'list' should remain constant but the the fragment having id 'viewer' should be able to call different classes.
(Note that the classes extend Activity.)
My question is simple: I have four classes(Extending ACTIVITY). I want to divide the screen into two parts. The left Side remains constant which contains the listview. On list view's click I want to open my Class(Extending ACTIVITY), but only in the right portion(remaining screen).
It is a basic question. You should start from here. And this topic can help you also.
Fragments are like seperate acticities, so unless u make the changes the action on one fragment will not affect the other fragments.
Assuming u have a listview on the left fragment, in its activity place a onItemClickListener.
For each itemclick switch the activity on the right fragment.
Sample Code for the OnItemClick Event
Fragment fragment=new activity1();
fragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.frame2,fragment);
ft.commit();
In the above code segment activity1 is the new class want to attach to the right fragment. R.id.frame2 is the id of the framelayout that is used with the right fragment.
According to the android documentation of fragments:
A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
http://developer.android.com/guide/components/fragments.html
what i understood from your question is that you want to the content of your fragement viewer at run-time. a possible solution which i can suggest for this is:
Instead of your four classes extending Activity, extend Fragment, each having its own layout. Modify the main layout file to look something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
android:id="#+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
the FrameLayout will basically act as a container for your fragments, which you can dynamically load at run-time(by clicking the ListView). This tutorial will help you out with it:
http://developer.android.com/training/basics/fragments/fragment-ui.html
Hope my answer helps you in some way.
The Fragment class can be used many ways to achieve a wide variety of results. In its core, it represents a particular operation or interface that is running within a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own lifecycle, that lifecycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed.
MyFragment newFragment = new MyFragment();// MyFragment is a Fragment class
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fra,newFragment, tag);
transaction.addToBackStack(null);
transaction.commit();
sample code
in sample code change
ft.add(android.R.id.content,fragTwo, "tag");
to
ft.add(R.id.fra,fragTwo, "tag");
and add some code in detail.java
public void onStart() {
// TODO Auto-generated method stub
tv.setText(data);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.beginTransaction();
Fragment fragTwo = new MyFragment();
//String tag = getActivity().GetFragmentID();
Fragment f= fm.findFragmentById(getId());
ft.replace(R.id.fra,fragTwo, "tag");
ft.hide(f);
ft.commit();
}
});
super.onStart();
}

findFragmentById always returns null

I'm defining an ID for my fragment in the xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/test_fragment"
...
Then I add this fragment in the activity's onCreate method:
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();
This is all working fine. Replacing fragments and is also working.
Later I'm trying to retrieve this fragment by its ID in one of the activity's methods:
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);
Doing so leads to myFragment being null. Always.
When I try to do the same with tags instead of IDs I can retrieve the fragment by its tag without any problems:
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment");
fragmentTransaction.commit();
...
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");
Why can't findFragmentById find the fragment, but findFragmentByTag does so? Am I missing something?
R.id.test_fragment is not the ID of your fragment but the id of your LinearLayout
Calling add(int containerViewId, Fragment fragment) will add a fragment without a tag.
So or you use add(int containerViewId, Fragment fragment, String tag) and you get back your fragment using your tag (as an ID)
Use the <FrameLayout> tag as a container in your layout file. Later to replace the fragments from your activity dynamically, you can use the ID of the <FrameLayout> container to replace the fragments in your activity.
<FrameLayout
android:id="#+id/test_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/test_fragment"
it should be a fragment not a LinearLayout
<fragment android:name="com.example.yourfragment"
android:id="#+id/test_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I was using android.support.v4.app.Fragment in my layout while calling getFragmentManager() which actually searched for android.app.Fragment subclasses and I got null.
So the fix was to call getSupportFragmentManager() instead.
In general make sure the package of a fragment you are subclassing and using in your layout is the same returned by the corresponding FragmentManager which performs search.
Or, you should have instead used :
(MyFragment) getFragmentManager().findFragmentById(R.id.fragment_container);
R.id.test_fragment is your LinearLayout ID not your Fragment.
You can define and id on a fragment when it is inflated from an xml like in this sample http://developer.android.com/guide/topics/fundamentals/fragments.html#Adding
The reasons mentioned above are valid but another possible reason is that you are trying to search for the fragment while being in a fragment this also results in fragmentManager.findFragmentById to return null. We should use childFragmentManager.findFragmentById to find the fragment inside a fragment.
According to the official documentation.
public final androidx.fragment.app.FragmentManager getChildFragmentManager()
Return a private FragmentManager for placing and managing Fragments
inside of this Fragment.
FragmentB fragmentB =
(FragmentB) getSupportFragmentManager().findFragmentById(R.id.containerb);
if(fragmentB != null)
{
fragmentB.showuserResponse(msg);
}
Use container id as fragment id. And then check for null reference.
fragmentTransaction.add(R.id.fragment_container, myFragment);
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);
Please notice the difference.
You should pass R.id.fragment_container as the argument to findFragmentById, as you pass it to the add function, instead of R.id.test_fragment
By the way , according to the inner implementation of the two functions, it should be right that the id can be
that of its container view.

Categories

Resources