作为ussual,我可以轻松地将更多项添加到ListView中。但是,当我的ListView在Fragment里面时问题就出现了。
public class QuestionFragment extends Fragment {
ExaminationActivity activity;
Question question;
TextView lblQuestion;
ListView listChoice;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = (ExaminationActivity) getActivity();
question = activity.getCurrentView();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_question, container, false);
lblQuestion = (TextView) view.findViewById(R.id.lbl_question);
lblQuestion.setText(question.getTitle());
listChoice = (ListView) view.findViewById(R.id.list_option);
listChoice.setAdapter(new ChosenAdapter(activity, 0, question.getMutipleChoice(), question.getUserChoice()));
return view;
}
private class ChosenAdapter extends ArrayAdapter<String> {
Context context;
ArrayList<String> multipleChoice;
int selected;
public ChosenAdapter(Context context, int resource, ArrayList<String> multipleChoice, int selected) {
super(context, resource, multipleChoice);
this.context = context;
this.multipleChoice = multipleChoice;
this.selected = selected;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
View view = inflater.inflate(R.layout.view_chosen_item, parent);
RadioButton radio = (RadioButton) view.findViewById(R.id.radio_choice);
radio.setChecked((selected == position));
TextView lbl_title = (TextView) view.findViewById(R.id.lbl_title);
lbl_title.setText(multipleChoice.get(position));
Log.i("INFO", "chosen " + multipleChoice.get(position));
return view;
}
}
}
和错误:
10-24 22:48:23.391 31862-31862 / com.dragonfly.tracnhiem E / AndroidRuntime:FATAL EXCEPTION:main 处理:com.dragonfly.tracnhiem,PID:31862 android.view.InflateException:二进制XML文件行#15:AdapterView不支持addView(View,LayoutParams) 在android.view.LayoutInflater.inflate(LayoutInflater.java:539) 在android.view.LayoutInflater.inflate(LayoutInflater.java:423) 在android.view.LayoutInflater.inflate(LayoutInflater.java:374) 在com.dragonfly.tracnhiem.activity.QuestionFragment $ ChosenAdapter.getView(QuestionFragment.java:65)
答案 0 :(得分:0)
与适配器一起使用的ListView
不允许从代码或XML布局添加视图(如您的情况)。
相反,您需要从代码中将数据项添加到适配器。如果在视图与适配器关联后添加了数据项,请记得调用adapter.notifyDataSetChanged()
。请查看本指南以获取更多信息:Building Layouts with an Adapter