赞
踩
说明:此处是自定义的对话框,该对话框包含有以下几部分功能:
1、支持单一选项的选择 (例如:聊斋、三国演义、红楼梦) 这些选项是单一选项
2、支持多选项互斥选择(例如:宋江武松林冲 为一组互斥选择,唐僧悟空八戒互斥选择)
3、支持初次默认选择(例如:左图中初次打开的时候,默认选择三国演义和八戒)
4、支持数据本地缓存和回显
5、支持对话框DIY设置基础标题样式和对话框显示宽高样式等
import android.content.Context; import android.graphics.Canvas; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.Spannable; import android.text.SpannableString; import android.text.style.StyleSpan; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; import androidx.fragment.app.DialogFragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.gson.Gson; import java.util.List; /** * 用法说明: * * <head> 主要是完成对话框, 出现单选和多选的一些设置选项 </head> * <ol> * <li> 数据准备 </li> * <p> * 主要是构建出 List<CommonOptionView.ItemBean> 的对象, 其中 ItemBean 对象的参数信息 <br> * 参数1 name 列表项需要显示的内容 <br> * 参数2 check 选项是否被选中, true 表示选中, false 表示未选中 <br> * 参数3 single 是否是单一的选项, 如果是 true 则下面的 groupId 不生效 <br> * 参数4 groupId 是否是选项组类型, 当single设置为false则生效, 选项组相同为同一组中进行多选一 <br> * </p> * <li> 界面显示 </li> * <p> * 主要是需要设置一些参数信息, 针对于界面的选项进行自定义操作, 主要包含以下内容: <br> * 步骤1 获取到对象 CommonOptionView optionView = CommonOptionView.getInstance(); <br> * 步骤2 设置数据源 optionView.setData(list); <br> * 步骤3 设置标题 optionView.setTitle("helloWorld", 25, 20, 20); <br> * 步骤4 设置全局参数 optionView.setOverall(1.0F, 0.75F, 0, 0, 0); <br> * 步骤5 显示对话框 optionView.show(getParentFragmentManager(), LoginFragment.TAG); <br> * </p> * <li> 逻辑处理 </li> * <p> * 主要是针对于事件进行处理 optionView.setOnItemClickListener((position, data, json) -> { ... } <br> * 参数1 position 表示当前点击的是哪一项 <br> * 参数2 data 表示之前传入的集合数据 <br> * 参数3 json 表示集合转换成为JSON类型的数据 <br> * <p/> * </ol> */ public class CommonOptionView extends DialogFragment { private TextView titleTextView; private String titleMessage; private int titleTop; private int titleBottom; private int titleSize; private List<ItemBean> list; private RecyclerView recyclerView; private LinearLayout rootView; private float scaleWidth; private float scaleHeight; private int spaceStart; private int spaceEnd; private int itemHeight; private static final float MAX_SCALE = 1.0F; private static final float MIN_SCALE = 0.0F; // 设置头部间距和尾部间距 private static final int WAY_SPACE_HEAD = 30; private static final int WAY_SPACE_TAIL = 30; private static final int DEFAULT_TEXT_SIZE = 14; // 设置列表项的间距高度 private static final int ITEM_HEIGHT = 120; private OnDismissListener onDismissListener; private OnItemClickListener onItemClickListener; private CommonOptionView() { } private static class CommonOptionViewInstance { private static final CommonOptionView INSTANCE = new CommonOptionView(); } public static CommonOptionView getInstance() { return CommonOptionViewInstance.INSTANCE; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } // 设置标题属性 public void setTitle(String titleMessage, int titleSize, int titleTop, int titleBottom) { this.titleMessage = titleMessage; this.titleTop = titleTop; this.titleBottom = titleBottom; if (titleSize < 0) { titleSize = DEFAULT_TEXT_SIZE; } this.titleSize = titleSize; } // 设置全局属性 public void setOverall(float scaleWidth, float scaleHeight, int spaceStart, int spaceEnd, int itemHeight) { if (scaleWidth > MAX_SCALE) { scaleWidth = MAX_SCALE; } if (scaleWidth < MIN_SCALE) { scaleWidth = MIN_SCALE; } if (scaleHeight > MAX_SCALE) { scaleHeight = MAX_SCALE; } if (scaleHeight < MIN_SCALE) { scaleHeight = MIN_SCALE; } if (spaceStart <= 0) { spaceStart = WAY_SPACE_HEAD; } if (spaceEnd <= 0) { spaceEnd = WAY_SPACE_TAIL; } if (itemHeight <= 0) { itemHeight = ITEM_HEIGHT; } this.scaleWidth = scaleWidth; this.scaleHeight = scaleHeight; this.spaceStart = spaceStart; this.spaceEnd = spaceEnd; this.itemHeight = itemHeight; } public void setData(List<ItemBean> list) { this.list = list; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (getContext() != null) { this.rootView = new LinearLayout(getContext()); this.rootView.setOrientation(LinearLayout.VERTICAL); this.titleTextView = new TextView(getContext()); this.titleTextView.setGravity(Gravity.CENTER); this.titleTextView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); this.recyclerView = new RecyclerView(getContext()); this.rootView.addView(titleTextView); this.rootView.addView(recyclerView); } return rootView; } // 在 View 被创建的时候, 设置相关显示的参数信息(标题和列表样式等) @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // 标题部分的设置效果, 加粗 和 间距 SpannableString spannable = new SpannableString(titleMessage); spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, spannable.length(), Spannable.SPAN_COMPOSING); titleTextView.setText(spannable); titleTextView.setTextSize(titleSize); titleTextView.setPadding(0, titleTop, 0, titleBottom); // 底部的 RecyclerView CommonOptionAdapter adapter = new CommonOptionAdapter(list, spaceStart, spaceEnd, itemHeight); LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(adapter); recyclerView.addItemDecoration(new OptionDividerItemDecoration(getContext())); adapter.setOnItemClickListener((position, list, json) -> { if (onItemClickListener != null) { onItemClickListener.itemClick(position, list, json); } }); } // 在 onResume 当中需要去指定对话框的宽度和高度, 以及对话框的消失事件处理监听器 @Override public void onResume() { super.onResume(); if (getDialog() != null && getDialog().getWindow() != null && getActivity() != null) { int widthPixels = getActivity().getResources().getDisplayMetrics().widthPixels; int heightPixels = getActivity().getResources().getDisplayMetrics().heightPixels; Window window = getDialog().getWindow(); WindowManager.LayoutParams params = window.getAttributes(); params.gravity = Gravity.CENTER; params.width = (int) (widthPixels * scaleWidth); params.height = (int) (heightPixels * scaleHeight); window.setAttributes(params); getDialog().setOnDismissListener(dialog -> { dismiss(); if (onDismissListener != null) { onDismissListener.onDismiss(); } }); } } // 自定义的适配器的对象 private static class CommonOptionAdapter extends RecyclerView.Adapter<CommonOptionAdapter.ViewHolder> { private final List<ItemBean> list; private final int spaceStart; private final int spaceEnd; private final int itemHeight; private OnItemClickListener onItemClickListener; private static final int idTextView = 0x66612555; private static final int idCheckBox = 0x66612444; public CommonOptionAdapter(List<ItemBean> list, int spaceStart, int spaceEnd, int itemHeight) { this.list = list; this.spaceStart = spaceStart; this.spaceEnd = spaceEnd; this.itemHeight = itemHeight; } @NonNull @Override public CommonOptionAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { RelativeLayout.LayoutParams paramEnd = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT); paramEnd.addRule(RelativeLayout.ALIGN_PARENT_END); RelativeLayout.LayoutParams paramVMiddle = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); paramVMiddle.addRule(RelativeLayout.CENTER_VERTICAL); // 定义列表项 RelativeLayout itemView = new RelativeLayout(parent.getContext()); itemView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, itemHeight)); TextView textView = new TextView(parent.getContext()); CheckBox checkBox = new CheckBox(parent.getContext()); textView.setId(idTextView); checkBox.setId(idCheckBox); checkBox.setLayoutParams(paramEnd); checkBox.setPadding(0, 0, spaceEnd, 0); checkBox.setFocusable(false); checkBox.setClickable(false); textView.setLayoutParams(paramVMiddle); textView.setPadding(spaceStart, 0, 0, 0); itemView.addView(textView); itemView.addView(checkBox); return new ViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull CommonOptionAdapter.ViewHolder holder, int position) { ItemBean itemBean = list.get(position); holder.textView.setText(itemBean.name); holder.checkBox.setChecked(itemBean.check); holder.itemView.setOnClickListener(v -> { // 判断多组选择的操作 processOption(position, list); // 点击的时候, 切换状态 flushUI(); String json = new Gson().toJson(list); if (onItemClickListener != null) { onItemClickListener.itemClick(position, list, json); } }); } // 判断类型 private void processOption(int position, List<ItemBean> list) { // 判断当前的选项是否点击的是多选项 ItemBean current = list.get(position); if (current.single) { // 如果是单选按钮 current.check = !current.check; list.set(position, current); return; } // 如果是多选按钮, 获取到当前选项的 groupId 信息, 根据 groupId 修改其他选项 for (int i = 0; i < list.size(); i++) { ItemBean child = list.get(i); if (current.groupId == child.groupId) { child.check = (position == i); list.set(i, child); } } } private void flushUI() { new Handler(Looper.getMainLooper()).postDelayed(() -> notifyDataSetChanged(), 100); } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } public interface OnItemClickListener { void itemClick(int position, List<ItemBean> list, String json); } @Override public int getItemCount() { return list == null ? 0 : list.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { private final TextView textView; private final CheckBox checkBox; public ViewHolder(@NonNull View itemView) { super(itemView); textView = itemView.findViewById(idTextView); checkBox = itemView.findViewById(idCheckBox); } } } private static class OptionDividerItemDecoration extends RecyclerView.ItemDecoration { private final Drawable mDivider; public OptionDividerItemDecoration(Context context) { mDivider = ResourcesCompat.getDrawable(context.getResources(), R.drawable.line_divider, null); } @Override public void onDrawOver(@NonNull Canvas c, RecyclerView parent, @NonNull RecyclerView.State state) { int left = parent.getPaddingLeft(); int right = parent.getWidth() - parent.getPaddingRight(); int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { View child = parent.getChildAt(i); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); int top = child.getBottom() + params.bottomMargin; int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } } // 对话选项的实体类 public static class ItemBean { public String name; // 选项的名称 public boolean check; // 是否默认选中 public boolean single; // 是否的单选 true 表示单选, false 表示多选 public int groupId; // 选项组的ID 这里需要注意的是, 如果前面选择 single=true 的情况下 groupId 默认为0 public ItemBean(String name, boolean check, boolean single, int groupId) { this.name = name; this.check = check; this.single = single; this.groupId = single ? 0 : groupId; } @NonNull @Override public String toString() { return "ItemBean{" + "name='" + name + '\'' + ", check=" + check + ", single=" + single + ", groupId=" + groupId + '}'; } } // 对话框消失时候的事件监听器 public interface OnDismissListener { void onDismiss(); } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } // 对话框 item 选项点击时候的事件监听器 public interface OnItemClickListener { void itemClick(int position, List<ItemBean> list, String json); } }
//[1] 数据准备 List<CommonOptionView.ItemBean> list = new ArrayList<>(); // 缓存的JSON格式的数据 String currentData = getContext().getSharedPreferences("fileName", Context.MODE_PRIVATE).getString("MyKey", ""); if (TextUtils.isEmpty(currentData)) { // itemBean 的四个参数说明: // 参数1: 需要显示列表项的名称 // 参数2: 是否默认被选中 // 参数3: 是否是单一选项, 如果设置true 则参数4 数值不生效 // 参数4: 是否是在同一组的互斥选项, 数值相同则在同一组。如果参数3设置为false 参数4才会生效 list.add(new CommonOptionView.ItemBean("聊斋", false, true, 0)); list.add(new CommonOptionView.ItemBean("三国演义", true, true, 0)); list.add(new CommonOptionView.ItemBean("红楼梦", false, true, 0)); list.add(new CommonOptionView.ItemBean("宋江", false, false, 11)); list.add(new CommonOptionView.ItemBean("武松", false, false, 11)); list.add(new CommonOptionView.ItemBean("林冲", false, false, 11)); list.add(new CommonOptionView.ItemBean("唐僧", false, false, 22)); list.add(new CommonOptionView.ItemBean("悟空", false, false, 22)); list.add(new CommonOptionView.ItemBean("八戒", true, false, 22)); } else { list = new Gson().fromJson(currentData, new TypeToken<List<CommonOptionView.ItemBean>>() {}.getType()); } //-------------------------------------------------------------------------------- //[2] 界面显示 CommonOptionView optionView = CommonOptionView.getInstance(); // A. 需要设置数据源信息, 数据源 List<CommonOptionView.ItemBean> 对象 optionView.setData(list); // B. 设置标题信息。 // 参数1: 标题的内容 // 参数2: 文字的大小 // 参数3: 标题距离顶部的距离 // 参数4: 标题距离底部的距离 optionView.setTitle("对话框标题", 25, 20, 20); // C. 设置全局信息。 // 参数1: 对话框宽度相对设备屏幕占比 // 参数2: 对话框高度相对设备屏幕占比 // 参数3: 对话框文字开始的间距 0表示默认 // 参数4: 对话框文字结尾的间距 0表示默认 // 参数5: 列表项的行高 0表示默认 optionView.setOverall(1.0F, 0.75F, 0, 0, 0); // D. 显示对话框信息。 参数1: FragmentManager 的对象, 参数2: 标识TAG optionView.show(getParentFragmentManager(), "TAG"); //-------------------------------------------------------------------------------- //[3] 逻辑处理 // 三个参数信息分别是: position 点击的位置从0开始, data 数据源集合类型, json 转换成为JSON格式数据, 以便于数据的缓存处理 optionView.setOnItemClickListener((position, data, json) -> { // 将数据进行存储 getContext().getSharedPreferences("fileName", Context.MODE_PRIVATE).edit().putString("MyKey", json).apply(); Toast.makeText(getContext(), "选中 position: " + position, Toast.LENGTH_SHORT).show(); });
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。