Android: Fragments: setContentView alternative - android

I'm trying to rewrite an existing project using fragments to port my application on tablet.
I'm replacing activities with fragments.
The problem is that I don't know what is the equivalent to setContentView method? Is there any way to create Fragment's view except rewriting onCreateView?

In the onCreateView() method you can return the view of your fragment as follows :
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.ads_tab, container, false);
}

I'm not sure why you cannot use onCreateView. But here is what you can do.
Create LinearLayout object, save it as mRooLayout member field and return it from onCreateView. Here is how you can implement setContentView:
void setFragmentContentView(View view)
{
LinearLayout.LayoutParams layoutParams =
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
mRootLayout.removeAllViews();
mRootLayout.addView(view, layoutParams);
}

Related

Is it possible to get a reference to a Fragment's child View inside the onCreate() of Activity?

I could use onCreateView() to get a reference to a a child view in a fragment, and then write a getter method inside the same fragment for this view, which would be called by the Activity to get a reference to the view. Like:
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout rootLinearLayout = (LinearLayout) layoutInflater.inflate(R.layout.my_fragment, container, false);
javaCameraView = (JavaCameraView) rootLinearLayout.findViewById(R.id.myFragment_javaCameraView);//***********
return rootLinearLayout;
}
JavaCameraView getCameraView() {
return javaCameraView;
}
But the problem is that I need the child view inside the Activity's onCreate(), and I think onCreateView() of fragment is called AFTER the onCreate() of Activity returns. Reference
So is there a way to get a reference to a fragment's view, inside the onCreate() of the Activity?
You are doing it wrong. You should not be exposing a fragment's UI elements to the hosting activity. A fragment should encapsulate it's views and functionality. If you are really only using the fragment as a UI component, create a custom View and use that in the activity.
To answer your question, no, you can't get a reference to the fragment's view in the activity's onCreate(). The reason is that the fragment's view doesn't exist until the fragment has gone through it's lifecycle. There's no guarantee when that's going to happen, which is why it's bad to be coding based on such assumptions.
If the fragment needs to communicate events back to the activity, have your activity implement a listener interface, and have the fragment call that interface when appropriate.
So in your case, you could do something like this in the fragment's onCreateView(),
if (getActivity() instanceof Listener) {
((Listener)getActivity()).onViewCreated(fragmentViews);
}
But again, that's doing it wrong.
To call onCreateView() manually should work, though this is not a good way to do it.
private JavaCameraView javaCameraView;
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout rootLinearLayout = (LinearLayout) layoutInflater.inflate(R.layout.my_fragment, container, false);
javaCameraView = (JavaCameraView) rootLinearLayout.findViewById(R.id.myFragment_javaCameraView);
return rootLinearLayout;
}
JavaCameraView getCameraView(LayoutInflater layoutInflater) {
if (javaCameraView == null) {
onCreateView(layoutInflater, null, null);
}
return javaCameraView;
}
You can then use yourFragment.getCameraView(getLayoutInflater()) in your onCreate().

Fragment layout in android

I am using Fragment layout in my app. but I want to use The code that I written in Oncreate Bundle, so how I can write my code in OncreateView.
here is the code of fragment layout.
public class Text extends Fragment {
public Text(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.text_to_speech, container, false);
return rootView;
}
so where I have to use oncreate bundle, or can I write same code in OncreateView.
help. Thanks.
You can get bundle like below if you passed some data by bundle.
Bundle bundle = getArguments();
We use this method for it.
public void onActivityCreated(Bundle savedInstanceState1) {
super.onActivityCreated(savedInstanceState1);
}
Here the full description about Fragment lifeCycle
Meanwhile, onCreateView must get the view from the Activity. here some usefull tutorial
wish that was helpfull
Fragment class doesn't have oncreate() method.You can write code in oncreateView().Check the Fragment lifecycle. Follow the link below
http://developer.android.com/guide/components/fragments.html

When Fragment.onCreateView is complete and how to receive this event from the Activity? [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
EDIT
Changed title.
SDK Guide document says, Activity.onCreate complete after Fragment.onCreateView and Fragment.onAcvityCreated.
But If I try findViewById for a view of the fragment it returns null.
How can I access contents of the fragment?
I'm very new to Android UI dev.
Below is a sample code generated by Eclipse IDE.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
// this is null
View rootView = findViewById(R.id.txtView);
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
First of all, I want to access inner contents of the 'fragment_main'.
Can I do this with findViewById?
I found that calling findViewById for a view of the fragment at onCreate call is not working.
How do I know when the Fragment views are ready at the Activity level?
I read How to implement OnFragmentInteractionListener
Am I needed to manually implement a event listener for this?
I think short answer is 'impossible' or 'not works like that'.
If one want to manage inner contents of fragments just delete fragments and move all the contents to the activity layout.
But If I try findViewById for a view of the fragment it returns null.
You can not just access the view of the fragment in your activity's oncreate or where ever, you can call view of the fragment in your activity.
I found that calling findViewById for a view of the fragment at onCreate call is not working.
That is because the view is not inflated yet in your fragment thus returning null.
Have a look at the fragment life cycle:
(source: xamarin.com)
As you can see onCreate is before onCreateView which you inflate your view for the fragment's layout.
solution:
you call findViewByIdit in your fragment's onActivityCreated.
sample:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView sample = (TextView) getView().findViewById(your_id);
}

Stop fragment from being recreated after resume?

I am using several fragments to be dynamically added into activity. Everything works fine, when I press back-button, the fragments go to backstack. And when I resume it, it appears. But everytime on Resume, it is recreating the fragment and call onCreateView. I know it is a normal behavior of the fragment lifecycle.
This is my onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.competitive_programming_exercise, container, false);
return rootView;
}
I want to stop those fragments from recreating. I tried with onSavedInstanstate but nothing is working. How can I accomplish that?
In the Activity's onCreateView set the savedInstanceState to null before calling the super method. You could also remove only the keys "android:viewHierarchyState" and "android:fragments" from the savedInstanceState bundle. Here is code for the simple solution, nulling the state:
#Override
public void onCreate(Bundle savedInstanceState)
{
savedInstanceState = null;
super.onCreate(savedInstanceState);
...
}
Iam using 5 fragments and working for me good as I was facing the same issue before..
public class MyFragmentView1 extends Fragment {
View v;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
if (v == null)
v = inflater.inflate(R.layout.my_fragment_view_layout,
container, false
);
return v;
}
}
I put the view variable inside class and inflating it as new only if the view instance is null or otherwise use the one created before
You can't stop the fragment from being recreated, unfortunately. The best you can do is to remove the fragment in a transaction, after it has been restored but before it gets displayed.
If you know you are going to remove the fragment immediately you can reduce the performance hit of restoring the fragment by simplifying methods such as onCreateView() to return a dummy view, rather than inflating the whole view hierarchy again.
Unfortunately the tricky part is finding the best place to commit this transaction. According to this article there are not many safe places. Perhaps you can try inside FragmentActivity.onResumeFragments() or possibly Fragment.onResume().

findViewById returns NULL when using Fragment

I'm new to Android developing and of course on Fragments.
I want to access the controls of my fragment in main activity but 'findViewById' returns null.
without fragment the code works fine.
Here's part of my code:
The fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:ignore="HardcodedText" >
<EditText
android:id="#+id/txtXML"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:ems="10"
android:scrollbars="vertical">
</EditText>
</LinearLayout>
the onCreate of MainActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.initialisePaging();
EditText txtXML = (EditText) findViewById(R.id.txtXML);}
on this point the txtXML is null.
What's Missing in my code or what should I do?
Try like this on your fragments on onCreateView
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
LinearLayout ll = (LinearLayout )inflater.inflate(R.layout.tab_frag1_layout, container, false);
EditText txtXML = (EditText) ll.findViewById(R.id.txtXML);
return ll;
}
You should inflate the layout of the fragment on onCreateView method of the Fragment then you can simply access it's elements with findViewById on your Activity.
In this Example my fragment layout is a LinearLayout so I Cast the inflate result to LinearLayout.
public class FrgResults extends Fragment
{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//some code
LinearLayout ll = (LinearLayout)inflater.inflate(R.layout.frg_result, container, false);
//some code
return ll;
}
}
I'm late, but for anyone else having this issue. You should be inflating your view in the onCreateView method. Then override the onCreateActivity method and you can use getView().findViewById there.
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment, container, false);
}
You can't access the the view of fragment in activity class by findViewById instead what you can do is...
You must have an object of Fragment class in you activity file, right? create getter method of EditText class in that fragment class and access that method in your activity.
create a call back in Fragment class on the event where you need the Edittext obj.
1) Try this:
Eclipse menu -> Project -> Clean...
update
2) If you have 2 or more instances of 'main' layout, check if all of them have a view with 'txtXML' id
3)
A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager, which can be obtained via Activity.getFragmentManager() and Fragment.getFragmentManager().
The Fragment class can be used many ways to achieve a wide variety of results. It is 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.
Study this. you must use FragmentManager.
If you want use findViewById as you use at activities onCreate, you can simply put all in overrided method onActivityCreated.
All the answers above tell you how you should "return the layout" but don't exactly tell you how to reference the layout that was returned so I was unable to use any of the solutions given. I used a different approach to solve the problem. In the Fragment class that handles the fragment, got to the onViewCreated() class and create a context variable in it that saves the context of the parent activity (main activity in my case).
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Context fragmentContext = (MainActivity) view.getContext();
}
Once that is done, you can use the new context to access items on your fragment from inside the onViewCreated() method.
EditText editText = context.findViewById(R.id.textXML);

Categories

Resources