如何从活动中更改片段的 textView 文本 [英] How to change fragment's textView's text from activity

查看:36
本文介绍了如何从活动中更改片段的 textView 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到如何从 Activity 更改片段的 textview.我有 4 个文件:

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 有 textView,我想从 MainActivity.java 更改文本.FragmentClass 扩展了 Fragment,这个片段显示在 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 tried this:

FragmentClass fc = new FragmentClass();
fc.changeText("some text");

但遗憾的是,这段代码在 fc.changeText("some text"); 处给了我 NullPointerException我也试过直接从 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);

失败了.

完整代码在这里

推荐答案

@Lalit 答案是正确的,但我发现您不需要创建像 fragment_obj.updateTextView(); 这样的函数.我将所有视图设置为类级别对象,并且能够直接更新文本视图.

@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆