AdapterView:
容器控件,其整体效果由每一个子元素内容决定,子元素的形式由Adapter决定。
AdapterView的子视图对象:
ListView:以垂直滑动列表形式显示一组数据。
GridView:以网格形式显示一组数据。
Spinner:以下拉列表形式显示一组数据。
Gallery:以水平滑动列表形式显示一组数据。(此类已弃用,由HorizontalScrollView和ViewPager代替
Adapter:
数据和视图之间交互的中介
Android中的常用Adapter
ArrayAdapter:最简单的适配器,数据源为文本字符串数组。
SimpleAdapter:简单适配器,数据源结构比较复杂,一般为List<Map>类型对象。 SimpleCursorAdapter:游标适配器,数据源一般为数据库中的数据。
自定义适配器:更灵活的适配器,数据源不定(由用户自行指定),需要继承BaseAdapter抽象类。
代码示例:
ArrayAdapter:
只能展示一行文字的最简单的adapter
使用:
activity_array_adapter:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".arrayAadapter.ArrayAdapterActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/list_array"/>
</LinearLayout>
ArrayAdapterActivity:
package com.example.ch0203adapter.arrayAadapter;
/*
* 只能展现一行文字
* */
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.ch0203adapter.R;
import java.util.ArrayList;
import java.util.List;
public class ArrayAdapterActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_array_adapter);
//提供数据
// String[] strs = {"A","B","C","D","E"};
//创建ArrayAdapter
// ArrayAdapter<String> adapter = new ArrayAdapter<String>
// (this,android.R.layout.simple_expandable_list_item_1,strs);
// 支持泛型 数据源
List<String> data = new ArrayList<String>();
data.add("A");
data.add("B");
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_expandable_list_item_1,data);
// simple_expandable_list_item_1系统提供的listview模板
//获取ListView对象,通过调用setAdapter方法为ListView设置Adapter设置适配器
ListView list_test = (ListView) findViewById(R.id.list_array);
list_test.setAdapter(adapter);
// 绑定事件监听器
list_test.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("ArrayAdapter","点击了" + position + "条");
}
});
}
}
效果:
simpleAdapter:
1、自定义子项布局文件
simple_list_item:子项布局
<?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 -->
<ImageView
android:id="@+id/imgtou"
android:layout_width="64dp"
android:layout_height="64dp"
android:baselineAlignBottom="true"
android:paddingLeft="8dp" />
<!-- 定义一个竖直方向的LinearLayout,显示姓名和身份-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:textColor="#1D1D1C"
android:textSize="20sp" />
<TextView
android:id="@+id/says"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8px"
android:textColor="#B4B4B9"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
activity_simple_adapter:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<ListView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list_simple"/>
</RelativeLayout>
SimpleAdapterActivity:
package com.example.ch0203adapter.simpleAdapter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.example.ch0203adapter.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SimpleAdapterActivity extends AppCompatActivity {
// 数据源
private String[] names = new String[]{"A", "B", "C"};
private String[] says = new String[]{"同学", "老师", "教导主任"};
private int[] imgIds = new int[]{R.drawable.head_icon1, R.drawable.head_icon1, R.drawable.head_icon1};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_adapter);
List<Map<String, Object>> listitem = new ArrayList<Map<String, Object>>();
for (int i = 0; i < names.length; i++) {
Map<String, Object> showitem = new HashMap<String, Object>();
showitem.put("touxiang", imgIds[i]);
showitem.put("name", names[i]);
showitem.put("says", says[i]);
listitem.add(showitem);
}
//创建一个simpleAdapter
SimpleAdapter myAdapter = new SimpleAdapter(getApplicationContext(), listitem, R.layout.simple_list_item, new String[]{"touxiang", "name", "says"}, new int[]{R.id.imgtou, R.id.name, R.id.says});
ListView listView = (ListView) findViewById(R.id.list_simple);
listView.setAdapter(myAdapter);
}
}
效果:
2、使用内置子项布局文件
activity_simple_adapter:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<ListView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list_simple"/>
</RelativeLayout>
SimpleAdapterActivity:
package com.example.ch0203adapter.simpleAdapter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.example.ch0203adapter.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SimpleAdapterActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_adapter);
/*使用内置子项布局文件*/
//准备数据源
List<Map<String,String>> students = new ArrayList<>();
Map<String,String> stu1 = new HashMap<>();
stu1.put("name", "张三");
stu1.put("no","2019010200");
students.add(stu1);
Map<String,String> stu2 = new HashMap<>();
stu2.put("name", "李四");
stu2.put("no","2019010201");
students.add(stu2);
//item布局文件(内置的)
//创建Adapter对象
SimpleAdapter simpleAdapter = new SimpleAdapter(this,
students,//显示的数据源
android.R.layout.simple_list_item_2,//item的布局文件
new String[]{"name","no"},//Map中的需要显示的数据的key值
new int[]{android.R.id.text1,android.R.id.text2});//显示数据的控件的id值
//获取ListView并绑定Adapter
ListView listView = findViewById(R.id.list_simple);
listView.setAdapter(simpleAdapter);
//绑定事件监听器
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//点击ListView每一个item都会执行
//parent当前的AdapterView对象(ListView对象)
//view当前点击的item的视图对象
//position用户当前点击的位置下标,从0开始
//id值通常同position值一致
Log.e("ListView","点击的位置"+position
+" 姓名:" + students.get(position).get("name"));
//点击某一条时,修改当前item视图的背景颜色
view.setBackgroundColor(getResources().getColor(R.color.purple_200));
}
});
}
}
效果:
自定义Adapter
ListView:
以垂直可滑动列表形式显示子项目的视图容器,是一种AdapterView。
ListView使用的基本流程:
准备ListView每一个子项的视图布局。 可以使用内置的布局,也可以用户自定义布局。
创建Adapter(连接数据源和视图布局)。
为ListView绑定Adapter。
为ListView绑定事件监听器。
代码示例:
student_list_item: 自定义每一个listitem布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_photo"
android:layout_width="150dp"
android:layout_height="150dp"/>
<LinearLayout
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@id/iv_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"/>
<TextView
android:id="@+id/tv_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"/>
</LinearLayout>
<ImageView
android:id="@+id/iv_delete"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginRight="20dp"
android:layout_alignParentRight="true"
android:src="@drawable/delete"/>
</RelativeLayout>
CustomerAdapter: 自定义Adapter需要继承BaseAdapter
package com.example.ch0203adapter.customerListAdapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.ch0203adapter.R;
import java.util.ArrayList;
import java.util.List;
/*
功能:将数据源同item布局绑定
*/
public class CustomAdapter extends BaseAdapter {
private List<Student> students = new ArrayList<>();
private int layoutResId;
private Context context;//环境上下文
public CustomAdapter(Context context, List<Student> students,
int layoutResId){
this.context = context;
this.students = students;
this.layoutResId = layoutResId;
}
@Override
//获取数据源数据条数
public int getCount() {
if (null != students){
return students.size();
}
return 0;
}
@Override
//返回每一个item显示的数据对象
public Object getItem(int position) {
if (null != students){
return students.get(position);
}
return null;
}
@Override
//返回每一个item的id的值
public long getItemId(int position) {
return position;
}
@Override
//生成每个item的视图对象(最重要)
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
//加载item的布局文件
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(layoutResId, null, false);
}
//在布局文件的控件中显示数据
//获取控件对象的引用
ImageView imageView = convertView.findViewById(R.id.iv_photo);
TextView tvName = convertView.findViewById(R.id.tv_name);
TextView tvNo = convertView.findViewById(R.id.tv_no);
ImageView ivDelete = convertView.findViewById(R.id.iv_delete);
//设置控件显示的内容
tvName.setText(students.get(position).getStuName());
tvNo.setText(students.get(position).getStuNo());
//设置ImageView显示的图片
imageView.setBackgroundResource(students.get(position).getPhotoId());
//处理控件的点击事件
ivDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//删除数据源中的一条数据
students.remove(position);
//刷新界面(更新Adapter)
notifyDataSetChanged();
}
});
return convertView;
}
}
ListActivity: 实现绑定
package com.example.ch0203adapter.customerListAdapter;
/*
* 自定义ListView 学生列表
* */
/*
* 准备ListView每一个子项的视图布局。可以使用内置的布局,也可以用户自定义布局。
*创建Adapter(连接数据源和视图布局)。
*为ListView绑定Adapter。
*为ListView绑定事件监听器。
*/
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import com.example.ch0203adapter.R;
import java.util.ArrayList;
import java.util.List;
public class ListActivity extends AppCompatActivity {
private List<Student> students = new ArrayList<>();
private CustomAdapter customAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
//准备数据源
initData();
//自定义item的布局文件 student_list_item
//初始化ListView,绑定Adapter
initListView();
initButton();
}
public void initData(){
Student stu1 = new Student("张三","2019001200",R.drawable.boy);
Student stu2 = new Student("李四","2019001202",R.drawable.girl);
Student stu3 = new Student("张三","2019001200",R.drawable.boy);
Student stu4 = new Student("李四","2019001202",R.drawable.girl);
Student stu5 = new Student("李四","2019001202",R.drawable.girl);
students.add(stu1);
students.add(stu2);
students.add(stu3);
students.add(stu4);
students.add(stu5);
}
public void initListView(){
ListView listView = findViewById(R.id.lv_student);
customAdapter = new CustomAdapter(
this,
students,
R.layout.student_list_item);
// 绑定Adapter
listView.setAdapter(customAdapter);
// 绑定事件监听器
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("自定义Adapter","点击了" + position + "条");
}
});
}
// 添加按钮点击事件
public void initButton(){
Button btnAdd = findViewById(R.id.btn_add);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//在数据源中添加一条数据
Student stu1 = new Student("王五","2019001202",R.drawable.boy);
students.add(stu1);
//更新界面
customAdapter.notifyDataSetChanged();
}
});
}
}
activity_list:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<ListView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv_student"/>
<Button
android:id="@+id/btn_add"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加"/>
</RelativeLayout>
Student:学生实体类
package com.example.ch0203adapter.customerListAdapter;
public class Student {
private String stuName;
private String stuNo;
private int photoId;
public Student() {
}
public Student(String stuName, String stuNo, int photoId) {
this.stuName = stuName;
this.stuNo = stuNo;
this.photoId = photoId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public int getPhotoId() {
return photoId;
}
public void setPhotoId(int photoId) {
this.photoId = photoId;
}
}
效果:
GridView网格列表
activity_grid:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".customerGridView.GridActivity">
<GridView
android:id="@+id/lv_students"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="2" />
<!--每行两个子项-->
</RelativeLayout>
GridActivity:
package com.example.ch0203adapter.customerGridView;
/*
* 与ListView相同
* 网格列表展示学生
* */
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.ch0203adapter.R;
import com.example.ch0203adapter.customerListView.CustomAdapter;
import com.example.ch0203adapter.Student;
import java.util.ArrayList;
import java.util.List;
public class GridActivity extends AppCompatActivity {
private List<Student> students = new ArrayList<>();
private CustomAdapter customAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
//准备数据源
initData();
//自定义item的布局文件 student_list_item
//初始化ListView,绑定Adapter
initListView();
}
public void initData(){
Student stu1 = new Student("张三","2019",R.drawable.boy);
Student stu2 = new Student("李四","2012",R.drawable.girl);
Student stu3 = new Student("张三","2010",R.drawable.boy);
Student stu4 = new Student("李四","2020",R.drawable.girl);
Student stu5 = new Student("李四","2012",R.drawable.girl);
students.add(stu1);
students.add(stu2);
students.add(stu3);
students.add(stu4);
students.add(stu5);
}
public void initListView(){
ListView listView = findViewById(R.id.lv_student);
customAdapter = new CustomAdapter(
this,
students,
R.layout.student_list_item);
// 绑定Adapter
listView.setAdapter(customAdapter);
// 绑定事件监听器
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("自定义Adapter","点击了" + position + "条");
}
});
}
}
MyAdapter
package com.example.ch0203adapter.customerGridView;
import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public abstract class MyAdapter<T> extends BaseAdapter {
private ArrayList<T> mData;
private int mLayoutRes; //布局id
public MyAdapter() {
}
public MyAdapter(ArrayList<T> mData, int mLayoutRes) {
this.mData = mData;
this.mLayoutRes = mLayoutRes;
}
@Override
public int getCount() {
return mData != null ? mData.size() : 0;
}
@Override
public T getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = ViewHolder.bind(parent.getContext(), convertView, parent, mLayoutRes
, position);
bindView(holder, getItem(position));
return holder.getItemView();
}
public abstract void bindView(ViewHolder holder, T obj);
//添加一个元素
public void add(T data) {
if (mData == null) {
mData = new ArrayList<>();
}
mData.add(data);
notifyDataSetChanged();
}
//往特定位置,添加一个元素
public void add(int position, T data) {
if (mData == null) {
mData = new ArrayList<>();
}
mData.add(position, data);
notifyDataSetChanged();
}
public void remove(T data) {
if (mData != null) {
mData.remove(data);
}
notifyDataSetChanged();
}
public void remove(int position) {
if (mData != null) {
mData.remove(position);
}
notifyDataSetChanged();
}
public void clear() {
if (mData != null) {
mData.clear();
}
notifyDataSetChanged();
}
public static class ViewHolder {
private SparseArray<View> mViews; //存储ListView 的 item中的View
private View item; //存放convertView
private int position; //游标
private Context context; //Context上下文
//构造方法,完成相关初始化
private ViewHolder(Context context, ViewGroup parent, int layoutRes) {
mViews = new SparseArray<>();
this.context = context;
View convertView = LayoutInflater.from(context).inflate(layoutRes, parent, false);
convertView.setTag(this);
item = convertView;
}
//绑定ViewHolder与item
public static ViewHolder bind(Context context, View convertView, ViewGroup parent,
int layoutRes, int position) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder(context, parent, layoutRes);
} else {
holder = (ViewHolder) convertView.getTag();
holder.item = convertView;
}
holder.position = position;
return holder;
}
@SuppressWarnings("unchecked")
public <T extends View> T getView(int id) {
T t = (T) mViews.get(id);
if (t == null) {
t = (T) item.findViewById(id);
mViews.put(id, t);
}
return t;
}
/**
* 获取当前条目
*/
public View getItemView() {
return item;
}
/**
* 获取条目位置
*/
public int getItemPosition() {
return position;
}
/**
* 设置文字
*/
public ViewHolder setText(int id, CharSequence text) {
View view = getView(id);
if (view instanceof TextView) {
((TextView) view).setText(text);
}
return this;
}
/**
* 设置图片
*/
public ViewHolder setImageResource(int id, int drawableRes) {
View view = getView(id);
if (view instanceof ImageView) {
((ImageView) view).setImageResource(drawableRes);
} else {
view.setBackgroundResource(drawableRes);
}
return this;
}
/**
* 设置点击监听
*/
public ViewHolder setOnClickListener(int id, View.OnClickListener listener) {
getView(id).setOnClickListener(listener);
return this;
}
/**
* 设置可见
*/
public ViewHolder setVisibility(int id, int visible) {
getView(id).setVisibility(visible);
return this;
}
/**
* 设置标签
*/
public ViewHolder setTag(int id, Object obj) {
getView(id).setTag(obj);
return this;
}
//其他方法可自行扩展
}
}
Student类同ListView文章来源:https://www.toymoban.com/news/detail-401539.html
效果:
文章来源地址https://www.toymoban.com/news/detail-401539.html
到了这里,关于Android学习——Adapter适配器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!