Android PopupWindow点击监听事件及DialogFragment、ProgressDialog、AlertDialog的使用

本文目录,点击跳转

  • 一、PopupWindow点击监听事件实现
    • 1.1 java代码部分
    • 1.2 xml代码部分
    • 1.3效果图如下
  • 二. 更好的替代PopupWindow的几种方法
    • 2.1、DialogFragment的使用
      • 2.1.1第一步,自定义DialogFragment
      • 2.1.2 第二步、可以自定义自己前端界面,这里的dialog_clause.xml代码如下:
      • 2.1.3 第三步、调用FragmentDialog
      • 2.1.4 效果图如下
    • 2.2. ProgressDialog的使用
      • 2.2.1第一步、初始化
      • 2.2.2 第二步、设置进度
      • 2.2.3 第三步最终效果如下
    • 2.3 AlertDialog的使用:
      • 2.3.1 调用AlertDialog
      • 2.3.2 自定义开发AlertDialog
      • 2.3.3 监听AlertDialog的显示和取消:
      • 2.3.4 通过反射修改按钮字体的颜色

一、PopupWindow点击监听事件实现

1.1 java代码部分

public void showPopupWindow( boolean showPopup) {
	final PopupWindow popupWindow = new PopupWindow();
	popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
	popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
	popupWindow.setFocusable(true);
	popupWindow.setTouchable(true);
	popupWindow.setContentView(LayoutInflater.from(this).inflate(R.layout.popup_select_sex,null));
        //第一步  获取到你添加的PopubWindow的父View
        View view = popupWindow.getContentView();
        //第二步 通过父View找到你要处理点击的子View
        FrameLayout frameLayout = view.findViewById(R.id.fl100);
        //第三步 给你想要点击的子View 设置监听事件
        frameLayout1.setOnClickListener(v -> {
            tvSex1.setText("男");
            popupWindow.dismiss();
        });
        FrameLayout frameLayout2 = view.findViewById(R.id.fl101);
        frameLayout2.setOnClickListener(v -> {
                    tvSex1.setText("女");
                    popupWindow1.dismiss();
                }
        );
        if (showPopup) {
        popupWindow.showAtLocation(getWindow()
                        .getDecorView(),Gravity.CENTER, 0, 0);
        else popupWindow.dismiss();
  }

1.2 xml代码部分

网上说的自定义PopubWindow方法过于麻烦,且只适合处理简单的点击监听事件
这里提供的方法可以快速实现按钮较多时的(或者子视图)点击事件处理
popup_select_sex.xml如下:




    
        
        
    
    
    
        
        
    




1.3效果图如下

Android PopupWindow点击监听事件及DialogFragment、ProgressDialog、AlertDialog的使用_第1张图片

二. 更好的替代PopupWindow的几种方法

2.1. DialogFragment
2.2. ProgressDialog
2.3. AlertDialog

2.1、DialogFragment的使用

2.1.1第一步,自定义DialogFragment

public class DisclaimerDialog extends DialogFragment {

    private final static String THIS_FILE = "DeviceScanDialog";
    private boolean changeDevice = false;
    private boolean isMainActivity = false;
    private TextView tv;
    private Timer scanHelpTimer = new Timer();
    private Button buttonAccept,buttonReject;
    private Context context;

    public void setContext(Context context) {
        this.context = context;
    }

    public static DisclaimerDialog newInstance() {
        return new DisclaimerDialog();
    }

    public  void setIsMainActivity(boolean isMainActivity) {
        this.isMainActivity = isMainActivity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.dialog_clause, container, false);
        //背景透明
        Objects.requireNonNull(Objects.requireNonNull(
                getDialog()).getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        ButterKnife.bind(this, v);
        setCancelable(false);
        changeDevice = false;
        tv = v.findViewById(R.id.tv);
        style.append("欢迎使用XXX," +
                "我们非常重视您的个人信息和隐私说明,在您使用XXX前," +
                "请仔细阅读《服务条款》和《隐私说明》," +
                "我们将严格按照经您同意的各项条款使用您的个人信息,以使为您提供更好的服务");

        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.BLUE);
        style.setSpan(clickableSpan, 40, 46, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(foregroundColorSpan, 40, 46, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(clickableSpan2, 47, 53, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(foregroundColorSpan, 47, 53, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setText(style);
        buttonAccept = v.findViewById(R.id.exit_btn);
        buttonAccept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesUtils.saveClauseState(context,1);
                getDialog().dismiss();
            }
        });
        buttonReject = v.findViewById(R.id.exit_btn_1);
        buttonReject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((StartActivity)getActivity()).finish();
            }
        });
        return v;
    }

    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            startActivity(new Intent(getContext(), ClausePrivacyActivity.class));
        }
    };
    ClickableSpan clickableSpan2 = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            startActivity(new Intent(getContext(), ClauseServerActivity.class));
        }
    };

    final SpannableStringBuilder style = new SpannableStringBuilder();



    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        Dialog dialog = super.onCreateDialog(savedInstanceState);
        // request a window without the title
        dialog.setCancelable(false);
        return dialog;

    }

    public void onResume() {

        // Store access variables for window and blank point
        Window window = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            window = Objects.requireNonNull(getDialog()).getWindow();
        }else window =getActivity().getWindow();
        Point size = new Point();
        // Store dimensions of the screen in `size`
        assert window != null;
        Display display = window.getWindowManager().getDefaultDisplay();
        display.getSize(size);
        // Set the width of the dialog proportional to 75% of the screen width
        window.setLayout((int) (size.x * 0.75), (int) (size.y * 0.60));
        window.setGravity(Gravity.CENTER);
        // Call super onResume after sizing
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //如果没有选择新的设备则重新连接
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }

}

2.1.2 第二步、可以自定义自己前端界面,这里的dialog_clause.xml代码如下:


    

        


        

        
            
                

shape_circular_17_2.xml




    

    
    


2.1.3 第三步、调用FragmentDialog

    public void showDisclaimerDialog() {
        FragmentManager fm = getSupportFragmentManager();
        DisclaimerDialog editNameDialogFragment = DisclaimerDialog.newInstance();
        editNameDialogFragment.setIsMainActivity(true);
        editNameDialogFragment.setContext(this);
        editNameDialogFragment.show(fm, "fragment_device_scan");
    }

2.1.4 效果图如下

Android PopupWindow点击监听事件及DialogFragment、ProgressDialog、AlertDialog的使用_第2张图片

2.2. ProgressDialog的使用

2.2.1第一步、初始化

private void showTipsSyncProgress(int chapterMusicMax) {


            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            // 设置ProgressDialog 标题
            progressDialog.setTitle("同步中...请勿中断");
            // 设置ProgressDialog 提示信息
            progressDialog.setMessage("当前读取进度:");
            // 设置ProgressDialog 是否可以按退回按键取消
            progressDialog.setCancelable(false);
            progressDialog.setMax(chapterMusicMax);
            progressDialog.show();
        }
    }

2.2.2 第二步、设置进度

private void setProgressDialogProgress(int progress, String musicName) {

        progressDialog.setMessage("曲目:" + musicName);
        /*
            if (progress == maxMusicNumber) {
            //todo 进度达到100%时你想做的事情
        }
        */
    }

2.2.3 第三步最终效果如下

Android PopupWindow点击监听事件及DialogFragment、ProgressDialog、AlertDialog的使用_第3张图片

2.3 AlertDialog的使用:

2.3.1 调用AlertDialog

new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.select_operation_type))
                    .setItems(propNameList.toArray(new String[propNameList.size()]), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setCharaProp(propList.get(which));
                        }
                    })
                    .show();

2.3.2 自定义开发AlertDialog

AlertDialog.Builder builder = new AlertDialog.Builder(context);

        builder.setTitle("对话框");
        builder.setMessage(“对话框提示语“);
        builder.setIcon(R.drawable.cloude_school);//这里是对话框的一个logo
        builder.setCancelable(false);//外部点击是否可以关闭
        builder.setPositiveButton(getString(R.string.yuxin_str_4), new DialogInterface.OnClickListener() {//确认按钮

            @Override
            public void onClick(DialogInterface dialog, int which) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //todo 这里是你想做的业务
                    }
                });
                dialog.dismiss();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                         //todo 这里是你想做的点击取消后的业务
                    }
                });
                dialog.dismiss();

            }
        });

        dialog.show();                              //显示对话框

2.3.3 监听AlertDialog的显示和取消:

//显示和消失监听
        AlertDialog dialog = builder.create();
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {

                Log.e("tipDialog", getString(R.string.yuxin_str_6));
            }
        });
        //对话框消失的监听事件
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                Log.e("tipDialog", getString(R.string.yuxin_str_7));
            }
        });
        dialog.show();                              //显示对话框

2.3.4 通过反射修改按钮字体的颜色

dialog.show();
        try {
            Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
            mAlert.setAccessible(true);
            Object mAlertController = mAlert.get(dialog);
            Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView");
            mMessage.setAccessible(true);
            TextView mMessageView = (TextView) mMessage.get(mAlertController);
            mMessageView.setTextColor(Color.BLUE);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

你可能感兴趣的:(安卓)