Spinner的使用(一项内容)

spinner_item1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/txt_name"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_marginLeft="10dp"
        android:gravity="center_vertical"
        android:textSize="16sp" />
</LinearLayout>

AdapterSpinner1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class AdapterSpinner1 extends BaseAdapter {
 
    private Context mContext;
    private List<String> mList;
 
    public AdapterSpinner1(Context pContext, List<String> pList){
        this.mContext = pContext;
        this.mList = pList;
    }
    @Override
    public int getCount() {
        return mList.size();
    }
 
    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }
 
    @Override
    public long getItemId(int position) {
        return position;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(R.layout.spinner_item1, null);
        if(convertView != null)
        {
            TextView txt_name = (TextView)convertView.findViewById(R.id.txt_name);
            txt_name.setText(mList.get(position));
        }
        return convertView;
    }
}

Activity中:

1. 定义变量

1
2
3
private Spinner mSpinnerZT;
private ArrayList<String> listZT;
private AdapterSpinner1 adpapter_ZT;

2. 变量的初始化

1
2
3
4
5
mSpinnerZT = (Spinner) findViewById(R.id.spinner_zt);
 
listZT = new ArrayList<String>();
adpapter_ZT = new AdapterSpinner1(this, listZT);
mSpinnerZT.setAdapter(adpapter_ZT);

3. 内容的动态改变

1
2
3
4
5
6
listZT.clear();
 for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonData = jsonArray.getJSONObject(i);
    listZT.add(jsonData.getString("NAME"));
}
adpapter_ZT.notifyDataSetChanged();

4. 取当前的选项

1
final String sZT = listZT.get(mSpinnerZT.getSelectedItemPosition());

  

  

 

 

posted @   @王新@  阅读(162)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示