I run a setText command inside of a fragment activity to try and set the text of a textView in the parent activity, but it's not working. Any ideas?
TextView text = (TextView) getView().findViewById(R.id.status);
text.setText("Text from a fragment");
I don't get an error in eclipse, but I get a null pointer exception during runtime. Of course it happens at the line where I setText. Any ideas on how to do this?
Yes your NPE will probably be because
R.id.status
is probably not defined in the fragment's view.getView()
will return the view that is generated in your Fragment'sonCreateView()
method.Are you trying to set a TextView in your Activity from a (secondary) FragmentActivity or trying to set a TextView in your FragmentActivity from a Fragment?
If it's the 1st option, you'll want to do something like use a message handler and pass the 2nd Activity a message. I don't think this is what you're asking though.
If you're wanting to set a TextView from a Fragment, the general way to do that is to define an interface on your FragmentActivity with a method (
updateText()
for example) and get the Fragment to call the method. The Activity then handles the TextView update, which works nicely because it can callgetView()
which will return the view you're looking for. It's similar to my answer posted hereUse getActivity(). It will cause the findViewById() method to start the search at the base activity and bubble up until it finds your "r.id.status".