要使用RecyclerView需添加依賴(lài):compile 'com.android.support:recyclerview-v7:25.3.1'
-
RecyclerView添加點(diǎn)擊選中效果
- itemView布局文件增加一個(gè)選中效果如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_selected_bg"
android:layout_width="54dp"
android:layout_height="54dp"
android:background="@color/colorAccent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/iv_pic"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/img_small_def3"
app:layout_constraintBottom_toBottomOf="@+id/iv_selected_bg"
app:layout_constraintLeft_toLeftOf="@+id/iv_selected_bg"
app:layout_constraintRight_toRightOf="@+id/iv_selected_bg"
app:layout_constraintTop_toTopOf="@+id/iv_selected_bg" />
</android.support.constraint.ConstraintLayout>
- 在Adapter中增加一個(gè)標(biāo)記存儲(chǔ)當(dāng)前選中position
private int selectPosition = -1;
- 在onBindViewHolder方法中設(shè)置itemView點(diǎn)擊事件赵辕,并傳遞當(dāng)前position到selectPosition
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
TestBean bean = (TestBean) dataList.get(position);
//如果選中的item是當(dāng)前position的item贤徒,則顯示選中效果
((PicHolder) holder).ivSelect.setVisibility(selectPosition == position ? View.VISIBLE : View.INVISIBLE);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//這里按下item將當(dāng)前position設(shè)置為selectPosition并通知更新列表
selectPosition = position;
//這里存在一個(gè)問(wèn)題,就是會(huì)刷新全部數(shù)據(jù)住闯,數(shù)據(jù)量大會(huì)犧牲效率
notifyDataSetChanged();
}
});
}
- 如果需要一進(jìn)入列表就有選中效果断箫,在Adapter中添加如下方法
/**
* 默認(rèn)選中位置
*
* @param position
*/
public void select(int position) {
this.selectPosition = position;
notifyDataSetChanged();
}
效果如圖:image.png
-
RecyclerView使用GridLayoutManager
1.很多時(shí)候各item之間寬度需要均等拂酣,在item布局中父控件寬度應(yīng)該設(shè)置為android:layout_width="match_parent"
目標(biāo)控件應(yīng)該設(shè)置為居中顯示android:layout_gravity="center"
不然會(huì)出現(xiàn)左邊item均分了,右邊還剩很大一片空白問(wèn)題