如何改变活性片段的TextView的文本 [英] How to change fragment's textView's text from activity
问题描述
这似乎是一个简单的事情,但我不能修复它,所以请帮助我。 我有4个文件:
It's seems like a simple thing to do, but I can't fix it, so please help me. I have 4 files :
MainActivity.java
activity_main.xml
FragmentClass.java
frag_class.xml
frag_class.xml有TextView的,我想改变从MainActivity.java文本。 FragmentClass延伸片段,该片段中显示MainActivity FragmentClass有:
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);
}
和在MainActivity我已经试过这样:
and in MainActivity I have tried this:
FragmentClass fc = new FragmentClass();
fc.changeText("some text");
但可悲的是这个code给我的NullPointerException在 fc.changeText(一些文本);
我也试过直接从MainActivity改变文字:
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);
失败。 请帮我。
Fail. Please help me.
更新: 全部code在这里。 http://pastebin.com/NQBieFLi
Update: Full code here. http://pastebin.com/NQBieFLi
推荐答案
@Lalit的答案是正确的,但我看到,你不需要建立像fragment_obj.updateTextView功能();.我把我所有的观点是一流水平的对象,并能够直接更新的TextView。
@Lalit answer is correct but I see that you dont need to create a function like fragment_obj.updateTextView();. I set all my view as class level objects and was able to update the textview directly.
fragmentRegister.textViewLanguage.setText("hello mister how do you do");
请注意:如果需要执行多个动作,然后有一个功能是要走的路
Note: If you need to perform more than one action then having a function is the way to go.
这篇关于如何改变活性片段的TextView的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!