Adapter与AdapterView
AdapterView列表视图,它由adpater(适配器)为其提供数据,可以这样看,AdapterView是MVC模式中的V,而adapter是C。对于列表类的控件,比如Listview ,RecycleView, GridView,ScrollView等控件,都需要为其提供一个适配器。 adapter常用的有ArrayAdapter, SimpleAdapter, 以及自定义的adapter。
1、 ArrayAdapter
- 一般只能使用在列表项中只有文本的情况
- 其数据源一般是字符是字符串数组,或者字符串集合
- 其每一项的基本布局使用TextView
String[] datas=new String[]{"小说","电影","游戏"};
ListView listView=findViewById(R.id.listview);
ArrayAdapter adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,datas);
listView.setAdapter(adapter);
android.R.layout.simple_list_item_1是Android提供的一个简单的内置布局,其中只有一个textview。
SimpleAdapter
相较于ArrayAdapter只能使用简单的文本类布局的情况,SimpleAdapter可以适配的控件类型就要多得多,同时使用的数据源也复杂得多。
- 数据源可变,支持多控件的适配
- 数据源类型List<Map<String,object>>()
- 通过from, to 将控件与资源一一对应起来
下面看一个例子 布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/imageview"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="80dp"
app:layout_constraintTop_toTopOf="parent"
android:orientation="vertical"
android:layout_marginLeft="20dp"
app:layout_constraintStart_toEndOf="@+id/imageview">
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="40dp"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
<TextView
android:id="@+id/price"
android:layout_width="match_parent"
android:layout_height="40dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/name" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
mainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
ListView listView=findViewById(R.id.listview);
int[] images=new int[]{R.drawable.plane,R.drawable.train,R.drawable.boat,R.drawable.bus,R.drawable.gaotie};
String[] names=new String[]{"飞机","火车","轮船","客车","高铁"};
String[] prices=new String[]{"1000元","200元","800元","400元","600元"};
List<Map<String,Object>> list=new ArrayList<>();
for(int i=0;i<images.length;i++){
HashMap<String,Object> hashMap=new HashMap<>();
hashMap.put("image",images[i]);
hashMap.put("name",names[i]);
hashMap.put("price",prices[i]);
list.add(hashMap);
}
String[] from={"image","name","price"};
int[] to={R.id.imageview,R.id.name,R.id.price};
SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.simplelayout,from,to);
listView.setAdapter(adapter);
}
}
显示效果 
自定义AdapterView
|