当我尝试在手机上运行该应用程序时,当我尝试执行 Activity 3 时,它会强制关闭。 Logcat 说:
01-13 17:53:25.368: E/AndroidRuntime(3235): 引起: java.lang.NullPointerException 01-13 17:53:25.368: E/AndroidRuntime(3235): 在 android.app.activity3.onCreate(activity3.java:18)
第 18 行是
Button wg = (Button) findViewById(R.id.Back);
这是我的activity3.java的完整代码:
package android.app;
import android.app.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class activity3 extends Activity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
Button wg = (Button) findViewById(R.id.Back);
wg.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}
}
提前致谢
最佳答案
您需要修改您的xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!-- your textview -->
<TextView
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text1"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<!-- your back button -->
<Button
android:id="@+id/back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/Back"
/>
</RelativeLayout>
我做了什么:
- 从根relativelayout中删除了文本和方向,这些没有任何作用。
- 已修改您的高度和宽度,请随意更改。
- 添加了一个 ID 为 R.id.back 且文本为 @string/Back 的按钮。
您现在可以使用 findViewById(R.id.back) 引用您的按钮并设置您的点击监听器。
关于java - 我的应用程序无法启动 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8859578/