Spinner的簡單使用

 

 

<?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:android

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:app

<?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>
相關文章
相關標籤/搜索