動態添加數據適配器adapter
Adapter是適配器,許多UI組件需要搭配Adapter來顯示界面,例如Spinner與ListView,另外當我們需要動態的添加數據給UI組件時就需要Adapter了。
我們來介紹幾個常見的Adapter:
SimpleAdapter extends Baseadapter(comman)
******************************************************************************
這兩個適配器非常常見,也非常有用,通常傳輸的數據可以是ArrayList<>封裝的數據。
示例如下:ArrayAdapter
private String[] string={"china","america","japan"};
List list=new ArrayList<String>();
for(int i=0;i<string.length;i++)
{
list.add(string[i]);
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.simple_spinner_item,list);
首先我們定義封裝數據,然後再定義Adapter,最後調用setAdapter()方法。
ArrayAdapter有三個參數,第一個參數爲Activity.this,第三個參數爲動態添加給adapter的數據
對於第二個數據:
R.layout.simple_spinner_item:意思是將數據傳給一個簡單地TextView組件
示例:SimpleAdapter
public class SimpleAdapter extends Activity{
private String[] names =new String[]{"nick","lebron","kobe","kevin"};
private int[] imgsIds[] =new Int[] {R.drawable.1,R.drawable.2,R.drawable.3,R.drawable.4};
@Override
public void onCreate(Bundle savedInsatnceState)
{
super.onCreate(savedInsatnceState);
setTitle("simpleadapter");
setContentView(R.layout.main);
List<Map><String,Object> list=new ArrayList<Map><String,Object>();//創建動態數組ArrayList
for(int i=0;i<names.length;i++){
Map<String,Object> map=new HashMap=<String,Object>;
map.put("name",names[i]);
map.put("headerImg",imgsIds[i]);
list.add(map);
}
SimpleAdapter adapter=new SimpleAdaper(this,list,R.layout.main,new String[]{"name","headerImg"},new int[]{R.id.name,R.id.headerImg});
ListView list=(ListView)findViewById(R.id.mylist);
list.setAdaper(adapter);
}
}
接下來我們介紹另一個常用的Adapter:BaseAdapter
BaseAdapter implements SpinnerAdapter implements ListViewAdapter(可用於ListView和Spinner)
示例:
public MyListView extensds Activity{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInsatnceState);
mDate=getDate();
MyAdapter myadapter=new MyAdapter(this);
ListView list=(ListView)findById(R.id.myList);
setAdapter(myadapter);
}
private List<Map<String, Object>> getData() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "G1");
map.put("info", "google 1");
map.put("img", R.drawable.i1);
list.add(map);
//添加第二個Map數據
map = new HashMap<String, Object>();
map.put("title", "G2");
map.put("info", "google 2");
map.put("img", R.drawable.i2);
list.add(map);
//添加第三個Map數據
map = new HashMap<String, Object>();
map.put("title", "G3");
map.put("info", "google 3");
map.put("img", R.drawable.i3);
list.add(map);
return list; //返回List數據
}
@verride
protected void onListItemClicked(ListView 1,View v,int position,long id){
Log.v("MyListView4_click",(String)mData.get(position).get("title"));
}
public void showInfo(){
new AlertDiolog.Builder(this)
.setTitle("MyListView")
.setMessage(Introduce)
.setPositiveButton("Ensure",new DialogInterface.OnClickListener()
{@Override
public void onClick(DialogInterface dialog,int which){} }).show();
}
}
private final class ViewHolder{
public ImageView img;
public TextView title;
public TextView info;
public Button viewBu;
}
public class MyAdapter extens BaseAdapter{
private LayoutInlfater myInflater;
public MyAdapter(Context context){
this.myInflater=LayoutInflater.from(context);
}
@Override
public int getCount(){
return mDate.size();}
@Override
public long getItemId(int position){
return null;}
@Override
public Object getItmeId(int position){
return 0;}
@Override
public View getview(int position,View convertView,ViewGroup parent){
ViewHolder holder=null;
if(convertView==null){
holder=new ViewHolder();
convertView=mInflater.inflate(R.layout.list,null)
//inflate函數有兩個參數--解析界面佈局
holder.img=(ImageView)convertView.findViewById(R.id.img);
holder.title=(TextView)convertView.findViewById(R.id.title);
holder.info=(TextView)convertView.findViewById(R.id.info);
holder.viewBu=(TextView)convertView.indViewById(R.id.viewBu);
convertView.setTag(holder);
}else{holder=(ViewHolder)convertViewgetTag();}
holder.img.setBackgroundResounce((Integer)mDate.get(position).get("img"));
holder.title.setText((String)mdata.get(position).get("title"));
holder.info.setText((String)mData.get(position).get("info"));
holder.viewBu.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
showInfo(); }
});
return convertView;
}
}
}
getView()方法有三個參數,int position表示第幾行,第幾個Item;convertView 表示解析過來的佈局,getCount表示列表項的個數。
在使用ExpandabListView組件時,我們必須使用這個Adapter:
ExpandableAdapter:(用於ExpandableListView):
public class ExpandableListViewTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//創建一個BaseExpandableListAdapter對象
ExpandableListAdapter adapter = new BaseExpandableListAdapter()
{
int[] logos = new int[]
{
R.drawable.p,
R.drawable.z,
R.drawable.t
};
private String[] armTypes = new String[]
{ "神族兵種", "蟲族兵種", "人族兵種"};
private String[][] arms = new String[][]
{
{ "狂戰士", "龍騎士", "黑暗聖堂", "電兵" },
{ "小狗", "刺蛇", "飛龍", "自爆飛機" },
{ "機槍兵", "護士MM" , "幽靈" }
};
//獲取指定組位置、指定子列表項處的子列表項數據
@Override
public Object getChild(int groupPosition, int childPosition)
{
return arms[groupPosition][childPosition];
}
@Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
@Override
public int getChildrenCount(int groupPosition)
{
return arms[groupPosition].length;
}
private TextView getTextView()
{
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 64);
TextView textView = new TextView(ExpandableListViewTest.this);
textView.setLayoutParams(lp);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
textView.setPadding(36, 0, 0, 0);
textView.setTextSize(20);
return textView;
}
//該方法決定每個子選項的外觀
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
TextView textView = getTextView();
textView.setText(getChild(groupPosition, childPosition).toString());
return textView;
}
//獲取指定組位置處的組數據
@Override
public Object getGroup(int groupPosition)
{
return armTypes[groupPosition];
}
@Override
public int getGroupCount()
{
return armTypes.length;
}
@Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
//該方法決定每個組選項的外觀
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
LinearLayout ll = new LinearLayout(ExpandableListViewTest.this);
ll.setOrientation(0);
ImageView logo = new ImageView(ExpandableListViewTest.this);
logo.setImageResource(logos[groupPosition]);
ll.addView(logo);
TextView textView = getTextView();
textView.setText(getGroup(groupPosition).toString());
ll.addView(textView);
return ll;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
@Override
public boolean hasStableIds()
{
return true;
}
};
ExpandableListView expandListView = (ExpandableListView)
findViewById(R.id.list);
expandListView.setAdapter(adapter);
}
}
在使用下拉列表的Spinner時候,還有時用到SpinnerAdapter:
下面一個示例是關於SpinnerAdapter:
private class SpinAdapter implements SpinnerAdapter{
@Override
public int getCount() {
return headIconIds.length;
}
@Override
public Object getItem(int pos) {
return null;
}
@Override
public long getItemId(int pos) {
return 0;
}
@Override
public int getItemViewType(int pos) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.head_image_spinner_layout, null);
ImageView hicon = (ImageView)convertView.findViewById(R.id.headericon);
hicon.setImageResource(headIconIds[position]);
TextView hnote = (TextView)convertView.findViewById(R.id.headernote);
hnote.setText(context.getString(R.string.header)+position);
hnote.setTextColor(Color.BLACK);
return convertView;
}
@Override
public int getViewTypeCount() {
return 0;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public void registerDataSetObserver(DataSetObserver arg0) {
}
@Override
public void unregisterDataSetObserver(DataSetObserver arg0) {
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getView(position, convertView, parent);
}
}
還有一些Adapter,例如:
SimpleCursorAdapter(用於來自數據庫的數據)關鍵代碼如下:
Cursor cur = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(cur);
//來自系統通訊錄數據庫的Cursor數據
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cur, new String[] {People.NAME}, new int[] {android.R.id.text1});
setListAdapter(adapter);