使用XML布局文件而不是Java代码创建TextView来显示通过intent接收到的消息



我正在学习如何开发android应用程序。

我遵循了谷歌构建你的第一个应用程序的教程。

这个想法基本上是在一个片段中写一个消息,用一个按钮提交,消息通过intent并显示在第二个片段中。

我的问题是关于我们显示消息的部分。这是在教程中如何完成的:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText("You submitted: "+message);

    // Set the text view as the activity layout
    setContentView(textView);
}

我了解到UI组件可以使用XML或Java实现,在这种情况下,显然教程使用Java通过intent接收到的数据创建一个新的TextView。我试图重做这一部分,但这一次,当涉及到视图时,不太依赖Java。所以我将// Create the text view下的部分替换为:

TextView textView = (TextView) findViewById(R.id.display_message);
textView.setText(message);

fragment_display_message.xml中,我有以下元素:

<TextView
    android:id="@+id/display_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

textView.setText(message);上抛出一个NullPointerException

我想知道为什么会发生这种情况,为什么不能这样做?

我想你应该打电话给

setContentView(R.layout.fragment_display_message);

在你调用

之前
TextView textView = (TextView) findViewById(R.id.display_message);
textView.setText(message);

但它是一个片段?

最新更新