几种常用的适配器--Adapter
16lz
2021-12-04
(1)数组适配器(ArrayAdapter)
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(context, textViewResourceId, objects)
context:上下文对象,一般填this即可
textViewResourceId:每个Item的布局样式,可以直接使用android提供的(例如:android.R.layout.simple_list_item_1
),如果android提供的不满足你的需求,你也可以自己写一个Layout
objects:数据源, 一般为一个数组或集合
实例:MainActivity.java
public class MainActivity extends Activity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, new String[] { "Item1", "Item2", "Item3", "Item4", "Item5" }); listView.setAdapter(adapter); }}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" > ListView>RelativeLayout>
(2)简单适配器(SimpleAdapter)
它虽然叫简单适配器,其实它还是比较复杂的
SimpleAdapter adapter = new SimpleAdapter(context, data, resource, from, to);
context:上下文对象,一般填this即可
data: 数据源,一般为List包装的Map
resource:每个Item的布局样式
from: 一个String的数组,里面包含Map中的键名
to:绑定数据视图的中的ID,与from成对应的关系
实例:MainActivity.java
public class MainActivity extends Activity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.item_layout, new String[] { "img", "text" }, new int[] { R.id.iv, R.id.tv }); listView.setAdapter(adapter); } //数据源 private List
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" > ListView>RelativeLayout>
item_layout.xml
<?xml version="1.0" encoding="utf-8"?><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/iv" android:layout_width="60dp" android:layout_height="60dp"/> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="60dp" android:gravity="center_vertical" android:textSize="40sp"/>LinearLayout>
注意:from 和 to 一定要是一一对应的
(3)基本适配器(BaseAdapter)
* 以后再更新*
更多相关文章
- 箭头函数的基础使用
- Android(安卓)浅谈MatrixCursor
- Android(安卓)Adapter
- android 图片文字轮播效果(图片和文字自动滚动)
- Android(安卓)浅谈MatrixCursor
- Android教程:LayerDrawable层叠样式layer-list
- Android(安卓)系统跳转实现分享功能(如 微信 朋友圈 QQ QQ空间 微
- Android(安卓)官方示例:android-architecture 学习笔记(二)之todo
- Android中Parcelable序列化总结