自定义适配器的常用思路

自定义适配器的常用思路:list + 对象

list:需要适配的数据集合;注意list只能new一次,否则适配器notifyDataSetChanged的时候找不到对象。
对象:getItem(postion)对应的数据对象,该对象的数据对应控件每个item上需要的数据。

列如:

package com.ylink.gesstrader.adapter;

import java.util.ArrayList;
import java.util.List;

import com.ylink.gesstrader.R;
import com.ylink.gesstrader.adapter.domain.NewsItem;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

public  class NewsItemDragListAdapter extends BaseAdapter{


protected Activity mContext;
private LayoutInflater inflater;
public ArrayList<NewsItem> list;

public NewsItemDragListAdapter(
Activity context,
ArrayList<NewsItem> list){
this.mContext = context;
this.list = list;

}
public int getCount() {
if(list != null)
return list.size();
else
return 0;
}

public Object getItem(int position) {

return list == null ? null : list.get(position);
}

public long getItemId(int position) {

return position;
}

public View getView(int position, View convertView, ViewGroup parent) { 
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout list_item = null;

list_item = (RelativeLayout)inflater.inflate(R.layout.list_item_date_str_middle, null);
TextView item_content = (TextView)list_item.findViewById(R.id.month_datestr_tv);
item_content.setText(list.get(position).getItems_title());
TextView item_date = (TextView)list_item.findViewById(R.id.month_date_tv);
item_date.setText(list.get(position).getItems_title_date());

return list_item;
}
}

Activity调用:
list_adapter = new NewsItemDragListAdapter(NewsItemListActivity.this,list);

list_view.setAdapter(list_adapter);
list_view.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
NewsItem row = (NewsItem)(parent.getAdapter().getItem(position));
String title = row.getItems_title();
String datetime = row.getItems_title_date();
String m_szType = row.getM_szType();
String m_uiInfoID = row.getM_uiInfoID();

Intent intent = new Intent();
    Bundle bundle = new Bundle();
    bundle.putString("title", title);
    bundle.putString("datetime", datetime);
    bundle.putString("m_szType", m_szType);
    bundle.putString("m_uiInfoID", m_uiInfoID);
   
    intent.putExtras(bundle);
    intent.setClass(NewsItemListActivity.this, NewsDetailActivity.class);
    NewsItemListActivity.this.startActivity(intent);
}

});

你可能感兴趣的:(自定义)