setText from inside a fragment

一世执手 提交于 2019-12-24 11:22:21

问题


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?


回答1:


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




回答2:


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");


来源:https://stackoverflow.com/questions/11839966/settext-from-inside-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!