Android - ListView ArrayAdapter VIewHolder
很久沒寫Android,一寫突然忘掉一堆,也找不到我想要的解,
自己再重寫一遍,(原來我認為的基本,結果當我需要的時候,找不到,這基本算是滿重要的)
首先要先建立自己的Model
MessageItem 如下
public class MessageItem {
public String Title = "初始標題";
public String Content = "知始內容";
public String getTitle() {
return this.Title;
}
public void setTitle(String value) {
this.Title = value;
}
public String getContent() {
return this.Content;
}
public void setContent(String value) {
this.Content = value;
}
}
然後建立繼承ArrayAdapter,並使用泛型
public class MessageListAdapter extends ArrayAdapter<MessageItem> {
private Context mContext;
static class ViewHolder{
TextView mTitle;
TextView mContent;
}
public MessageListAdapter(Context ctx) {
super(ctx, R.layout.item_message);
mContext = ctx;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_message, null);
holder.mTitle = (TextView) convertView.findViewById(R.id.tv_title);
holder.mContent = (TextView) convertView.findViewById(R.id.tv_content);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MessageItem item = this.getItem(position);
holder.mTitle.setText(item.getTitle());
holder.mContent.setText(item.getContent());
return convertView;
}
}
在Activity頁面,取得ListView 後,設定Adapter
mListMessgae = (ListView) this.findViewById(R.id.list_message);
mAdapter = new MessageListAdapter(this);
mListMessgae.setAdapter(mAdapter);
這之間當然有要撈資料的部分使用
AsyncTask
public class LoadTask extends AsyncTask<Void, Void, Void> {
public List<MessageItem> mItems = new ArrayList<MessageItem>();
@Override
protected Void doInBackground(Void... voids) {
mItems = appApi.GetMessages();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mAdapter.clear();;
mAdapter.addAll(mItems);
mAdapter.notifyDataSetChanged();
}
}
Activity OnCreate的時候執行
LoadTask task = new LoadTask();
task.execute();
完成
我的文章竟然沒這段,重寫一遍做一個記錄。