Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change fragment's textView's text from activity

I cannot find how to change fragment's textview from an Activity. I have 4 files :

MainActivity.java activity_main.xml FragmentClass.java frag_class.xml 

frag_class.xml has textView, I want to change the text from MainActivity.java. FragmentClass extends Fragment, this fragment is displayed in MainActivity FragmentClass has:

public void changeText(String text){  TextView t = (TextView) this.getView().findViewById(R.id.tView);  t.setText(text); } 

and in MainActivity I tried this:

FragmentClass fc = new FragmentClass(); fc.changeText("some text"); 

But sadly this code gives me NullPointerException at fc.changeText("some text"); I've also tried changing the text directly from MainActivity with:

 TextView t = (TextView) this.getView().findViewById(R.id.tView);  t.setText(text); 

which Failed.

[EDIT] The full code is here

like image 699
Cԃաԃ Avatar asked Apr 30 '13 08:04

Cԃաԃ


2 Answers

You can find the instance of Fragment by using,

For support library,

YourFragment fragment_obj = (YourFragment)getSupportFragmentManager().                                               findFragmentById(R.id.fragment_id); 

else

YourFragment fragment_obj = (YourFragment)getFragmentManager().                                              findFragmentById(R.id.fragment_id);  

Then create a method in the Fragment that updates your TextView and call that method using fragment_obj like,

fragment_obj.updateTextView();

like image 143
Lalit Poptani Avatar answered Sep 27 '22 20:09

Lalit Poptani


From activity to Fragment by Fragment Transaction:

public class MainActivity extends Activity {      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);      }     public static void changeFragmentTextView(String s) {         Fragment frag = getFragmentManager().findFragmentById(R.id.yourFragment);         ((TextView) frag.getView().findViewById(R.id.textView)).setText(s);       } } 
like image 20
Daryn Avatar answered Sep 27 '22 18:09

Daryn