【发布时间】:2014-12-26 23:27:50
【问题描述】:
我已经实现了一个自定义适配器和 listItemView。适配器将 onlclick 侦听器设置为 listItemView 上的按钮。 onclick 侦听器只是调用我在适配器中的私有方法并将要删除的项目的位置传递给它。我知道位置是正确的,因为数据库删除了正确的项目。我发现了类似的问题,但无法调整答案以适合我。非常感谢您的想法和想法。谢谢。
这是完整的适配器类
public class FoodListAdapter extends ArrayAdapter<FoodListItem> {
//private
private int type;
public FoodListAdapter(Context context, ArrayList<FoodListItem> _objects) {
super(context, 0, _objects);
type = 0;
}
public FoodListAdapter(Context context, ArrayList<FoodListItem> _objects, int _type) {
super(context, 0, _objects);
type = _type;
}
@Override
public View getView(int position, View reusableView, ViewGroup parent)
{
//Cast the reusable view to a listAdpaterItemView
FoodListItemView listItemView = (FoodListItemView) reusableView;
//Check if the listAdapterItem is null
if(listItemView == null)
{
//If it is null, then create a view.
listItemView = FoodListItemView.inflate(parent, this, type);
}
if (type == 2)
{
Button deleteButton = (Button) listItemView.findViewById(R.id.listItemViewDeleteBTN);
deleteButton.setTag(new Integer(position));
}
//Now we need to set the view to display the data.
listItemView.setData(getItem(position));
return listItemView;
}
}
这是我在片段中使用的部分代码。请注意,我在 listAdapter 的类中有一个私有变量,但我认为我不需要它。
private void displayListForDate(Calendar _date)
{
//get the list view
ListView listView = (ListView) getView().findViewById(1);
//Clear the listview by removing the listadapter and setting it to null.
//listView.setAdapter(null);
//First we must get the items.
Global global = (Global) getActivity().getApplicationContext();
DietSQLiteHelper database = global.getDatabase();
//Create a list to hold the items we ate. This list will then be added to the listView.
final ArrayList<FoodListItem> consumedList;
//Add the items to the array.
consumedList = database.getConsumed(_date.getTimeInMillis());
//Create an adapter to be used by the listView
listAdapter = new FoodListAdapter(getActivity().getBaseContext(), consumedList, 2);
//Add the adapter to the listView.
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
consumedList.remove(position);
listAdapter.notifyDataSetChanged();
}
});
}
【问题讨论】:
-
你在哪里从适配器中删除数据?
-
在deleteItem()中我调用remove(item),这个方法在adapater类中。
-
可以发一下
remove(item)方法的代码吗? -
remove方法是继承的,我没有实现或者覆盖它。
-
你能发布完整的适配器代码吗?
标签: android android-listview android-adapter