gpt4 book ai didi

java - Android 教程 - 当我尝试访问现有 TextView 时,为什么我的应用程序崩溃

转载 作者:行者123 更新时间:2023-12-01 11:47:44 26 4
gpt4 key购买 nike

我正在学习 Android 教程 here 。我按照他们的方式实现它没有问题。但是,我试图理解为什么这种其他方式会失败。如果我启用两个注释掉的行并注释掉它们后面的行,我的应用程序就会崩溃。在我看来,我应该能够通过 ID 引用现有的 TextView ,设置其文本,然后将内容 View 设置为包含我引用的 TextView 的布局。我确信我以错误的方式思考这个问题,但我想澄清为什么它不起作用。

    String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
//TextView textView = (TextView)findViewById(R.id.text_view);
TextView textView = new TextView(this); //comment this out
textView.setTextSize(40);
textView.setText(message);
//setContentView(R.layout.activity_display_message);
setContentView(textView); //comment this out

和我的 xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.<myname>.myfirstapp.DisplayMessageActivity">

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

</RelativeLayout>

最佳答案

It seems to me that I should be able to reference an existing text view by ID, set its text, and then set the content view to be the layout that contains the text view I have referenced

逻辑错误。只有调用setContentView()后,才能使用findViewById()从布局文件中获取 View ,然后调用 View 的方法。

您的intent.getStringExtra(MyActivity.EXTRA_MESSAGE)可以在OnCreate()中的任何位置调用,因此它的位置没有任何问题。

关于java - Android 教程 - 当我尝试访问现有 TextView 时,为什么我的应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29024200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com