Android AlertDialog 宽度自适应无效解决方法

在网上找了许久也没找到对应的有效方法。网上的通常是说getWindow、或者View对象修改LayoutParams。但试了一系列均是无效,能指定宽高,但还是无法自适应。最后想起以前的一个处理button边距。一些系统控件/UI会有默认的边距等属性。之前分析过button是通过theme预设了边距的。那么AlertDialog的宽度是是否如此呢?一步一步进入系统源码发现AlertDialog是有默认theme——R.attr.alertDialogTheme的。

①android.app.AlertDialog.Builder#Builder(android.content.Context)
②public Builder(Context context) {
            his(context, resolveDialogTheme(context, Resources.ID_NULL));
       }
③static @StyleRes int resolveDialogTheme(Context context, @StyleRes int themeResId) {
        if (themeResId == THEME_TRADITIONAL) {
            return R.style.Theme_Dialog_Alert;
        } else if (themeResId == THEME_HOLO_DARK) {
            return R.style.Theme_Holo_Dialog_Alert;
        } else if (themeResId == THEME_HOLO_LIGHT) {
            return R.style.Theme_Holo_Light_Dialog_Alert;
        } else if (themeResId == THEME_DEVICE_DEFAULT_DARK) {
            return R.style.Theme_DeviceDefault_Dialog_Alert;
        } else if (themeResId == THEME_DEVICE_DEFAULT_LIGHT) {
            return R.style.Theme_DeviceDefault_Light_Dialog_Alert;
        } else if (ResourceId.isValid(themeResId)) {
            // start of real resource IDs.
            return themeResId;
        } else {
            final TypedValue outValue = new TypedValue();
            context.getTheme().resolveAttribute(R.attr.alertDialogTheme, outValue, true);
            return outValue.resourceId;
        }
    }

由于我的电脑内存小没下载源码深层源码无法看到具体属性,但也是可以佐证了我的猜想。然后找了一个以前自定义Dialog的主题,去创建AlertDialog 。一时即中。在创建AlertDialog时传入不同的主题即可做到宽度自适应。如:R.style.Theme_AppCompat_Dialog

 AlertDialog.Builder exitBuilder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容