<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.lantianbaiyunyk.asus.spnner.MainActivity"> <Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="50dp"> </Spinner>
</LinearLayout>
MainActivity
public class MainActivity extends AppCompatActivity { private Spinner spinner; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
ilit();
} private void ilit() {
final List<String> datas = new ArrayList<>();
for (int i = 0; i <10 ; i++) {
datas.add("数据"+i);
}
MyAdapter adapter = new MyAdapter(this);
spinner.setAdapter(adapter);
adapter.setDatas(datas);
/**选项选择监听*/
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "点击了" + datas.get(position), Toast.LENGTH_SHORT).show();
} @Override
public void onNothingSelected(AdapterView<?> parent) { }
}); } private void initView() {
spinner = (Spinner) findViewById(R.id.spinner);
}
}
Adapter:
public class MyAdapter extends BaseAdapter{
List<String> datas = new ArrayList<>();
Context mContext;
public MyAdapter(Context context) {
this.mContext = context;
} public void setDatas(List<String> datas) {
this.datas = datas;
notifyDataSetChanged();
} @Override
public int getCount() {
return datas==null?0:datas.size();
} @Override
public Object getItem(int position) {
return datas==null?null:datas.get(position);
} @Override
public long getItemId(int position) {
return position;
} @Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHodler hodler = null;
if (convertView == null) {
hodler = new ViewHodler();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item, null);
hodler.mTextView = (TextView) convertView;
convertView.setTag(hodler);
} else {
hodler = (ViewHodler) convertView.getTag();
} hodler.mTextView.setText(datas.get(position)); return convertView;
} private static class ViewHodler{
TextView mTextView;
}
}
item:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"> </TextView>