DialogFragment 侧滑退出 奇奇怪怪的写法

555 阅读2分钟

public class NetworkStateDialog extends AppCompatDialogFragment {

public void setPath(String path) {
    this.path = path;
}

private String path;
private DialogMsgBinding binding;
private FileAdapter fileAdapter;
private List<FileData> list;
private String projectName ="";//工程名
private String FZname ="";//负责人

public void setProjectName(String projectName) {
    this.projectName = projectName;
}

public void setFZname(String FZname) {
    this.FZname = FZname;
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    binding = DialogMsgBinding.inflate(inflater, container, false);
    return binding.getRoot();
}
int lastX;
int offsetX;
@SuppressLint("ClickableViewAccessibility")
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    binding.getRoot().setOnTouchListener((v, event) -> {
        int x= (int) event.getRawX();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                lastX= (int) event.getRawX();
                break;
            case MotionEvent.ACTION_MOVE :
                offsetX = x - lastX ; //记录Y轴移动的距离
                if(offsetX>0){
                    binding.getRoot().setTranslationX( offsetX); //跟随手指滑动,向下移动View
                }
                break;
            case MotionEvent.ACTION_UP :
                if(offsetX>0){
                    if(offsetX<binding.getRoot().getWidth() / 3){//移动距离 < View高度 / 3
                        binding.getRoot().setTranslationX(0);//回到初始位置
                    }else{
                        /*
                         *关闭View
                         *注:这里dismiss是DialogFragment中的一个方法,用于关闭DialogFragment
                         */
                        dismiss();
                    }
                }
                break;
        }

        return  true;
    });
    list=new ArrayList<>();
    list.add(new FileData("标准测量法",true));
    list.add(new FileData("工作曲线法",false));
    fileAdapter=new FileAdapter(list);
    binding.rv.setLayoutManager(new LinearLayoutManager(requireActivity(),RecyclerView.HORIZONTAL,false));
    binding.rv.setAdapter(fileAdapter);
    binding.queding.setOnClickListener(v -> {
        if(!TextUtils.isEmpty(binding.name.getText())){
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).isChecked()){
                    File file=new File(path,binding.name.getText().toString()+"——"+list.get(i).text+".txt");
                    try {
                        file.createNewFile();
                        String string = new Gson().toJson(new Standard(binding.name.getText().toString(),list.get(i).text,projectName,FZname,"","","--年--月--日 00:00:00","0.0 (ng/ml)"));
                        new Thread(() -> {
                            FileWriter fw = null;    //创建FileWriter类对象
                            try {
                                fw = new FileWriter(file);
                                BufferedWriter bufw=new BufferedWriter(fw);   //创建BufferedWriter对象
                                bufw.write(string);
                                bufw.close();                                 //关闭BufferedWriter流
                                fw.close();
                                if(huiDiao!=null){
                                    huiDiao.hui();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }).start();
                    } catch (IOException e) {
                        e.printStackTrace();
                        requireActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Snackbar.make(binding.getRoot(), "文件创建失败", Snackbar.LENGTH_LONG)
                                        .setAction("确定", null).show();
                            }
                        });
                    }
                }
            }


        }
    });
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Objects.requireNonNull(getDialog()).setCancelable(false);
    Objects.requireNonNull(getDialog()).setCanceledOnTouchOutside(false);
    Window window = getDialog().getWindow();
    window.setWindowAnimations(R.style.TopDialogAnimation);
    WindowManager.LayoutParams windowParams = window.getAttributes();
    window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    windowParams.dimAmount = 0.0f;//Dialog外边框透明
    window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); //高度自适应,宽度全屏
    windowParams.gravity = Gravity.TOP; //在顶部显示
    window.setAttributes(windowParams);
}

@Override
public void show(FragmentManager manager, String tag) {

    try {
        //在每个add事务前增加一个remove事务,防止连续的add
        manager.beginTransaction().remove(this).commit();
        super.show(manager, tag);
        //m.sendEmptyMessageDelayed(1,2000);
    } catch (Exception e) {
        //同一实例使用不同的tag会异常,这里捕获一下
        e.printStackTrace();
    }
}



private class FileAdapter extends RecyclerView.Adapter<FileAdapter.ViewHolder>{
    private List<FileData> list;

    public FileAdapter(List<FileData> list) {
        this.list = list;
    }

    @NonNull
    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(requireActivity()).inflate(R.layout.item_file_type, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull ViewHolder holder, int position) {

        holder.binding.text.setText(list.get(position).getText());
        if(list.get(position).isChecked()){
            holder.binding.getRoot().setBackgroundColor(getResources().getColor(R.color.juhuang));
        }else {
            holder.binding.getRoot().setBackgroundColor(getResources().getColor(R.color.lucency));
        }

        holder.binding.getRoot().setOnClickListener(v -> {
            for (FileData fileData:
            list) {
                fileData.setChecked(false);
            }
            list.get(position).setChecked(true);
            notifyDataSetChanged();
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        ItemFileTypeBinding binding;
        public ViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            binding=ItemFileTypeBinding.bind(itemView);
        }
    }
}

private class FileData{
    private String text;
    private boolean checked;

    public FileData(String text, boolean checked) {
        this.text = text;
        this.checked = checked;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }
}

public interface HuiDiao{ void hui(); }

public void setHuiDiao(HuiDiao huiDiao) {
    this.huiDiao = huiDiao;
}

private HuiDiao huiDiao;

}