setText from inside a fragment

2019-07-31 17:11发布

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?

2条回答
男人必须洒脱
2楼-- · 2019-07-31 18:02

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's onCreateView() 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 call getView() which will return the view you're looking for. It's similar to my answer posted here

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-31 18:06

Use 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".

TextView text = (TextView) getActivity().findViewById(R.id.status);
text.setText("Text from a fragment");
查看更多
登录 后发表回答