透過上一次的範例,請將ArrayAdapter改寫成BaseAdapter的模式
能在每一個SpinnerItem中,除了文字內容外,也加入圖片。
MainActivity- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- final String[] food = {"雞腿飯", "魯肉飯", "排骨飯", "水餃", "陽春麵"};
- dataModel model = new dataModel();
- model.item = "雞腿飯";
- model.img = null;
- ArrayList<dataModel> list = new ArrayList<dataModel>();
- list.add(model);
- Spinner spinner = (Spinner) findViewById(R.id.spinner);
- SpinnerAdapter adapter = new SpinnerAdapter(list,MainActivity.this);
- spinner.setAdapter(adapter);
- }
複製代碼 SpinnerAdapter- public class SpinnerAdapter extends BaseAdapter {
- Context context;
- ArrayList<dataModel> data;
- public SpinnerAdapter(ArrayList<dataModel> data,Context context) {
- this.context = context;
- this.data = data;
- }
- @Override
- public int getCount() {
- return 2;
- }
- @Override
- public Object getItem(int position) {
- return data.get(position);
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- Log.d("leolog", String.valueOf(position));
- // 綁定你的Adapter要使用哪一個layout
- convertView = LayoutInflater.from(this.context).inflate(R.layout.spinner_layout, null);
- TextView textView = (TextView) convertView.findViewById(R.id.spinner_text);
- textView.setText(((dataModel) getItem(position)).item);
- ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
- imageView.setImageBitmap(((dataModel) getItem(position)).img);
- return convertView;
- }
- }
複製代碼 SpinnerLayout- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="match_parent"
- android:layout_height="match_parent">
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/imageView"
- android:layout_gravity="center_horizontal"
- android:src="@drawable/abc_ic_star_black_36dp"
- android:layout_alignParentTop="true"
- android:layout_alignParentEnd="true" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textAppearance="?android:attr/textAppearanceLarge"
- android:text="Large Text"
- android:id="@+id/spinner_text"
- android:layout_alignParentTop="true"
- android:layout_alignParentStart="true" />
- </RelativeLayout>
複製代碼 |