我有一个ArrayList,它使用ArrayAdapter在ListView中显示其列表数据
每个ListView项目都有一个TextView和一个Button。单击该按钮可更新ArrayList中保存的数据,这样可以正常工作。如何让ListView同时更新?我知道如何从创建ArrayAdapter的Activity中执行此操作,因为我可以调用itemAdapter.notifyDataSetChanged()来更新视图。但是当点击Button myButton时,我不知道如何在ArrayAdapter类(即ListItemAdapter)中完成它。
有什么想法吗?感谢。
StartActivity Class
public class StartActivity extends Activity {
ArrayList<DataRecord> datalist;
ListView listView;
ListItemAdapter itemAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
datalist = new ArrayList<DataRecord>();
listView = (ListView) findViewById(R.id.ListViewId);
itemAdapter = new ListItemAdapter(this, android.R.layout.simple_list_item_1, datalist);
listView.setAdapter(itemAdapter);
DataRecord dataRecord = new DataRecord("Data Item 1 ");
datalist.add(dataRecord);
dataRecord = new DataRecord("Data Item 2 ");
datalist.add(dataRecord);
dataRecord = new DataRecord("Data Item 3");
datalist.add(dataRecord);
itemAdapter.notifyDataSetChanged();
}
}
ListItemAdapter类
public class ListItemAdapter extends ArrayAdapter<DataRecord> {
private ArrayList<DataRecord> datalist;
public ListItemAdapter(Context context, int textViewResourceId, ArrayList<DataRecord> datalist) {
super(context, textViewResourceId, datalist);
this.datalist = datalist;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_row, null);
}
Button mybutton = (Button)v.findViewById(R.id.pushBtn);
final DataRecord dataitem = datalist.get(position);
mybutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dataitem.information = "Hello";
for (int i = 0; i < datalist.size(); i++) {
Log.d("Item", datalist.get(i).information); // this shows the ArrayList gets updated
}
}
});
if (dataitem != null) {
TextView listText = (TextView) v.findViewById(R.id.list_text);
if (listText != null) {
listText.setText(dataitem.information);
}
}
return v;
}
}
答案 0 :(得分:3)
只需在适配器中使用相同的方法,但没有对象引用,因为您位于对象的上下文中
mybutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dataitem.information = "Hello";
notifyDataSetChanged();
}
});
答案 1 :(得分:0)
试试这个
mybutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//
//update data
//
this.notifyDataSetChanged();
}
});
答案 2 :(得分:0)
mybutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dataitem.information = "Hello";
ListItemAdapter.this.notifyDataSetChanged();
}
});