在使用 gridview嵌套RecyclerView,并且RecyclerView中条目实现多选效果,确定后获取相应获取对应数据进行保存,并且可以记录选中的状态,运用场景:常见的商城中商品的颜色 规格 以及配置等,接下来我们看下效果:
图一: 实现多选
图二: 点击确定获取选中数据
图三: 再次点击记录选中数据
定义OnItemClickLitener类
import android.view.View;
/**
* 创建人:lwd
* 时 间:2018/7/9 10:15
*/
public interface OnItemClickLitener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
这里我们需要用到一个工具类 Utils:
1.首先getJson是获取本地assets中Json文件
2.isContainsNum方法是判断字符串是否包含数据(由于数字与汉字所在字节不同,后面会用到)
import android.content.Context;
import android.content.res.AssetManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 创建人:lwd
* 时 间:2018/7/9 09:50
*/
public class Utils {
public static String getJson(String fileName,Context context) {
//将json数据变成字符串
StringBuilder stringBuilder = new StringBuilder();
try {
//获取assets资源管理器
AssetManager assetManager = context.getAssets();
//通过管理器打开文件并读取
BufferedReader bf = new BufferedReader(new InputStreamReader(
assetManager.open(fileName)));
String line;
while ((line = bf.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
/** 判断字符串中是否包含数字 **/
public static boolean isContainsNum(String input) {
int len = input.length();
for (int i = 0; i < len; i++) {
if (Character.isDigit(input.charAt(i))) {
return true;
}
}
return false;
}
}
现在我们看下适配器adapter中代码:
1.这里我们用ConcurrentHashMap来存储选中数据关于ConcurrentHashMap介绍:点击打开链接
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.dayo.map.selectionmulti.R;
import com.dayo.map.selectionmulti.help.OnItemClickLitener;
import com.dayo.map.selectionmulti.help.Utils;
import com.dayo.map.selectionmulti.vo.SpecificationParamClassList;
import com.dayo.map.selectionmulti.vo.SpecificationParamMultipleList;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* 创建人:lwd
* 时 间:2018/2/27 17:01
*/
public class SpecificationTitleRvAdapter extends RecyclerView.Adapter {
private Context context;
private ArrayList paramClassList = new ArrayList<>();
private OnItemClickLitener mOnItemClickLitener;
public ConcurrentHashMap selectData = new ConcurrentHashMap();
private String[] mVals;
//
public SpecificationTitleRvAdapter(Context context) {
this.context = context;
}
public void addrest(ArrayList paramClassList, ConcurrentHashMap selectData) {
this.paramClassList.clear();
this.paramClassList.addAll(paramClassList);
this.selectData.clear();
this.selectData.putAll(selectData);
}
public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
this.mOnItemClickLitener = mOnItemClickLitener;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_specification_title, null); //解决条目显示不全
return new SingleViewHolder(view);
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof SingleViewHolder) {
final SingleViewHolder viewHolder = (SingleViewHolder) holder;
final ArrayList paramMultipleList = paramClassList.get(position).getParamClassList();
viewHolder.tvSpecificationTitle.setText(paramClassList.get(position).getFparamclassname());
if (paramMultipleList != null && paramMultipleList.size() > 0) {
mVals = new String[paramMultipleList.size()];
for (int i = 0; i < paramMultipleList.size(); i++) {
mVals[i] = paramMultipleList.get(i).getFparammultiplename();
}
}
final TagAdapter tagAdapter = new TagAdapter(mVals) {
@Override
public View getView(FlowLayout parent, int position, String s) {
View view = LayoutInflater.from(context).inflate(R.layout.item_category_flow, viewHolder.tflSpecificationTitle, false);
TextView tv = view.findViewById(R.id.tv_fault_name);
if (s.length() == 1) {
tv.setText(" " + s + " ");
} else if (s.length() == 2) {
if (Utils.isContainsNum(s))
tv.setText(" " + s + " ");
else
tv.setText(" " + s + " ");
} else if (s.length() == 3) {
if (Utils.isContainsNum(s))
tv.setText(" " + s + " ");
else
tv.setText(" " + s + " ");
} else if (s.length() == 4) {
if (Utils.isContainsNum(s))
tv.setText(" " + s + " ");
else
tv.setText(" " + s + " ");
} else if (s.length() == 5) {
if (Utils.isContainsNum(s))
tv.setText(" " + s + " ");
else
tv.setText(s);
} else {
tv.setText(s);
}
Iterator> entries = selectData.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
Log.d("getValue", entry.getValue());
if (entry.getValue().equals(paramMultipleList.get(position).getFparammultiplename())) {
tv.setBackgroundResource(R.drawable.shape_fault_select);
tv.setTextColor(Color.WHITE);
}
}
return view;
}
};
viewHolder.tflSpecificationTitle.setAdapter(tagAdapter);
tagAdapter.notifyDataChanged();
if (mOnItemClickLitener != null) {
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnItemClickLitener.onItemClick(viewHolder.itemView, viewHolder.getAdapterPosition());
}
});
}
viewHolder.tflSpecificationTitle.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
@Override
public boolean onTagClick(View view, int selectPosition, FlowLayout parent) {
String selectName = paramMultipleList.get(selectPosition).getFparammultiplename();
//第一种遍历方法
Set set = selectData.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
int key = it.next();
if (selectData.get(key).equals(selectName)) {
selectData.remove(key);
//ToastUtils.showToast(context, "取消" + selectName);
tagAdapter.notifyDataChanged();
return true;
}
}
selectData.put(position, selectName);
//ToastUtils.showToast(context, "你选择了" + selectName);
tagAdapter.notifyDataChanged();
return true;
}
});
}
}
@Override
public int getItemCount() {
return paramClassList.size();
}
class SingleViewHolder extends RecyclerView.ViewHolder {
TextView tvSpecificationTitle;
TagFlowLayout tflSpecificationTitle;
public SingleViewHolder(View itemView) {
super(itemView);
tvSpecificationTitle = (TextView) itemView.findViewById(R.id.tv_specification_title);
tflSpecificationTitle = (TagFlowLayout) itemView.findViewById(R.id.tfl_specification_title);
}
}
}
最后我们来看下MainActivity中核心代码:
package com.dayo.map.selectionmulti;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.dayo.map.selectionmulti.adapter.SpecificationTitleRvAdapter;
import com.dayo.map.selectionmulti.help.Utils;
import com.dayo.map.selectionmulti.vo.SpecificationBean;
import com.dayo.map.selectionmulti.vo.SpecificationParamClassList;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoLayoutActivity;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MainActivity extends AutoLayoutActivity implements View.OnClickListener {
private Dialog datePickerDialog;
private ArrayList paramClassList;
private SpecificationTitleRvAdapter specificationAdapter;
public ConcurrentHashMap selectData = new ConcurrentHashMap<>();
private String specificationTitle = "";
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.bt).setOnClickListener(this);
tv = findViewById(R.id.tv);
data();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt:
popwindowSpecification();
break;
//规格取消
case R.id.tv_specification_cancel:
if (datePickerDialog != null) {
datePickerDialog.dismiss();
}
break;
//规格确定
case R.id.bt_specification_ok:
selectData.clear();
ConcurrentHashMap map = specificationAdapter.selectData;
selectData.putAll(map);
Iterator> entries = map.entrySet().iterator();
specificationTitle = "";
while (entries.hasNext()) {
Map.Entry entry = entries.next();
if (TextUtils.isEmpty(specificationTitle)) {
specificationTitle = specificationTitle + entry.getValue();
} else {
specificationTitle = specificationTitle + " , " + entry.getValue();
}
}
tv.setText(specificationTitle);
if (datePickerDialog != null) {
datePickerDialog.dismiss();
}
break;
}
}
public void data() {
String data = Utils.getJson("data.json", this);
Log.d("data", data);
//获取数据
SpecificationBean specificationBean = new Gson().fromJson(data, SpecificationBean.class);
paramClassList = specificationBean.getParamClassList();
}
/**
* 规格
*/
private void popwindowSpecification() {
datePickerDialog = new Dialog(this, R.style.time_dialog);
datePickerDialog.setCancelable(false);
datePickerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
datePickerDialog.setContentView(R.layout.item_select_specification);
RecyclerView rvSpecificationRv = datePickerDialog.findViewById(R.id.rv_specification_rv);
TextView title = datePickerDialog.findViewById(R.id.tv_electrical_title);
ImageView cover = datePickerDialog.findViewById(R.id.iv_electrical_cover);
ImageView notData = datePickerDialog.findViewById(R.id.iv_specification_not);
Button btSpecificationOk = datePickerDialog.findViewById(R.id.bt_specification_ok);
datePickerDialog.findViewById(R.id.tv_specification_cancel).setOnClickListener(this);
btSpecificationOk.setOnClickListener(this);
title.setText("多选");
//Glide.with(this).load(MCUrl.Prefix + beanFmoicon).into(cover);
if (paramClassList != null && paramClassList.size() > 0) {
LinearLayoutManager layoutManager = new LinearLayoutManager(this) {
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
};
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvSpecificationRv.setLayoutManager(layoutManager);
specificationAdapter = new SpecificationTitleRvAdapter(this);
specificationAdapter.addrest(paramClassList, selectData);
rvSpecificationRv.setAdapter(specificationAdapter);
} else {
rvSpecificationRv.setVisibility(View.GONE);
btSpecificationOk.setVisibility(View.GONE);
notData.setVisibility(View.VISIBLE);
}
Window window = datePickerDialog.getWindow();
if (window != null) {
window.setGravity(Gravity.BOTTOM);
datePickerDialog.setCanceledOnTouchOutside(true);
WindowManager manager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
if (manager != null) {
manager.getDefaultDisplay().getMetrics(dm);
}
window.setWindowAnimations(R.style.dialogstyle); // 添加动画
WindowManager.LayoutParams lp = window.getAttributes();
lp.width = dm.widthPixels;
window.setAttributes(lp);
}
datePickerDialog.show();
}
}
demo 点击打开链接