Adapter(适配器):
ArrayAdapter(只能文字) / BaseAdapter() / SingleAdapter(图文混排)
与 Adapter(适配器)搭配使用(控件id.setAdapter(适配器对象))的 控件有: Spinner /
AutoCompleteTextView/ ListView(最常用) / GridLayout(网格布局)
Spinner : 下拉列表框 , 弹出框
属性:
entries:
(这个 属性的值 为resàValuesàString.xml中 配置的文件, eg: String-array)
spinnerMode:
“dropdown”(默认是下拉框式) / “dialog” (对话框式(置顶优先级最高的)的 列表框)
prompt: (设置标题,但只配合dialog使用)
android:popupBackground="#000"
事件:
SetOnItemSelectedListener()
方法:
getSelectedItem/ getSelectedId / getSelectedPosition
entries: 用法
// strings.xml文件中 自定义列表项
<string name="app_name">My Application</string>
<string-array name="movies">
<item>毒液</item>
<item>终局之战</item>
<item>阿丽塔</item>
<item>玻璃先生</item>
</string-array>
// 布局文件中<Spinner
android:layout_width="wrap_content"
android:layout_height="40dp"
android:entries="@array/movies"
>
(但是如果 使用该属性: 则列表项item也就在String.xml配置文件中写死了,所以灵活性不高! 一般不建议使用!)
BaseAdapter 适配器 用法:
/**
-
BaseAdapter:
-
步骤:1.自定义类继承自BaseAdapter
-
2.重写四个方法
-
3.写行布局(每一行有哪些控件,新建一个布局文件中就写哪些控件)
-
4.编写数据源 (ArrayList类型的数据源,写数据类Bean再封装一个ArrayList<Bean></Bean>)
-
5.传参(把数据源传给适配器)== 其实就是个带参构造
-
6.四个方法的内容 (getCount(),getItem(),getItemId(),getView())
*/ // 3 写行布局文件<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv01"
android:layout_width="150dp"
android:layout_height="150dp" />
<TextView
android:id="@+id/tv01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="测试"
android:textSize="30sp"
android:paddingTop="40dp"
android:paddingLeft="20dp"/>
// 1, 2, 4, 6 自定义类继承BaseAdapter,
public class MyBase extends BaseAdapter {
ArrayList<Bean> beans; //数据源
Context c; //上下文对象
public MyBase(ArrayList<Bean> beans,Context c){
this.beans = beans;
this.c = c;
}
@Override
public int getCount() {
return beans.size();
}
@Override
public Object getItem(int position) {
return beans.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){ //说明这一行没有被填充,还没有数据
//布局文件转为view对象
convertView = LayoutInflater.from(c).inflate(R.layout.item_layout , null); //R.layout.item_layout这个文件转换为View类型的对象
//从view对象中获得控件 (通过ID)
ImageView imageView = convertView.findViewById(R.id.iv01);
TextView textView = convertView.findViewById(R.id.tv01);
//赋值 (数据源为 传参传过来的 数据集合/数组 )
imageView.setImageResource(beans.get(position).imageId);
textView.setText(beans.get(position).str);
}
return convertView;
}
}
// 在Activity.java中 写// 4 编写数据源
Bean bean1 = new Bean(R.mipmap.bq1,"红烧狮子头");
Bean bean2 = new Bean(R.mipmap.bq2,"红烧肉");
Bean bean3 = new Bean(R.mipmap.bq3,"红烧排骨");
ArrayList<Bean> beans = new ArrayList<>();
beans.add(bean1);
beans.add(bean2);
beans.add(bean3);
/**
- 5.传参, 创建适配器对象
*/
MyBase shipeiqi = new MyBase(beans,Main6Activity.this);
//控件绑定适配器
spinner.setAdapter(shipeiqi);