我正在尝试按照本指南为列表视图创建自定义行。当我逐行遵循指南时,它起作用了,只更改名称和一些细节以适应我自己行中的不同视图。但是,我希望能够通过单击按钮来添加行,因此示例中提供的数组将不起作用。我尝试创建一个 Requirement 类型的 ArrayList,它由 Requirement 类定义,以替换用于创建适配器的数组,但它不起作用。我无法再打开测试按钮的意图,因为它在尝试初始化列表视图时崩溃,错误是空指针异常。
我在 onCreate 中调用这个函数:
ArrayList<Requirement> req_data_list;
RequirementAdapter adapter;
private void initialize_listView(){
req_data_list.add(new Requirement());
RequirementAdapter adapter = new RequirementAdapter(this, R.layout.requirements_item, req_data_list);
ListView req_list = (ListView) findViewById(R.id.Requirement_listview);
req_list.setAdapter(adapter);
}
这是 ArratList 元素的类:
public class Requirement{
public String name,requirement_id,type,notes;// These variables will be implemented later, and correspond to elements not yet included.
public int men, hours, elevation,req_count;
public boolean breathing_air;
public Requirement(){
super();
}
public Requirement(int men_p, int hours_p, int elevation_p, int req_count_p, String name_p,
String requirement_id_p, String type_p, String notes_p, boolean breathing_air_p){
super();
//TODO this constructor will be defined later.
}
}// Requirement
这是定义适配器的类:
public class RequirementAdapter extends ArrayAdapter<Requirement>{
Context context;
int layoutResourceId;
ArrayList<Requirement> data = null;
public RequirementAdapter(Context context, int layoutResourceId, ArrayList<Requirement> data ){
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data=data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
RequirementHolder holder = null;
if(row==null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId,parent,false);
holder = new RequirementHolder();
holder.name = (TextView) row.findViewById(R.id.Name_Text);
holder.name_e = (EditText) row.findViewById(R.id.Name_Edit);
holder.men = (Button) row.findViewById(R.id.Men_But);
row.setTag(holder);
} // if
else{
holder = (RequirementHolder)row.getTag();
} // else
return row;
} // getView
static class RequirementHolder{
TextView name;
EditText name_e;
Button men;
}
}
最后,这是在列表视图中添加新元素的函数:
private void new_layout_element(){
req_data_list.add(new Requirement());
adapter.notifyDataSetChanged();
}
我怎样才能解决这个问题?谢谢!
编辑:如果有帮助,我发现如果我将数组列表改回数组,无论数组有多长,都只会显示一个元素。