spinner_item1.xml
<?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
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. 定义变量
private Spinner mSpinnerZT; private ArrayList<String> listZT; private AdapterSpinner1 adpapter_ZT;
2. 变量的初始化
mSpinnerZT = (Spinner) findViewById(R.id.spinner_zt); listZT = new ArrayList<String>(); adpapter_ZT = new AdapterSpinner1(this, listZT); mSpinnerZT.setAdapter(adpapter_ZT);
3. 内容的动态改变
listZT.clear(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonData = jsonArray.getJSONObject(i); listZT.add(jsonData.getString("NAME")); } adpapter_ZT.notifyDataSetChanged();
4. 取当前的选项
final String sZT = listZT.get(mSpinnerZT.getSelectedItemPosition());