![](/img/trans.png)
[英]Why does my Android react native app crash instantly when I try to bridge device listening modules from Java
[英]Android Tutorials — Why does my app crash when I try to access an existing Text View
我在这里浏览Android教程。 我完全可以按照他们的方式来实现它。 但是,我试图理解为什么这种方式失败了。 如果我启用了两条注释行,并按照注释注释掉了这两行,我的应用程序将崩溃。 在我看来,我应该能够通过ID引用现有的文本视图,设置其文本,然后将内容视图设置为包含我所引用的文本视图的布局。 我确定我在想这是错误的方法,但是我想澄清一下为什么它不起作用。
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>
在我看来,我应该能够通过ID引用现有的文本视图,设置其文本,然后将内容视图设置为包含我已引用的文本视图的布局。
逻辑是错误的。 仅在调用setContentView()之后,可以使用findViewById()从布局文件获取视图,然后可以调用视图的方法。
您的intent.getStringExtra(MyActivity.EXTRA_MESSAGE)
可以在OnCreate()的任何位置调用,因此它的位置没有错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.