How to attach to parentView while using fragments? - android

I have followed this tutorial and its working great. In my fragment's view there are some buttons which I have some onClick assigned to. For example I have a button like:
<ImageButton
android:onClick="doSomething">
</ImageButton>
While creating the rootView I use the following code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
I did some googling and found out the last parameter is for attach to parentView and I have set it to true. But the parent view is container. Where does this container point to?
Where should I write the function 'doSomething'?

I did some googling and found out the last parameter is for attach to
parentView and I have set it to true.
Don't set it to true. In the onCreateView() you'll create the view for the fragment and return it and Android will attach that view to the layout on its own(what the documentation says).
Where does this container point to?
If not null it will be the layout where the fragment's view will be added, generally used for generating the proper LayoutParams for the newly inflated view.
Where should I write the function 'doSomething'?
As the buttons using the onClick attribute will be part of the fragment layout you should remove the onClick attribute from the layout and set the OnClickListener in code on the buttons. Android will search for the doSomething() method at the Activity level so you can't receive the on click event directly in the fragment.

Related

Android Fragment what container is it in onCreateView() method

I wonder what is container parameter in onCreateView(), cause when i inflate view to that container it make me wonder what viewGroup is this,is it a viewGroup from the activity that we will add a fragment to ? if it is true then why we need to attach it in inflate method cause i think we will add this fragment to the viewgroup of activity in activity's xml anyway.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_top,container,true);
return view;
}
The inflate() method takes three arguments:
The resource ID of the layout you want to inflate.
The ViewGroup to be the parent of the inflated layout. Passing the container is important in order for the system to apply layout
parameters to the root view of the inflated layout, specified by the
parent view in which it's going.
A boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during inflation.
For more refer here
To be more specific, I think the container is the FragmentContainerView in this example. Basically it's the resource id which you add your fragment to. For example, if we do
fragmentTransaction.add(R.id.container_view, fragment).commitNow();
Then the container is the ViewGroup identified by R.id.container_view.
Quoting the docs
container ViewGroup: If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view. This value may be null.

Are Views automatically inflated?

From what I understand, the LayoutInflater converts XML into Views. But when I use Buttons, TextViews or other widgets in code, I simply have to use findViewById() without having to inflate these Views first. Are these views automatically inflated? If so, when are views automatically inflated and when do you have to inflate them manually?
You just have to inflate an xml layout, and then all the viewgroups and views (buttons,textview,edittext,etc.) will automatically be shown.
So in an Activity class, oncreate method has a line SetContentview(), this inflates the xml layout.
An Activity needs to include a call to setContentView(R.layout.<your_layout_here>) in its onCreate method. That inflates the XML in the specified layout into the view hierarchy for the Activity. For a Fragment, override the onCreateView method like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.<your_layout_here>, container, false);
}
Once you've inflated a layout (and all of its children Views) into the view hierarchy, you can then use findViewById(R.id.<your_view_id>) to get a reference to the actual View object that you've inflated into the hierarchy and play with it.
you inflate your views manually if you create your activity and xml manually.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
}
Few things are here:
1. View for your activity(UI screen), that is set by setContentView() method.
2. View for a specific UI component e.g. Button, that is either created in xml of your activity_layout or you can inflate a separate xml layout file for your specific UI component. The best example and use is like inflating an xml layout file for your customised Toast.
So, here is the thing that relates setContentView() and inflating an xml layout file for a separate view:
Both of these provides a layout for view and view components, both of them creates a binary output for layout and use them as described above.

Access to different xml elements

I would like to know if there is a way to access elements from different layouts in a Fragment class, something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view1 = inflater.inflate(R.activity_layout_1, container, false);
View view2 = inflater.inflate(R.activity_layout_2, container, false);
TextView textView1= (TextView) view1.findViewById(R.id.textView1);
TextView textView2= (TextView) view2.findViewById(R.id.textView2);
textView2.setText("text changed");
}
This is what I want to achieve
Am I missing something?
To add menu items to the ActionBar, you should override onCreateOptionsMenu(). You can do this in either an Activity or a Fragment. The "listener" is actually the onOptionsItemSelected() method, also within the Activity or Fragment subclass which created the menu. For details, check out the Menus API Guide.
If you are targetting API 23 (Marshmallow), you should look at Toolbar. Even for older versions, you can use Toolbar from the appcompat library.
Your code should work as written. What it will look like will depend upon the container. And, depending upon how you are setting up the fragment, you might not have control over container
Another options is to use <include> instead, for greater control. You have one layout that uses <include> elements to reference the ones that you want to reuse and, if needed, provide right containers for it all to work.

Using CustomView as a rootview in fragment

In Activity's onCreate Method we can do the following
QuickReturnHeaderHelper helper = new QuickReturnHeaderHelper(this,
R.layout.activity_product_detail,R.layout.product_details_footer);
wholeView = helper.createView(productDetailDTO.isOwner());
setContentView(wholeView);
In fragment,we can return a layout from onCreateView(), we can inflate it from a layout resource defined in XML. To help us do so, onCreateView() provides a LayoutInflater object.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
Now, I want to use
whole view i.e my custom view
as my fragments rootview.I dont want to inflate if from a layout resource defined in XML.
But, until now I have not been able to do so. I have been searching in google for past few days but searching didnot produce any result. So, here I am posting this question.
I do not get your question completely but in my opinion what you can do is create an empty xml file(with relative layout only) and inflate it then add your custom view to it. Hope this will work, sorry if i was wrong

What does the LayoutInflater attachToRoot parameter mean?

The LayoutInflater.inflate documentation isn't exactly clear to me about the purpose of the attachToRoot parameter.
attachToRoot: whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct
subclass of LayoutParams for the root view in the XML.
Could someone please explain in more detail, specifically what the root view is, and maybe show an example of a change in behavior between true and false values?
NOW OR NOT NOW
The main difference between the "third" parameter attachToRoot being true or false is this.
When you put attachToRoot
true : add the child view to parent RIGHT NOW
false: add the child view to parent NOT NOW.
Add it later. `
When is that later?
That later is when you use eg parent.addView(childView)
A common misconception is, if attachToRoot parameter is false then the child view will not be added to parent. WRONG
In both cases, child view will be added to parentView. It is just a matter of time.
inflater.inflate(child,parent,false);
parent.addView(child);
is equivalent to
inflater.inflate(child,parent,true);
A BIG NO-NO
You should never pass attachToRoot as true when you are not responsible for adding the child view to the parent.
Eg When adding Fragment
public View onCreateView(LayoutInflater inflater,ViewGroup parent,Bundle bundle)
{
super.onCreateView(inflater,parent,bundle);
View view = inflater.inflate(R.layout.image_fragment,parent,false);
.....
return view;
}
if you pass third parameter as true you will get IllegalStateException because of this guy.
getSupportFragmentManager()
.beginTransaction()
.add(parent, childFragment)
.commit();
Since you have already added the child fragment in onCreateView() by mistake, calling add will tell you that child view is already added to the parent Hence IllegalStateException.
Here you are not responsible for adding childView, FragmentManager is responsible. So always pass false in this case.
NOTE: I have also read that parentView will not get childView touchEvents if attachToRoot is false. But I have not tested it though.
If set to true then when your layout is inflated it will be automatically added to the view hierarchy of the ViewGroup specified in the 2nd parameter as a child. For example if the root parameter was a LinearLayout then your inflated view will be automatically added as a child of that view.
If it is set to false then your layout will be inflated but won't be attached to any other layout (so it won't be drawn, receive touch events etc).
Seems like a lot of text in the responses but no code, that's why I decided to revive this old question with a code example, in several responses people mentioned:
If set to true then when your layout is inflated it will be automatically added to the view hierarchy of the ViewGroup specified in the 2nd parameter as a child.
What that actually means in code(what most programmers understand) is:
public class MyCustomLayout extends LinearLayout {
public MyCustomLayout(Context context) {
super(context);
// Inflate the view from the layout resource and pass it as child of mine (Notice I'm a LinearLayout class).
LayoutInflater.from(context).inflate(R.layout.child_view, this, true);
}
}
Notice that previous code is adding the layout R.layout.child_view as child of MyCustomLayout because of attachToRoot param is true and assigns the layout params of the parent exactly in the same way as if I would be using addView programmatically, or as if I did this in xml:
<LinearLayout>
<View.../>
...
</LinearLayout>
The following code explains the scenario when passing attachRoot as false:
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
// Create a stand-alone view
View myView = LayoutInflater.from(context)
.inflate(R.layout.ownRootView, null, false);
linearLayout.addView(myView);
In the previous code you specify that you wanted myView to be it's own root object and do not attach it to any parent, later on we added it as part of the LinearLayout but for a moment it was a stand-alone (no parent) view.
Same thing happens with Fragments, you could add them to an already existing group and be part of it, or just pass the parameters:
inflater.inflate(R.layout.fragment, null, false);
To specify that it will be it's own root.
The documentation and the two previous answers should be enough, just some thoughts from me.
The inflate method is used to inflate layout files. With those inflated layouts you have to possibility to attach them directly to a parent ViewGroup or just inflate the view hierarchy from that layout file and work with it outside of the normal view hierarchy.
In the first case the attachToRoot parameter will have to be set to true(or much simple use the inflate method that takes a layout file and a parent root ViewGroup(non null)). In this case the View returned is simply the ViewGroup that was passed in the method, the ViewGroup to which the inflated view hierarchy will be added.
For the second option the returned View is the root ViewGroup from the layout file. If you remember our last discussion from the include-merge pair question this is one of the reasons for the merge's limitation(when a layout file with merge as root is inflated, you must supply a parent and attachedToRoot must be set to true). If you had a layout file with the root a merge tag and attachedToRoot was set to false then the inflate method will have nothing to return as merge doesn't have an equivalent.
Also, as the documentation says, the inflate version with attachToRoot set to false is important because you can create the view hierarchy with the correct LayoutParams from the parent. This is important in some cases, most notable with the children of AdapterView, a subclass of ViewGroup, for which the addView() methods set is not supported. I'm sure you recall using this line in the getView() method:
convertView = inflater.inflate(R.layout.row_layout, parent, false);
This line ensures that the inflated R.layout.row_layout file has the correct LayoutParams from the AdapterView subclass set on its root ViewGroup. If you wouldn't be doing this you could have some problems with the layout file if the root was a RelativeLayout. The TableLayout/TableRow also have some special and important LayoutParams and you should make sure the views in them have the correct LayoutParams.
I wrote this answer because even after going through several StackOverflow pages I wasn't able to clearly grasp what attachToRoot meant. Below is inflate() method in the LayoutInflater class.
View inflate (int resource, ViewGroup root, boolean attachToRoot)
Take a look at activity_main.xml file, button.xml layout and the MainActivity.java file I created.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
button.xml
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = getLayoutInflater();
LinearLayout root = (LinearLayout) findViewById(R.id.root);
View view = inflater.inflate(R.layout.button, root, false);
}
When we run the code, we won't see the button in the layout. This is because our button layout is not added into the main activity layout since attachToRoot is set to false.
LinearLayout has an addView(View view) method which can be used to add Views to LinearLayout. This will add the button layout into the main activity layout, and make the button visible when you run the code.
root.addView(view);
Let's remove the previous line, and see what happens when we set attachToRoot as true.
View view = inflater.inflate(R.layout.button, root, true);
Again we see that the button layout is visible. This is because attachToRoot directly attaches the inflated layout to the parent specified. Which in this case is root LinearLayout. Here we don't have to add the views manually like we did in the previous case with addView(View view) method.
Why are people getting IllegalStateException when setting attachToRoot as true for a Fragment.
This is because for a fragment you have already specified where to place your fragment layout in your activity file.
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.root, fragment)
.commit();
The add(int parent, Fragment fragment) adds the fragment which has it's layout to the parent layout. If we set attachToRoot as true, you will get IllegalStateException: The specified child already has a parent. Since fragment layout is already added to the parent layout in the add() method.
You should always pass false for attachToRoot when you're inflating Fragments. It is the FragmentManager’s job to add, remove and replace Fragments.
Back to my example. What if we do both.
View view = inflater.inflate(R.layout.button, root, true);
root.addView(view);
In the first line, LayoutInflater attaches the button layout to the root layout and returns a View object which holds the same button layout. In the second line, we add the same View object to the parent root layout. This results in the same IllegalStateException we saw with Fragments (The specified child already has a parent).
Keep in mind that there is another overloaded inflate() method, which sets attachToRoot as true by default.
View inflate (int resource, ViewGroup root)
I myself was also confused about what was the real purpose of attachToRoot in inflate method. After a bit of UI study, I finally got the answer:
parent:
in this case is the widget/layout that is surrounding the view objects that you want to inflate using findViewById().
attachToRoot:
attaches the views to their parent (includes them in the parent hierarchy), so any touch event that the views recieve will also be transfered to parent view. Now it's upto the parent whether it wants to entertain those events or ignore them. if set to false, they are not added as direct children of the parent and the parent doesn't recieve any touch events from the views.
Hope this clears the confusion
There is a lot of confusion on this topic due to the documentation for the inflate() method.
In general, if attachToRoot is set to true, then the layout file specified in the first parameter is inflated and attached to the ViewGroup specified in the second parameter at that moment in time. When attachToRoot is false, the layout file from the first parameter is inflated and returned as a View and any View attachment happens at some other time.
This probably doesn't mean much unless you see a lot of examples. When calling LayoutInflater.inflate() inside of the onCreateView method of a Fragment, you will want to pass in false for attachToRoot because the Activity associated with that Fragment is actually responsible for adding that Fragment's view. If you are manually inflating and adding a View to another View at some later point in time, such as with the addView() method, you will want to pass in false for attachToRoot because the attachment comes at a later point in time.
You can read about several other unique examples concerning Dialogs and custom Views on a blog post I wrote about this very topic.
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
attachToRoot set to true means the inflatedView will be added to the parent view's hierarchy. Thus can possibly be "seen" and sense touch events (or any other UI operations) by users. Otherwise, it is just been created, not been added to any view hierarchy and thus cannot be seen or handle touch events.
For iOS developers new to Android, attachToRoot set to true means you call this method:
[parent addSubview:inflatedView];
If going further you might ask: Why should I pass parent view if I set attachToRoot to false? It is because the root element in your XML tree needs the parent view to calculate some LayoutParams (like match parent).
When you define the parent the attachToRoot determines whether you want the inflater to actually attach it to the parent or not. In some cases this causes problems, like in a ListAdapter it will cause an exception because the list tries to add the view to the list but it says it's already attached. In other cased where you're just inflating the view yourself to add to an Activity it could be handy and save you a line of code.
For example we have an ImageView , a LinearLayout and a RelativeLayout. LinearLayout is the child of RelativeLayout.
the View Hierarchy will be.
RelativeLayout
------->LinearLayout
and we have a separate layout file for ImageView
image_view_layout.xml
Attach to root:
//here container is the LinearLayout
View v = Inflater.Inflate(R.layout.image_view_layout,container,true);
Here v contains the reference of the container layout i.e the
LinearLayout.and if you want to set the parameters like setImageResource(R.drawable.np); of ImageView you will have to find it by the reference of parent i.e view.findById()
Parent of v will be the FrameLayout.
LayoutParams will be of FrameLayout.
Not attach to root:
//here container is the LinearLayout
View v = Inflater.Inflate(R.layout.image_view_layout,container,false);
Here v contains the no reference container layout but direct
reference to the ImageView that is inflated so you can set its
parameters like view.setImageResource(R.drawable.np); without
refereing like findViewById. But container is specified so that
ImageView gets the LayoutParams of the container so you can say
that the reference of container is just for LayoutParams nothing
else.
so in particular case Parent will be null.
LayoutParams will be of LinearLayout.
attachToRoot Set to true:
If attachToRoot is set to true, then the layout file specified in the first parameter is inflated and attached to the ViewGroup specified in the second parameter.
Imagine we specified a button in an XML layout file with its layout width and layout height set to match_parent.
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/custom_button">
</Button>
We now want to programmatically add this Button to a LinearLayout inside of a Fragment or Activity. If our LinearLayout is already a member variable, mLinearLayout, we can simply add the button with the following:
inflater.inflate(R.layout.custom_button, mLinearLayout, true);
We specified that we want to inflate the Button from its layout resource file; we then tell the LayoutInflater that we want to attach it to mLinearLayout. Our layout parameters are honored because we know the Button gets added to a LinearLayout. The Button’s layout params type should be LinearLayout.LayoutParams.
attachToRoot Set to false (not required to use false)
If attachToRoot is set to false, then the layout file specified in the first parameter is inflated and not attached to the ViewGroup specified in the second parameter but that inflated view acquires parent's LayoutParams which enables that view to fit correctly in the parent.
Let’s take a look at when you would want to set attachToRoot to false. In this scenario, the View specified in the first parameter of inflate() is not attached to the ViewGroup in the second parameter at this point in time.
Recall our Button example from earlier, where we want to attach a custom Button from a layout file to mLinearLayout. We can still attach our Button to mLinearLayout by passing in false for attachToRoot—we just manually add it ourselves afterward.
Button button = (Button) inflater.inflate(R.layout.custom_button, mLinearLayout, false);
mLinearLayout.addView(button);
These two lines of code are equivalent to what we wrote earlier in one line of code when we passed in true for attachToRoot. By passing in false, we say that we do not want to attach our View to the root ViewGroup just yet. We are saying that it will happen at some other point in time. In this example, the other point in time is simply the addView() method used immediately below inflation.
The false attachToRoot example requires a bit more work when we manually add the View to a ViewGroup.
attachToRoot Set to false(false is Required)
When inflating and returning a Fragment’s View in onCreateView(), be sure to pass in false for attachToRoot. If you pass in true, you will get an IllegalStateException because the specified child already has a parent. You should have specified where your Fragment’s view will be placed back in your Activity. It is the FragmentManager’s job to add, remove and replace Fragments.
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.root_viewGroup);
if (fragment == null) {
fragment = new MainFragment();
fragmentManager.beginTransaction()
.add(R.id.root_viewGroup, fragment)
.commit();
}
The root_viewGroup container that will hold your Fragment in your Activity is the ViewGroup parameter given to you in onCreateView() in your Fragment. It’s also the ViewGroup you pass into LayoutInflater.inflate(). The FragmentManager will handle attaching your Fragment’s View to this ViewGroup, however. You do not want to attach it twice. Set attachToRoot to false.
public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, parentViewGroup, false);
…
return view;
}
Why are we given our Fragment’s parent ViewGroup in the first place if we don’t want to attach it in onCreateView()? Why does the inflate() method request a root ViewGroup?
It turns out that even when we are not immediately adding our newly inflated View to its parent ViewGroup, we should still use the parent’s LayoutParams in order for the new View to determine its size and position whenever it is eventually attached.
Link: https://youtu.be/1Y0LlmTCOkM?t=409
Just sharing some points that i encountered while working on this topic,
In addition to the accepted answer i want to some points which could be of some help.
So, when i used attachToRoot as true, the view which was returned was of type ViewGroup i.e. parent's root ViewGroup which was passed as parameter for the inflate(layoutResource,ViewGroup,attachToRoot) method, not of type the layout which was passed but on attachToRoot as false we get the function return type of that layoutResource's root ViewGroup.
Let me explain with an example:
If we have a LinearLayout as the root layout and then we want to add TextView in it through inflate function.
then on using attachToRoot as true inflate function returns a View of type LinearLayout
while on using attachToRoot as false inflate function returns a View of type TextView
Hope this finding would be of some help...

Categories

Resources