Android PopupWindow 内部点击和外部点击事件实现

一、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如下:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <FrameLayout
        android:id="@+id/fl100"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@drawable/shape_circular_42_a">
        <ImageView
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_gravity="center"
            app:srcCompat="@drawable/ic_boy"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="男生"
            android:textColor="@color/white"
            android:layout_gravity="center_horizontal|bottom"
            android:textSize="@dimen/text_size_12sp"/>
    </FrameLayout>
    <View
        android:layout_width="200dp"
        android:layout_height="1px"
        android:layout_gravity="center"/>
    <FrameLayout
        android:id="@+id/fl101"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@drawable/shape_circular_42_b">
        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            app:srcCompat="@drawable/ic_girl"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="女生"
            android:textColor="@color/white"
            android:layout_gravity="center_horizontal|bottom"
            android:textSize="@dimen/text_size_12sp"/>
    </FrameLayout>

</LinearLayout>


1.3 效果图如下

在这里插入图片描述

二、DialogFragment的使用

2.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.2 第二步、编写xml代码

dialog_clause.xml代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FFFFFF"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:background="@drawable/shape_circular_17_2"
        android:layout_margin="5dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textStyle="bold"
            android:textColor="#3F51B5"
            android:layout_marginTop="15dp"
            android:layout_marginEnd="15dp"
            android:layout_gravity="center"
            android:text="声明与条款" />


        <TextView
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:padding="10dp"
            android:textStyle="normal"
            android:textColor="#242424"
            android:textSize="18sp"
            />

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="15dp"
            android:orientation="horizontal">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <Button
                    android:id="@+id/exit_btn"
                    android:layout_width="match_parent"
                    android:layout_height="35dp"
                    android:layout_gravity="center"
                    android:paddingStart="15dp"
                    android:paddingEnd="15dp"
                    android:background="@drawable/shape_circular_17_1"
                    android:textStyle="bold"
                    android:scaleType="fitCenter"
                    android:textColor="@color/white"
                    android:text="同意并继续" />
                <Button
                    android:id="@+id/exit_btn_1"
                    android:layout_width="match_parent"
                    android:layout_height="35dp"
                    android:layout_gravity="center"
                    android:layout_marginTop="30dp"
                    android:paddingStart="15dp"
                    android:background="@color/white"
                    android:paddingEnd="15dp"
                    android:textColor="#464646"
                    android:textStyle="bold"
                    android:scaleType="fitCenter"
                    android:text="不同意" />

            </LinearLayout>


        </FrameLayout>
    </LinearLayout>
</LinearLayout>

shape_circular_17_2.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <stroke
        android:width="2dp"
        android:color="#535353" />

    <corners android:radius="20dp" />
    <solid android:color="@color/white" />

</shape>
2.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.4 效果图如下

在这里插入图片描述

三、 ProgressDialog的使用

3.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();
        }
    }
3.2 第二步、设置进度
private void setProgressDialogProgress(int progress, String musicName) {

        progressDialog.setMessage("曲目:" + musicName);
        /*
            if (progress == maxMusicNumber) {
            //todo 进度达到100%时你想做的事情
        }
        */
    }
3.3 第三步最终效果如下

在这里插入图片描述

四、AlertDialog的使用:

4.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();
4.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();                              //显示对话框
4.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();                              //显示对话框
4.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();
        }

更新:2022年12月1日15:09:11
深度定制化开发可以使用Xpopop

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全面解读

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值