首先,原谅破碎的英语。
我想知道如何使用listview中的删除按钮从其他类中删除数据。
我在MainActivity中使用一个按钮,将一些数据插入到名为昵称的数组中。
这是我的CustomAdapter类。
public class CustomAdapter extends ArrayAdapter<String>{
public CustomAdapter(Context context, String[] name) {
super(context,R.layout.custom_row ,name);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
final View customView = inflater.inflate(R.layout.custom_row, parent, false);
final String singleName = getItem(position);
TextView nickname = (TextView) customView.findViewById(R.id.nickname);
nickname.setText(singleName);
return customView;
}}
这是我在MainActivity类中的onClick
public void resultNickname(View view){
nicknames[] = dbHandler.retrieveName();
setContentView(R.layout.nickname_list);
ListAdapter listAdapter = new CustomAdapter(this,nicknames);
ListView nameListView = (ListView) findViewById(R.id.nickList);
nameListView.setAdapter(listAdapter);
}
我认为我的问题可以根据这个问题答案解决。 android: how to delete a row from a ListView with a delete button in the row 但我不能让它工作,因为我不明白项目的意思是什么以及如何在我的代码中实现它。
有人可以帮助我至少解释其他问题中的项目是什么意思以及如何在我的代码中实现它吗?
答案 0 :(得分:1)
public class CustomAdapter extends ArrayAdapter<String>
{
Context c1;
String s1[];
int s2[];
CustomAdapter(Context c,String s[],int s3[])
{
super(c,R.layout.tcustom,s);
this.c1=c;
this.s1=s;
this.s2=s3;
}
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
tv.setText(s1[position]);
Button bt = (Button) v.findViewById(R.id.button);
bt.setTag(position); //important so we know which item to delete on button click
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
int positionToRemove = (int)v.getTag(); //get the position of the view to delete stored in the tag
removeItem(positionToRemove);
notifyDataSetChanged(); //remove the item
}
});
return v;
}
public void removeItem(int position){
//convert array to ArrayList, delete item and convert back to array
ArrayList<String> a = new ArrayList<>(Arrays.asList(s1));
a.remove(position);
String[] s = new String[a.size()];
s=a.toArray(s);
s1 = s;
notifyDataSetChanged(); //refresh your listview based on new data
}
public int getCount() {
return s1.length;
}
public String getItem(int position) {
return s1[position];
}}
答案 1 :(得分:0)
尝试回答,首先我认为您应该使用删除按钮定义onclick,然后使用行的位置删除列表/数组。