简体   繁体   中英

textView.setText not working

I have a TextView in a fragment called "frontpage". In my MainActivity (also called frontpage, and the fragment is also there), I want to change the text of my textview. Here is my code in the Mainactivity:

public static class PlaceholderFragment extends 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
    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. Why is that?

Because you never called your setText(String) function! JVM will follow what you tell it to and you never asked it to go and execute seText(String) function :)

在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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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