Use view from fragment xml file - android

I have an activity with several tabs (using the 'fixed tabs + swipe' style). Each tab layout is defined as a fragment xml file.
Eg, my activity is called ModifyCustActivity. This uses an almost-empty xml file called activity_modify_cust.xml. Each tab on this page is represented by various xml files such as fragment_modify_cust_basic and fragment_modify_cust_address etc etc. Each of these fragment xml files contains EditTexts, Spinners and more.
When the activity starts, I need to be able to access these views from the activity code, as I need to pre-populate them, and get their results once they are edited. However, because these views exist in a fragment xml file, I don't seem to be able to reach them in code. Is there a way to access a view contained in a fragment xml file?

Is there a way to access a view contained in a fragment xml file?
Yes it is, but your fragment should be declared in the XML layout file, which seems to be your case.
For example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
...">
<fragment
android:name="com.example.MyFragment"
android:id="#+id/my_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
And you would access the fragment like this:
FragmentManager manager = getSupportFragmentManager();
MyFragment fragment = (MyFragment)manager.findFragmentById(R.id.my_fragment);
Then using the fragment instance you could further access your views, for example by calling a public method from the fragment which updates some particular view.
UPDATE:
Suppose you have a TextView that appears in layout of the fragment, and need to update from the activity.
Let this be the fragment class:
public class MyFragment extends Fragment{
private TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null, false);
textView = (TextView)view.findViewById(R.id.textView);
return view;
}
public void updateTextView(String text){
textView.setText(text);
}
}
Then you would update the TextView by calling in your activity the updateTextView() method:
fragment.updateTextView("text");

You can reach fragments views from activity. If you want to send a data from fragment to another fragment. Your sender fragment must communicate with activity and your activity can manipulate the view in other fragment
http://developer.android.com/training/basics/fragments/communicating.html

Related

How to set an Activity's root view as fragment in Android?

I have a Fragment, and I want to set that whole fragment as root view of my activity. I have everything ready, and I'm instantiating my fragment programatically. I've tried (in my activity):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FeedFragment fragment = [...];
setContentView(fragment.getView());
}
But I've got a null pointer exception. In other words, how can I make my fragment act like an activity? I only target ICS+, I don't need to support older versions, if it makes any difference.
Try this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.all_lecturer_frag, container, false);
......
return rootView;
}
A Fragment, by design, is intended to be a tool to help you reuse screen space and as such, fragments have to be present inside a container. So while a fragment cannot technically be a root view, you can have a fragment be the only view inside the Activity. For this, you should inflate the view for your fragment programmatically inside the onCreateView() method of the fragment. then you could have something like this in your activity's layout xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.package.fragment_name
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
And then, within your activity, all you have to do is:
setContentView(R.layout.main);
Since, the fragment is defined in the layout xml, it cannot be removed from the activity's layout (although the layout itself can be changed) and is tied to it.
Also, on a side note, notice that the root view is a FrameLayout and not the fragment itself. But in this manner, your fragment can be tied to the activity. But don't forget that the Fragment will still retain it's lifecycle separate from the activity's.
EDIT: If you need to create your fragment instance programmatically, you have to do:
getFragmentManager().beginTransaction().add(R.id.frame_layout, your_fragment).commit();
This is the only way to add your fragment programmatically. But also keep in mind that the Fragment's layout is not tied to the activity's layout. But you can use the Fragment's lifecycle to behave similarly as an Activity.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.xxx);
//initializations...
if (savedInstanceState == null) {
// During initial setup, plug in the fragment.
YourFragment details = new YourFragment();
getFragmentManager().beginTransaction().add(R.id.your_root_frame_layout, details).commit();
}
}

Is it possible to access fragment's UI elements from activitiy's onCreate

As the headline says: Is it possible to get the currently visible fragment with all UI elements initialized within the onCreate() method of the activity?
I am implementing a separation into model, view and controller with separate controller classes that handle business logic and UI events. Therefore they need a reference to the current fragment. These controllers are initialized in the onCreate() method of the activity hence I need the initialized fragment within that method.
I welcome any kind of advice :)
EDIT:
Adding some code for better understanding:
I'm using dagger for dependency injection and would like to do this in the onCreate() method. As I said before my controller needs an the mapView element. And that is why I would like to have a fragment with the mapView element initialized.
MapActivity#onCreate(Bundle):
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_layout);
MyMapFragment fragment = new MyMapFragment();
getFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment, "fragment")
.commit();
ObjectGraph.create(new Module(fragment.getMapView())).inject(this);
}
activity_layout.xml
<android.support.v4.widget.DrawerLayout>
<FrameLayout
android:id="#+id/activity_container"
... />
<ListView .../>
</android.support.v4.widget.DrawerLayout>
fragment_layout.xml
<RelativeLayout>
<org.osmdroid.map.MapView
android:id"#+id/mapview"
... />
<Button .../>
</RelativeLayout>
2ND EDIT:
So it seems like that is not possible... Yay for the downvote ^^
By default, no. At the time activity onCreate() runs, the fragment is not attached to the activity yet.
Right place to access a fragment's views is in the fragment itself. Consider putting the controller assignments in the fragment within its lifecycle such as onCreateView() or onViewCreated().
It is possible to explicitly run queued up fragment transactions using executePendingTransactions(), or implicitly after super.onStart() has been run in the activity lifecycle. After that the fragment views are accessible in the activity view hierarchy.
in your onCreate method add the following (I used a textview as an example):
while (fragment.getView() == null) {
}
rootView = fragment.getView();
TextView myView = (TextView) rootView.findViewById(R.id.text_view);
Make sure to return the rootView in your fragment's onCreateView method as follows:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activity,
container, false);
return rootView;
}
I know that the idea of getting your fragment to access its views from the main activity is bad. Yet, this solution may give you what you want.

How to pass dynamically created RelativeLayout to the fragment

I have created the class which extends Fragment which creates the RelativeLayout.I want to know how to pass that dynamically created RelativeLayout to the another fragment containing FrameLayout and set that RelativeLayout to that FrameLayout.
Why creating the layout outside the fragment? that's why fragments have onCreaveView & onViewCreated methods in their lifecycle.
I would suggest you to pass a STATE variable (int,string) to the fragment using Bundle,
and on the onCreateView method get the state in build the view according to it.
You can find simple example how to pass bundle and use it inside the fragment here
If you find yourself must pass a view to fragment you can use 3rd class which will hold it. But that's really not the right way...
I haven't try it yet but it might work
class CustomFragment extends Fragment{
RelativeLayout relativeView;
CustomFragment(RelativeLayout view){
relativeView = view;
}
onCreateView(){
//inflate layout and get FrameLayout
frameLayout.addView(relativeView);
}
}
and your RelativeLayout
RelativeLayout r = new RelativeLayout(context);
// custom it as you wish
CustomFragment fragment = new CustomFragment(r);

settext() for textview inside Fragment is not changing the textview

I have a fragment activity that creates several fragments for a viewpager. The first fragment I'm making is a port from previously being an activity. Before the activity's onCreate method set a textview based on some prior user input.
However now that this is a fragment the same code in onCreateView is ignoring the setText() method and only ever shows the default XML layout text inside the UI elements.
I've seen other people with this issue and yet not found it to be resolved. How can I setText for a textview in a fragment, the way it used to work for onCreate in an activity?
Thanks.
edit: The text I'm trying to set comes in through an intent when the host FragmentActivity (which makes the fragments) is created. So
Activity A + String str -->
creates FragmentActivity (gets str from intent). -->
Fragment 1, textView TV, TV.sestText(str);
If you need to see code, its from this example:
http://thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/
http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/
Where inside Tab1Fragment, I've added a textview to the XML file, and I'm trying to call setText inside the onCreateView method in Tab1Frag.
If I recall, it goes something like this...
public RelativeLayout onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.frag1_layout, null);
title = (TextView) view.findViewById(R.id.frag1_title);
title.setText("Success!");
return (RelativeLayout)inflater.inflate(R.layout.frag1_layout, container, false);
}

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