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
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();
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With