Android Dialog自定义弹窗

1、加载自定义的弹窗内容


private void showDialog(Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("弹窗标题");
    LayoutInflater inflater = LayoutInflater.from(context);
    //弹窗需要展示什么内容,就在 R.layout.my_dialog 自己添加
    View root = inflater.inflate(R.layout.my_dialog, null);
    builder.setView(root);
    AlertDialog dialog = builder.create();
    dialog.show();
}

2、自定义弹窗宽高(按屏幕总宽高的百分比来设置)要在 dialog.show() 之后调用


private static final float SCALE_WIDTH = 0.75f;//弹窗宽度百分比
private static final float SCALE_HEIGHT = 0.8f;//弹窗高度百分比

private void setDialogSize(Context context, AlertDialog dialog) {
    Window window = dialog.getWindow();
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    int screenWidth = displayMetrics.widthPixels;
    int screenHeight = displayMetrics.heightPixels;
    WindowManager.LayoutParams dialogParems = window.getAttributes();
    dialogParems.width = (int) (screenWidth * SCALE_WIDTH);//可以设置具体的值,比如500,单位是px
    dialogParems.height = (int) (screenHeight * SCALE_HEIGHT);
    window.setAttributes(dialogParems);
}

3、设置点击弹窗输入框时允许弹出输入法软键盘


mDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

4、设置弹窗是否可以消失(点击取消或确认时)


//canDismiss:如果传参true,则弹窗正常消失,如果传参false,则点击确认或取消按钮后弹窗不消失
private static void setDialogCanDismiss(boolean canDismiss) {
    try {
        Field field = mDialog.getClass().getSuperclass().getDeclaredField("mShowing");
        field.setAccessible(true);
        field.set(mDialog, canDismiss);
    } catch (Exception e) {
        Log.e("tag", Objects.requireNonNull(e.getMessage()));
    }
}

//用法如下:
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        //点击了确定按钮,此时自己做一些判断,看是否需要弹窗不消失继续显示
        if (inNeedShowDialog) {
            //设置弹窗不消失
            setDialogCanDismiss(false);
        } else {
            //设置弹窗可以消失
            setDialogCanDismiss(true);
        }
    }
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        //设置弹窗可以消失
        setDialogCanDismiss(true);
        mDialog.dismiss();
    }
});

5、弹窗返回数据的接口定义,接口名、函数名、参数名、数据类型都可以根据实际需求灵活自定义


interface IDialogResult {
    void onGetResult(List<HashMap<String, String>> result);
}

6、弹窗自定义view常用的一些api


int childCount = parentView.getChildCount();//获取父控件中子控件的数量
View childView = parentView.getChildAt(position);//获取指定位置的子控件对象
parentView.removeView(parentView.getChildAt(position));//移除指定位置的子控件对象
parentView.removeView(childView);//移除指定的子控件对象
parentView.addView(childView);//插入子控件

 7、其它:EditText控件监听焦点丢失事件以及软键盘点击回车键事件

private void addLostFocusListener(EditText editText, int position) {
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                //TODO
            }
        }
    });
    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_DONE || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                editText.clearFocus();
            }
            return true;
        }
    });
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Android Studio中自定义可以通过以下步骤实现: 1. 首先,在res/values/styles.xml文件中定义一个自定义的对话框主题,可以使用如下代码: ``` <style name="CustomDialog" parent="android:style/Theme.Dialog"> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowNoTitle">true</item> <item name="android:windowFrame">@null</item> <item name="android:windowIsFloating">true</item> <item name="android:backgroundDimEnabled">true</item> </style> ``` 2. 然后,在res/layout文件夹中创建对话框布局文件,例如dialog_layout.xml。 3. 创建一个自定义的对话框类,例如DialogView,继承自android.app.Dialog,并在构造函数中设置布局和主题,可以使用如下代码: ``` public class DialogView extends Dialog { public DialogView(@NonNull Context context, int layout, int style, int gravity) { super(context, style); setContentView(layout); Window mWindow = getWindow(); // 设置对话框宽度、高度和位置 // WindowManager.LayoutParams params = mWindow.getAttributes(); // params.width = WindowManager.LayoutParams.MATCH_PARENT; // params.height = WindowManager.LayoutParams.WRAP_CONTENT; // params.gravity = gravity; // mWindow.setAttributes(params); } } ``` 4. 最后,在使用自定义对话框的地方,创建DialogView实例并设置相应的参数。 此外,你还可以通过在res/drawable文件夹下创建XML文件来定义对话框的背景,例如bg_custom_dialog.xml,可以参考以下代码: ``` <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="10dp"/> <solid android:color="@color/white"/> </shape> ``` 这样就可以在Android Studio中实现自定义了。123 #### 引用[.reference_title] - *1* *2* [Android开发-自定义框篇(一)](https://blog.csdn.net/x97666/article/details/130140885)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}} ] [.reference_item] - *3* [androidstudio自定义Dialog](https://blog.csdn.net/m0_57458432/article/details/129636189)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

却染人间愁

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

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

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

打赏作者

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

抵扣说明:

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

余额充值