displayTextView.setText(“更改代码”);错了吗?
一个简单的 android Hello World:
MainActivity.java:
package com.amaker.ch02.app;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private TextView displayTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayTextView = (TextView)findViewById(R.id.DisplayTextView);
displayTextView.setText("change in the code"); <--Right if delete the line
}
}
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id = "@+id/DisplayTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
运行,android 将显示: 抱歉,应用程序意外停止。请重试。,但是正如我在代码 MainActivity.java
中指出的那样,如果我删除代码 displayTextView.setText("change in the code" );
,一切正常。
这行代码有什么问题吗?
A simple android Hello World:
MainActivity.java:
package com.amaker.ch02.app;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private TextView displayTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayTextView = (TextView)findViewById(R.id.DisplayTextView);
displayTextView.setText("change in the code"); <--Right if delete the line
}
}
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id = "@+id/DisplayTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
Run, and android will display: sorry, the application has stopped unexpectedly. Please try again., but just as I point in the code MainActivity.java
, if I delete the code displayTextView.setText("change in the code");
, everything is OK.
What's wrong with the line of code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的代码看起来是正确的。尝试清理并构建项目。还尝试更改 xml 以及代码中的 textview id。您的
DisplayTextView
可能会为 null,因此会产生此问题。调试代码并找到实际原因。或向我们提供 logcat 详细信息。your code seems right. try to clean and build the project. also try to change textview id in xml as well as in your code.your
DisplayTextView
might coming null so creating this problem. debug the code and find the actual cause. or provide us logcat details.