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已停止。导入语句没有任何问题,因为我使用了命令+ 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)
答案 0 :(得分:2)
在您的代码中使用
设置内容视图activity_quiz
并且您说您发布的xml称为
fragment_quiz
你得到一个空指针异常,因为你定义的按钮不在activity_quiz
中