【问题标题】:Getting TextView view object from "onCreate" Activity's method从“onCreate”Activity 的方法中获取 TextView 视图对象
【发布时间】:2014-05-18 17:10:48
【问题描述】:

我在尝试通过 onCreate 方法中的 id 检索 TextView 对象时遇到问题来自 Activity。

我活动的 xml Fragment TextView 的部分:

<TextView
    android:id="@+id/message_display_field"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

onCreate 方法:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Create the text view
    TextView tv = (TextView) findViewById(R.id.message_display_field);
    tv.setText(message);
}

TextView tv = (TextView) findViewById(R.id.message_display_field); 不返回我希望它返回的 textView 而是 null

最后正如人们所料,这会抛出一个NullPointerException

如果这不是要走的路,我怎么能检索我的 TextView view 对象? :(

注意事项:

  • 在我按下运行按钮通过模拟器启动应用程序之前,没有任何警告或错误。

  • NullPointer 在运行时被触发。

我会给予任何帮助,提前谢谢你!

【问题讨论】:

  • TextView 是否在您的 activity_display_message XML 文件中?
  • 你的 textView 在片段内吗?
  • @NoXSaeeD @user184994 是的:/

标签: android


【解决方案1】:

实际上,如果你在 Fragment xml 中的 TextView 你要做的是:

1- 从那里转到类片段覆盖 onCreateView 方法,您可以像这样获得片段内的所有视图。

TextView foo;as //globle var

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

    foo = rootView.findViewById(R.id.message_display_field);

    return rootView;                 
}

现在你很开心
我希望这会有所帮助

【讨论】:

  • 这实际上是错误的。 onCreate 在 onCreateView 之前调用。您可能打算写 onActivityCreate 或更好的 onViewCreated,不是吗?
  • 是的,我的意思是 onCreateView 所以这里是你如何从片段中获取视图
  • 答案已编辑完成,如果我要获得最佳答案,因为没有其他我投票回答的人会很感谢。
猜你喜欢
  • 1970-01-01
  • 2018-04-27
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 2018-08-03
相关资源
最近更新 更多