【发布时间】:2014-07-15 18:37:20
【问题描述】:
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton;
private Button mFalseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this, R.string.false_toast, Toast.LENGTH_SHORT).show();
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this, R.string.false_toast, Toast.LENGTH_SHORT).show();
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
当我注释掉没有 mTrueButton.setOnClickListener 和 mTrueButton.setOnClickListener 的代码部分时,模拟器能够显示按钮。但是,当我将它们放回原处时,即使 onClick(View v) 中没有任何方法,模拟器也会告诉我 QuizApp 已停止。导入语句没有任何问题,因为我使用了 command + shift + o 。有人知道为什么它不起作用吗?
这里是 fragment_quiz.xml 类:
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:gravity = "center"
android:orientation = "vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
android:text="@string/question_text" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/true_button"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/true_button" />
<Button
android:id = "@+id/false_button"
android:orientation="horizontal"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/false_button" />
</LinearLayout>
</LinearLayout>
这是 LogCat 的前几行给我的:
FATAL EXCEPTION: main
Process: com.example.geoquiz, PID: 1099
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.geoquiz/com.example.geoquiz.QuizActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
【问题讨论】:
-
从 logcat 发布堆栈跟踪。
-
onCreate 末尾的代码(以
if (savedInstanceState == null) {开头)似乎是 Eclipse 模板中遗留下来的。那应该还在吗? -
您可以尝试在您的 XML 中为按钮使用
android:Clickable="true"和android:onClick="methodToBeCalled"作为替代解决方案。 -
你能调试一下代码看看哪里出错了吗? nullPointerException 应该很容易捕获。
-
感谢您的所有帮助。错误原来是使用错误的文件设置内容视图。
标签: java android eclipse listener