简体   繁体   English

textView.setText不起作用

[英]textView.setText not working

I have a TextView in a fragment called "frontpage". 我在一个名为“ frontpage”的片段中有一个TextView。 In my MainActivity (also called frontpage, and the fragment is also there), I want to change the text of my textview. 在我的MainActivity(也称为frontpage,也存在该片段)中,我想更改textview的文本。 Here is my code in the Mainactivity: 这是我在Mainactivity中的代码:

public static class PlaceholderFragment extends Fragment { 公共静态类PlaceholderFragment扩展Fragment {

public PlaceholderFragment() {


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_frontpage, container, false);
    return rootView;

}
public void setText(String text){
    TextView textView = (TextView) getView().findViewById(R.id.NameView);
    textView.setText("HI!");
}

} }

And here is my code in the xml layout for the textview: 这是我在textview的xml布局中的代码:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/NameView"
    android:layout_below="@+id/textView"
    android:layout_centerHorizontal="true" />

No errors are being shown, but when running the app, the textview stays empty. 没有显示任何错误,但在运行应用程序时,textview保持空白。 Why is that? 这是为什么?

Because you never called your setText(String) function! 因为您从未调用过setText(String)函数! JVM will follow what you tell it to and you never asked it to go and execute seText(String) function :) JVM将按照您告诉的内容进行操作,而您从未要求它执行seText(String)函数:)

在return rootView上方添加此代码。

setText("Hi");
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_frontpage, container, false);
    TextView textView = (TextView) rootView.findViewById(R.id.NameView);
    textView.setText("Hi");
    return rootView;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM