我試圖讓用戶在我的應用程序中創建一個調查,但我正在努力與我的一塊代碼。用戶可以點擊「添加答案」,它會添加一個RadioButton/EditText。然後點擊「刪除答案」,它應該刪除這些。它用於刪除已添加的第一個Radiobutton/RditText,但如果我已經添加了2個或更多RadioButton,則會引發錯誤。在Android中添加/刪除RadioButton/EditText
任何想法我的代碼有什麼問題?
mAddAnswer = (Button) v.findViewById(R.id.addAnswer);
mAddAnswer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
RadioButton question = new RadioButton(getActivity().getApplicationContext());
question.setId(newQuestionRadioId);
newQuestionRadioId += 1;
mAnswersGroup.addView(question);
EditText answer = new EditText(getActivity().getApplicationContext());
answer.setInputType(InputType.TYPE_CLASS_TEXT);
answer.setId(newQuestionId);
newQuestionId += 1;
answer.setHint("Enter answer");
mAnswerHolder.addView(answer);
questionNumber += 1;
}
});
mRemoveAnswer = (Button) v.findViewById(R.id.removeAnswer);
mRemoveAnswer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mAnswersGroup.getChildCount() > 1) {
mAnswersGroup.removeViewAt(newQuestionRadioId - 1);
mAnswerHolder.removeViews(questionNumber - 1, questionNumber - 1);
newQuestionId -= 1;
newQuestionRadioId -= 1;
questionNumber -= 1;
}
}
});
的logcat:
02-16 16:39:49.295: E/AndroidRuntime(2532): FATAL EXCEPTION: main
02-16 16:39:49.295: E/AndroidRuntime(2532): java.lang.NullPointerException
02-16 16:39:49.295: E/AndroidRuntime(2532): at android.view.ViewGroup.removeViewsInternal(ViewGroup.java:2231)
02-16 16:39:49.295: E/AndroidRuntime(2532): at android.view.ViewGroup.removeViews(ViewGroup.java:2179)
02-16 16:39:49.295: E/AndroidRuntime(2532): at com.example.surveymetest.AddQuestionFragment$2.onClick(AddQuestionFragment.java:106)
02-16 16:39:49.295: E/AndroidRuntime(2532): at android.view.View.performClick(View.java:2485)
02-16 16:39:49.295: E/AndroidRuntime(2532): at android.view.View$PerformClick.run(View.java:9080)
02-16 16:39:49.295: E/AndroidRuntime(2532): at android.os.Handler.handleCallback(Handler.java:587)
02-16 16:39:49.295: E/AndroidRuntime(2532): at android.os.Handler.dispatchMessage(Handler.java:92)
02-16 16:39:49.295: E/AndroidRuntime(2532): at android.os.Looper.loop(Looper.java:130)
02-16 16:39:49.295: E/AndroidRuntime(2532): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-16 16:39:49.295: E/AndroidRuntime(2532): at java.lang.reflect.Method.invokeNative(Native Method)
02-16 16:39:49.295: E/AndroidRuntime(2532): at java.lang.reflect.Method.invoke(Method.java:507)
02-16 16:39:49.295: E/AndroidRuntime(2532): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-16 16:39:49.295: E/AndroidRuntime(2532): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-16 16:39:49.295: E/AndroidRuntime(2532): at dalvik.system.NativeStart.main(Native Method)
你能提供更多關於你接收到什麼錯誤的細節嗎? –
logcat的副本會很好。 – NasaGeek
對不起,現在附上。 –