Android Studio中使用LayoutInflater自定义AlertBox失效求助
问题分析与修复方案
看起来你遇到的崩溃问题是由两个关键错误导致的NullPointerException,咱们一步步来解决:
1. 错误地从点击的View中查找自定义Dialog控件
你当前代码里的这段:
TextView title = (TextView) view.findViewById(R.id.title); ImageButton imageButton = (ImageButton) view.findViewById(R.id.image); TextView laman = (TextView) view.findViewById(R.id.laman);
这里的view是用户点击的Button,而title、imageButton、laman是你自定义AlertDialog布局custom_layout里的控件,并不是Button的子控件。所以这样查找会返回null,后续调用setText()或setImageResource()时就会触发空指针异常,直接导致应用崩溃。
你需要从**inflate出来的自定义Dialog布局对象v**中查找这些控件,而不是点击的Button。
2. Inflate布局时传入了错误的父容器
这段代码的第二个参数存在问题:
View v = inflater.inflate(R.layout.custom_layout, (ViewGroup) view, false);
LayoutInflater.inflate()的第二个参数是布局要依附的父容器,你现在把点击的Button作为父容器,这会把自定义Dialog的布局错误地附加到Button上,既不符合逻辑,还会引发布局层级错误。正确的做法是传入null,因为AlertDialog.Builder会自动把布局添加到Dialog的正确容器中。
修正后的完整checkAnswer方法
public void checkAnswer(View view) { // Get pushed button. Button answerBtn = (Button) findViewById(view.getId()); String btnText = answerBtn.getText().toString(); // 初始化Dialog和自定义布局 AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); // 传入null作为父容器,由AlertDialog处理布局依附 View v = inflater.inflate(R.layout.custom_layout, null, false); // 从自定义Dialog布局v中查找控件 TextView title = (TextView) v.findViewById(R.id.title); ImageButton imageButton = (ImageButton) v.findViewById(R.id.image); TextView laman = (TextView) v.findViewById(R.id.laman); if (btnText.equals(rightAnswer)) { // Correct! startService(new Intent(roxasquiz.this, tamamusic.class)); imageButton.setImageResource(R.drawable.check); title.setText("Magaling!"); laman.setText("Tama ang iyong sagot! "); rightAnswerCount++; } else { // Wrong... startService(new Intent(roxasquiz.this, malimusic.class)); title.setText("Magsanay pa!"); laman.setText("Mali ang iyong sagot! "); imageButton.setImageResource(R.drawable.wrong); } builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (quizCount == QUIZ_COUNT) { // Show Result. Intent intent = new Intent(getApplicationContext(), roxasresult.class); intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount); startActivity(intent); } else { quizCount++; showNextQuiz(); } } }); builder.setView(v); builder.setCancelable(false); builder.show(); }
额外检查项
请确认你的custom_layout.xml文件中确实存在R.id.title、R.id.image、R.id.laman这三个控件,并且ID拼写完全一致——有时候拼写错误也会导致findViewById返回null,引发同样的崩溃问题。
内容的提问来源于stack exchange,提问作者jane
相关产品推荐
相关产品推荐

