當前位置:編程學習大全網 - 源碼下載 - android 裏怎麽用adapter寫下拉菜單選擇

android 裏怎麽用adapter寫下拉菜單選擇

所使用的工具:電腦

開發工具:eclipse for ?Android , Android ?Studio

用adapter 寫下拉菜單需要我們自己進行自定義,具體步驟如下:

1、自定義類,類成員與需要顯示的字段壹致;

public?class?Manufacture?{

private?String?name?;

public?Manufacture(String?name)?{

super();

this.name?=?name;

}

public?String?getName()?{

return?name;

}

public?void?setName(String?name)?{

this.name?=?name;

}

}

2、自定義adapter並繼承自BaseAdapter實現相應方法,下面是貼出的代碼示例:

public?class?MnufactureAdapter?extends?BaseAdapter{

private?List<Manufacture>?mList;

private?Context?context?;

//創建有參構造,參數需要傳入兩個1.自定義類類型的List,上下文參數

public?MnufactureAdapter(List<Manufacture>?mList,?Context?context)?{

super();

this.mList?=?mList;

this.context?=?context;

}

//返回長度位所定義List的長度

@Override

public?int?getCount()?{

return?mList.size();

}

//返回位置為自定義list當前位置

@Override

public?Object?getItem(int?position)?{

return?mList.get(position)

}

//返回條目的ID

@Override

public?long?getItemId(int?position)?{

return?position;

}

//這裏getView需方法需要重點說明和註意:

@Override

public?View?getView(int?position,?View?convertView,?ViewGroup?parent)?{

//創建壹個LayoutInflater並傳入上下文

LayoutInflater?linflater?=?LayoutInflater.from(context);

//添加自定義item布局到convertView;(item內容和樣式通過自定義方式實現)

convertView?=?linflater.inflate(R.layout.spinner_item_layout,?null);

//初始化Item中控件

TextView?textView?=(TextView)?convertView.findViewById(R.id.manufacture_list);

//設置控件顯示內容

textView.setText(mList.get(position).getName());

return?convertView;

}

}

3、在activity中需要添加如下代碼:

//初始化布局文件中的spinner

Spinner?mSpinner?=?(Spinner)?findViewById(R.id.spinner1);

//初始化自定義的List,並往裏面添加數據

List<Manufacture>?manufacture?=?new?ArrayList<Manufacture>();

接著就是添加數據,在項目中我是添加的從網絡上下載的數據解析之後進行添加的,具體的添加方式根據具體需要進行添加,我把自己的貼在下面供大家參考:

for(int?i?=?0;i<list.size();i++){

//添加數據源

manufacture.add(new?Manufacture(list.get(i).getName()));

}

//實例化壹個之前自定義的adapter並向裏面添加數據

MnufactureAdapter?madapter?=?new?MnufactureAdapter(manufacture,?ProductManageActivity.this);

參數說明:第壹個參數是添加數據源後的List,第二個是當前activity的上下文。

最後壹步,向spinner裏面添加數據源

mSpinner.setAdapter(madapter);

  • 上一篇:後臺軟件怎麽織夢,怎麽織夢,怎麽做軟件。
  • 下一篇:周公解夢夢見麻將七萬
  • copyright 2024編程學習大全網