我为我的项目实现了一个自定义数组适配器,到目前为止我能够添加和删除它的项目,它也会在ListView中显示它们 动态..但是我在MainActivity中有一个按钮(包含ListView),单击时我想显示所有行项。 到目前为止,我将所有值附加到StringBuilder后,而不是适配器中的数据是: 的 com.baseadapter.C @ 4052b9b8com.baseadapter.C @ 4052f490com.baseadapter.C @ 40531378com.baseadapter.C @ 4053415
arrayadapter和arraylist设置如下:
ArrayList<C> arrayvalues= new ArrayList<C>();
MyAdapter adapter;
adapter= new MyAdapter(MainActivity.this, R.layout.list_item,
arrayvalues);
我的集合类的代码是:
public class C {
String the_text;
public String getText() {
return the_text;
}
public void setText(String the_text) {
this.the_text = the_text;
}
public C(String the_text) {
super();
this.the_text = the_text;
}
}
我用来迭代适配器的代码是:
btn_done.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
StringBuilder b = new StringBuilder();
for(int i=0 ; i<adapter.getCount() ; i++){
b.append(adapter.getItem(i));
}
Toast.makeText(getApplicationContext(), b.toString(), Toast.LENGTH_SHORT).show();
}
});
和自定义适配器代码(以防万一,虽然我不认为问题出在这里):
public class MyAdapter extends ArrayAdapter<C> {
Context context;
int layoutResourceId;
ArrayList<C> data = new ArrayList<C>();
public MyAdapter(Context context, int layoutResourceId,
ArrayList<C> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
myholder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new myholder();
holder.tv = (TextView) row.findViewById(R.id.tv_num);
holder.btnDelete = (ImageButton) row.findViewById(R.id.btn_delete);
row.setTag(holder);
} else {
holder = (myholder) row.getTag();
}
C c=data.get(position);
holder.tv.setText(c.getText());
//String c=data.get(position);
//holder.tv.setText(c.g.getName());
holder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
data.remove(position);
notifyDataSetChanged();
}
});
return row;
}
static class myholder {
TextView tv;
ImageButton btnDelete;
}
}
我该怎么做才能获得适配器中的实际值?ps:请附上代码,谢谢
答案 0 :(得分:0)
更改以下循环代码。它现在可以工作了。
for(int i=0 ; i<adapter.getCount() ; i++)
{
C itemObject=adapter.getItem(i);
if(itelObject!=null)
b.append(itemObject.getText());
}
答案 1 :(得分:0)
您应该覆盖适配器中的 getItem()方法:
@Override
public C getItem(int position) {
return data.get(position);
}
更新循环代码以获取“C”的文本或覆盖“C”toString()方法,如建议的那样。