我在尝试找出这个数组适配器时遇到了很多麻烦。
我已经在一些教程和此页面How to add/remove item from listview in android when click button in item listview
的帮助下将其整合在一起了但我有一个问题,其中"适配器"设置为" null"当getView运行时。我不知道这是怎么回事。我已经解决了将备份适配器备份到backupAdapter的可怕hacky解决方案,然后在需要调用adapter.notifyDataSetChanged()时将其复制回来。
我发现第一次使用deleteButton时,resetAdapter发现适配器为null并从backupAdapter复制值。在那之后它很好并且不需要再次恢复。所以我的代码可行,但它很糟糕。我做错了什么?
public class EditTaskList extends Activity {
private static ArrayList<Something> list;
private CustomAdapter adapter;
private CustomAdapter backupAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_task_edit);
ListView listView = (ListView)findViewById(R.id.edit_task_listview);
list = MainActivity.getMasterList();
CustomAdapter adapter = new CustomAdapter(this, list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
backupAdapter = adapter;
}
public void resetAdapter(){
if(adapter == null){
System.out.println("Not fixed");
adapter = backupAdapter;
}
else{System.out.println("Fixed!");}
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_task_list, menu);
return true;
}
public class CustomAdapter extends ArrayAdapter<Something>{
//private Context context;
private ArrayList<Something> things;
private LayoutInflater inflater;
class ViewHolder {
public TextView text;
public Button editButton;
public Button deleteButton;
}
public CustomAdapter(Context context, ArrayList<Something> things) {
super(context, R.layout.edit_task_list_item, things);
inflater = LayoutInflater.from(context);
this.things = things;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// reuse views
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.edit_task_list_item, null);
// configure view holder
viewHolder.text = (TextView) ConvertView.findViewById(R.id.edit_task_name);
viewHolder.editButton = (Button) convertView.findViewById(R.id.edit_task_edit);
viewHolder.deleteButton = (Button) convertView.findViewById(R.id.edit_task_delete);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.text.setTag(position);
viewHolder.text.setText(things.get(position).toString());
viewHolder.deleteButton.setTag(position);
viewHolder.editButton.setTag(position);
viewHolder.deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
int tag = (Integer)view.getTag();
things.remove(tag);
resetAdapter();
}
});
return convertView;
}
}
}
答案 0 :(得分:2)
这一行:
CustomAdapter adapter = new CustomAdapter(this, list);
创建本地变量,因此字段 adapter 永远不会被初始化。相反,您希望将新创建的适配器分配给字段:
adapter = new CustomAdapter(this, list);