Android下拉框带图片
程序员文章站
2022-03-08 11:37:45
...
MainActivity 类
package com.example.android_06;
/**
* 上课代码
*/
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
// 简单控件
// 搜索下拉框图片加描述
private List<Map<String ,Object>> data3 = new ArrayList<>();
private SimpleAdapter adapter3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* 搜索下拉框图片加描述
*/
// 初始化
loadData3();
adapter3 = new SimpleAdapter(this,data3,R.layout.spinner_main_item1,new String[] {"img","desc"},new int[] {R.id.iv_main_img,R.id.tv_main_desc});
spinner_main_img.setAdapter(adapter3);
spinner_main_img.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Map<String ,Object> itemAtPosition = (Map<String, Object>) parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, itemAtPosition.toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
/**
* 搜索下拉框图片加描述
*/
private void loadData3() {
List<Book> list = new BookDAO().list();
Map<String,Object> map;
for (Book book : list) {
map = new HashMap<>();
map.put("img",book.getImage());
map.put("desc",book.getName());
data3.add(map);
}
}
}
book类
package com.example.android_06;
public class Book {
private Integer id;
private String name;
private Integer image;
public Book() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getImage() {
return image;
}
public void setImage(Integer image) {
this.image = image;
}
}
bookdao类
package com.example.android_06;
import java.util.ArrayList;
import java.util.List;
public class BookDAO {
public List<Book> list() {
List<Book> bookList = new ArrayList<Book>();
String[] names = {"愤怒的小鸟", "汤姆猫", "落汤鸡", "牛牛", "哈巴狗", "神龙", "烤鸭",
"小象", "美人鱼", "九尾狐"};
int[] images = {R.drawable.bird, R.drawable.cat, R.drawable.chicken,
R.drawable.cow, R.drawable.dog, R.drawable.dragon,
R.drawable.duck, R.drawable.elephant, R.drawable.fish,
R.drawable.fox};
Book b = null;
for (int i = 0; i < names.length; i++) {
b = new Book();
b.setId(i + 1);
b.setName(names[i]);
b.setImage(images[i]);
bookList.add(b);
}
return bookList;
}
}