【问题标题】:textView.setText not workingtextView.setText 不工作
【发布时间】:2015-05-25 14:53:34
【问题描述】:

我在名为“frontpage”的片段中有一个 TextView。在我的 MainActivity(也称为 frontpage,片段也在那里)中,我想更改我的 textview 的文本。这是我在 Mainactivity 中的代码:

公共静态类 PlaceholderFragment 扩展片段 {

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

}

这是我在 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" />

没有显示错误,但是在运行应用程序时,文本视图保持为空。这是为什么呢?

【问题讨论】:

  • 覆盖onViewCreated并调用方法
  • 你在哪里调用你的 setText 方法?
  • 好吧,我意识到我没有在任何地方调用它,所以问题是,我应该在哪里调用它? (对不起这些基本问题,我是初学者,这是我的第一个应用程序,所以我一边编程一边学习。)

标签: java android xml android-studio textview


【解决方案1】:

在上面添加此代码返回 rootView。

setText("Hi");

【讨论】:

    【解决方案2】:

    因为您从未调用过您的 setText(String) 函数! JVM 会按照你告诉它的,而你从来没有要求它去执行 seText(String) 函数:)

    【讨论】:

      【解决方案3】:
      @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;
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多