ListView以列表的形式展现数据,用户可通过对屏幕的上下滑动加载数据。
在activity_main.xml中加入ListView:
修改MainActivity,用系统自带的ArrayAdapter,参数分别为Context、适配布局id和要适配的数据,这里适配布局采用内置布局android.R.layout.simple_list_item_1
public class MainActivity extends AppCompatActivity {
private String[] data = {"A", "B", "C", "D", "E", "F", "G", "H"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, data);
ListView listView = findViewById(R.id.list_view);
listView.setAdapter(adapter);
}
}
准备数据,创建名为Data的bean类
public class Data {
private String name;
private int imageId;
public Data(String name, int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
}
准备ListView的适配布局,创建list_item.xml:
创建数据适配器,重写构造器暂存数据、重写getView()方法加载布局并获取控件设置数据
public class DataAdapter extends ArrayAdapter {
private int resourceId;
public DataAdapter(@NonNull Context context, int resource, @NonNull List objects) {
super(context, resource, objects);
resourceId = resource;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Data data = getItem(position);
View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
ImageView dataIv = view.findViewById(R.id.list_iv);
TextView dataTv = view.findViewById(R.id.list_tv);
dataIv.setImageResource(data.getImageId());
dataTv.setText(data.getName());
return view;
}
}
MainActivity找到ListView并为其添加适配器
public class MainActivity extends AppCompatActivity {
private List dataList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
DataAdapter adapter = new DataAdapter(MainActivity.this, R.layout.list_item, dataList);
ListView listView = findViewById(R.id.list_view);
listView.setAdapter(adapter);
}
private void initData() {
for (int i = 0; i < 15; i++) {
Data data = new Data("data" + i, R.mipmap.ic_launcher);
dataList.add(data);
}
}
}
上面的DataAdapter每次通过findViewById查找View,可通过引入ViewHolder提升效率
public class DataAdapter extends ArrayAdapter {
private int resourceId;
public DataAdapter(@NonNull Context context, int resource, @NonNull List objects) {
super(context, resource, objects);
resourceId = resource;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Data data = getItem(position);
View view;
ViewHolder viewHolder;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
viewHolder = new ViewHolder();
viewHolder.dataIv = view.findViewById(R.id.list_iv);
viewHolder.dataTv = view.findViewById(R.id.list_tv);
view.setTag(viewHolder);
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.dataIv.setImageResource(data.getImageId());
viewHolder.dataTv.setText(data.getName());
return view;
}
private class ViewHolder {
ImageView dataIv;
TextView dataTv;
}
}
public class DataAdapter extends BaseAdapter {
private List mData;
private LayoutInflater mInflater;
public DataAdapter(Context context, List data) {
mData = data;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object 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 = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.dataIv = convertView.findViewById(R.id.list_iv);
holder.dataTv = convertView.findViewById(R.id.list_tv);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Data data = (Data) getItem(position);
holder.dataIv.setImageResource(data.getImageId());
holder.dataTv.setText(data.getName());
return convertView;
}
private class ViewHolder {
ImageView dataIv;
TextView dataTv;
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, dataList.get(position).getName(), Toast.LENGTH_SHORT).show();
}
});
点击时默认会改变背景颜色,可通过如下属性取消
android:listSelector="@android:color/transparent"
android:listSelector="#00000000"
listView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
有三种滑动类型,在滑动时还可以通过onScroll()判断当前位置、方向
private int lastVisibleItemPosition;
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case SCROLL_STATE_IDLE: //滑动停止
break;
case SCROLL_STATE_TOUCH_SCROLL://正在滑动
break;
case SCROLL_STATE_FLING: //手指抛甩,惯性滑动
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//firstVisibleItem 当前可视的第一个item
//visibleItemCount 当前可视的item总数,包括未显示完全的item
if (totalItemCount > 0 && firstVisibleItem + visibleItemCount == totalItemCount) {
//滑动到最后一行
}
if (firstVisibleItem > lastVisibleItemPosition) {
//上滑
} else if (firstVisibleItem < lastVisibleItemPosition) {
//下滑
}
lastVisibleItemPosition = firstVisibleItem;
}
});
listView.getFirstVisiblePosition(); //获取当前可视部分第一个Item ID
listView.getLastVisiblePosition(); //获取当前可视部分最后一个Item ID
可通过如下属性设置颜色和大小
android:divider="@color/colorPrimaryDark"
android:dividerHeight="5dp"
如下属性取消滚动条
android:scrollbars="none"
默认显示第一个Item,可通过如下方法设置显示,如显示第五项
listView.setSelection(5);
每当数据变化时,可通过如下方式动态更新ListView
dataList.add(new Data("data100", R.mipmap.ic_launcher));
adapter.notifyDataSetChanged();
当列表为空时,ListView不会显示任何提示,可通过如下方式设置无数据时的提示,其可以是任何View
listView.setEmptyView();
默认ListView滑到顶部或尾部只会出现一个半弧形提示,如下
并不会弹性继续滑动,可通过重写overScrollBy()设置maxOverScrollY实现弹性回滚
public class MyListView extends ListView {
private int mMaxOverDistance = 100;
public MyListView(Context context) {
this(context, null);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float density = metrics.density;
mMaxOverDistance = (int) (density * mMaxOverDistance);
}
public MyListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public MyListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, mMaxOverDistance, isTouchEvent);
}
}
效果如下图
(适配器、数据、适配布局同上),如下实现在滚动时隐藏标题栏,需要添加一个HeadView,避免第一个Item被Topbar遮挡
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private List dataList = new ArrayList<>();
private float mFirstY;
private float mCurrentY;
private boolean isScrollDown;
private boolean mShow = true;
private Animator mAnimator;
private int mTouchSlop;
private Toolbar mToolbar;
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
addAdapter();
addHeaderView();
addListener();
}
private void initView() {
mListView = findViewById(R.id.list_view);
mToolbar = findViewById(R.id.tb);
}
private void addListener() {
mListView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mFirstY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
mCurrentY = event.getY();
if (mCurrentY - mFirstY > mTouchSlop) {
isScrollDown = true; //下滑,Y不断变大
} else {
isScrollDown = false; //上滑,Y不断变小
}
toolbarAnim(isScrollDown);
mShow = !mShow;
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
}
private void addHeaderView() {
View header = new View(this);
/*TypedValue tv = new TypedValue();
int actionBarHeight = 0;
if (this.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, this.getResources().getDisplayMetrics());
}
Log.d(TAG, "onCreate: actionBarHeight = " + actionBarHeight);
header.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
actionBarHeight));*/
header.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
(int) getResources().getDimension(R.dimen.abc_action_bar_default_height_material)));//获取属性Actionbar的高度
mListView.addHeaderView(header);
}
private void addAdapter() {
DataAdapter adapter = new DataAdapter(MainActivity.this, dataList);
mListView.setAdapter(adapter);
}
private void toolbarAnim(boolean isScrollDown) {
if (mAnimator != null && mAnimator.isRunning()) {
mAnimator.cancel();
}
Log.d(TAG, "toolbarAnim: isScrollDown = " + isScrollDown);
Log.d(TAG, "toolbarAnim: mToolbar.getTranslationY() = " + mToolbar.getTranslationY());
Log.d(TAG, "toolbarAnim: -mToolbar.getHeight() = " + -mToolbar.getHeight());
if (isScrollDown) { //下滑的时候,显示标题栏,即将滑动的Y递减为0
mAnimator = ObjectAnimator.ofFloat(mToolbar,
"translationY", mToolbar.getTranslationY(), 0);
} else { //上滑,隐藏标题栏,即减去Toolbar高度
/*mAnimator = ObjectAnimator.ofFloat(mToolbar,
"translationY", mToolbar.getTranslationY(), -mToolbar.getHeight()); */
mAnimator = ObjectAnimator.ofFloat(mToolbar,
"translationY", 0, -mToolbar.getHeight());
}
mAnimator.start();
}
private void initData() {
for (int i = 0; i < 30; i++) {
Data data = new Data("data" + i, R.mipmap.ic_launcher);
dataList.add(data);
}
mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop(); //获取系统最短滑动距离,根据此判断是否滑动
}
}
布局如下
manifest中将theme设置为NoActionBar
android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"
效果如图,下滑时隐藏Topbar,上滑时显示
在上面的Data Bean类再加上type及其构造函数
private int type;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Data(String name, int imageId, int type) {
this.name = name;
this.imageId = imageId;
this.type = type;
}
创建相反布局list_item2.xml
在适配器中重写getItemViewType和getViewTypeCount,在getView根据type初始化布局
@Override
public int getItemViewType(int position) {
Data data = mData.get(position);
return data.getType();
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
if (getItemViewType(position) == 0) {
convertView = mInflater.inflate(R.layout.list_item, null);
} else {
convertView = mInflater.inflate(R.layout.list_item2, null);
}
holder.dataIv = convertView.findViewById(R.id.list_iv);
holder.dataTv = convertView.findViewById(R.id.list_tv);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Data data = (Data) getItem(position);
holder.dataIv.setImageResource(data.getImageId());
holder.dataTv.setText(data.getName());
return convertView;
}
在创建数据时,加入type
private void initData() {
boolean type = true;
for (int i = 0; i < 30; i++) {
Data data = new Data("data" + i, R.mipmap.ic_launcher, type ? 0 : 1);
dataList.add(data);
type = !type;
}
mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop(); //获取系统最短滑动距离,根据此判断是否滑动
}
效果如下
实现当Item被选中时,让其布局发生改变,如下为xml
Adapter的getView()方法根据当前Item选择布局
public class DataAdapter extends BaseAdapter {
private Context mContext;
private List mData;
public void setCurrentItem(int currentItem) {
mCurrentItem = currentItem;
}
private int mCurrentItem;
public DataAdapter(Context context, List data) {
mData = data;
mContext = context;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object 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) {
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
if (mCurrentItem == position) {
layout.addView(addFocusView());
} else {
layout.addView(addNormalView(position));
}
return layout;
}
private View addFocusView() {
ImageView iv = new ImageView(mContext);
iv.setImageResource(R.mipmap.ic_launcher);
return iv;
}
private View addNormalView(int i) {
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.HORIZONTAL);
ImageView iv = new ImageView(mContext);
iv.setImageResource(mData.get(i).getImageId());
layout.addView(iv, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
TextView tv = new TextView(mContext);
tv.setText(mData.get(i).getName());
layout.addView(tv, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
return layout;
}
}
MainActivity中为ListView设置点击事件,点击时通知Adapter重写加载
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private List dataList = new ArrayList<>();
private ListView mListView;
private DataAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
addListener();
}
private void initView() {
mListView = findViewById(R.id.list_view);
}
private void addListener() {
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
mAdapter.setCurrentItem(position);
mAdapter.notifyDataSetChanged();
}
});
}
private void initData() {
for (int i = 0; i < 30; i++) {
Data data = new Data("data" + i, R.mipmap.ic_launcher);
dataList.add(data);
}
mAdapter = new DataAdapter(this, dataList);
mListView.setAdapter(mAdapter);
}
}
效果如图