【发布时间】:2014-05-05 21:11:57
【问题描述】:
我有一个 ListView,其中每个列表项行都有一个自定义布局,其中包含一个人的姓名和一个删除按钮。
我不知道应该如何对删除按钮中的事件处理程序进行编码,以便删除该行。我知道我需要删除 ArrayList 中的项目,然后调用 adapter.notifyDataSetChanged(),但我无法从自定义行布局类中访问 ArrayList 或适配器。
我看到过一些类似的问题,但我没有看到任何涉及自定义列表项布局内的删除按钮。
我能想到的唯一可能的解决方案是将对适配器对象的引用以及对 ArrayList 的引用传递给 PersonLayout(在适配器的 getView() 方法中执行此操作),但必须有更好的解决方案。
代码如下:
/**
* PersonLayout is the layout for a single list item (row) in the listview.
* It displays the name for a single person.
*
* Each PersonLayout row also contains a delete button that is used to delete that row.
*
* I do not know what I should do in onClick() for the delete button
* in order to delete this row.
*/
public class PersonLayout extends RelativeLayout implements OnClickListener
{
private TextView nameTextView;
private Button deleteButton;
private Person person;
private Context context;
public PersonLayout(Context context)
{
super(context);
}
public PersonLayout(Context context, Person p)
{
super(context);
this.context = context;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.listview_person, this, true);
nameTextView = (TextView) findViewById(R.id.nameTextView);
deleteButton = (Button) findViewById(R.id.deleteButton);
this.setOnClickListener(this);
setPerson(p);
}
public void setPerson(Person p)
{
person = p;
nameTextView.setText(p.getName());
}
@Override
public void onClick(View v)
{
// handle delete button click
// How do I delete the current list item (row) ?
}
} // end class PersonLayout
/**
* The custom adapter for the ListView.
*/
public class PeopleListAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Person> people;
public PeopleListAdapter(Context context, ArrayList<Person> people)
{
this.context = context;
this.people = people
}
@Override
public int getCount()
{
return people.size();
}
@Override
public Object getItem(int position)
{
return people.get(position);
}
@Override getItemId(int position)
{
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
PersonLayout personLayout = null;
Person person = people.get(position);
if (convertView == null)
{
personLayout = new PersonLayout(context, person);
}
else
{
personLayout = (PersonLayout) convertView;
personLayout.setPerson(person);
}
return personLayout;
}
} // end class PeopleListAdapter
【问题讨论】:
-
这看起来是非常规的创建布局的方法。 Listview/gridview 通过扩展适配器类可以更高效、更轻松地处理
标签: android android-listview android-adapter