我正在尝试在 android 中创建自定义 ListView 。
当我尝试在 HistoryAdapter
-> getView
中访问我的数组列表变量 historyArrayList
时,historyArrayList
总是返回我最后添加的元素数组列表。
public class HistoryDetails extends Activity {
List<HistoryInfoClass> historyArrayList = new ArrayList<HistoryInfoClass>() ;
DBAdapter db = new DBAdapter(this);
private class HistoryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public HistoryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return historyArrayList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.history_listview, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//PROBLEM HERE " historyArrayList.get(position).Time " always give me last element in historyArrayList, and historyArrayList.get(0).Time give me last element too, and get(1)
holder.text.setText(Integer.toString( historyArrayList.get(position).Time ));
holder.text2.setText(Integer.toString( historyArrayList.get(position).Time1 ));
return convertView;
}
private class ViewHolder {
TextView text;
TextView text2;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.historydetails);
super.onCreate(savedInstanceState);
HistoryFromDBToArray();
ListView l1 = (ListView) findViewById(R.id.ListView01);
l1.setAdapter(new HistoryAdapter(this));
l1.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(), "You clciked ", Toast.LENGTH_LONG).show();
}
});
}
class HistoryInfoClass {
Integer Time = 0,
Time1 = 0;
}
private void HistoryFromDBToArray(){
HistoryInfoClass History = new HistoryInfoClass();
historyArrayList.clear();
db.open();
int i =0;
Cursor c = db.getHistory("history");
startManagingCursor(c);
if (c.moveToFirst())
{
do {
History.Time = c.getInt(1);
History.Time1 = c.getInt(2);
historyArrayList.add(History);
// Here "historyArrayList.get(i).Time" return true value (no last record)
i++;
} while (c.moveToNext());
}
db.close();
}
}
最佳答案
当您填充 historyArrayList
时,每次循环都会更新和添加相同的对象 History
。尝试在循环开始时重新初始化 History
:
do {
// Initialize History
History = new HistoryInfoClass();
History.Time = c.getInt(1);
History.Time1 = c.getInt(2);
historyArrayList.add(History);
i++;
} while (c.moveToNext());
关于java - Android自定义 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4048224/