Reputation: 7268
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 EditText
s, Spinner
s 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?
Upvotes: 2
Views: 4202
Reputation: 16043
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");
Upvotes: 3
Reputation: 434
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
Upvotes: 0