android - 具有标准图标、标题和按钮的独立于平台版本的自定义对话框

标签 android dialog customization platform-independent

我要存档的内容:我想要一个带有自定义 View 的对话框,但我想要来自 AlertDialog 的标准图标、标题和按钮.

我正在做的是这个自定义对话框类:

public class CustomDialog extends AlertDialog.Builder {

    private Activity activity;
    private View root;

    public CustomDialog(Activity context) {
        super(context);
        this.activity = context;
    }

    public void setView(int layoutResID) {
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        root = inflater.inflate(layoutResID, (ViewGroup) activity.findViewById(R.id.dialog_root), false);
        ScrollView scroller = new ScrollView(activity);
        scroller.addView(root);
        setView(scroller);
    }

    public void setCustomView(View v) {
        ScrollView scroller = new ScrollView(activity);
        scroller.addView(v);
        setView(scroller);
    }

    public View getRoot() {
        return root;
    }

    @Override
    public AlertDialog create() {
        AlertDialog dialog = super.create();

        dialog.getWindow().getAttributes().width = LayoutParams.MATCH_PARENT;

        return dialog;
    }
}

效果很好,期待 TextView前 Honeycomb 和 Honeycomb 设备上的颜色不正确。我正在使用 Holo.Light主题,因此标准文本颜色为黑色,但在 Honeycomb 之前的设备上对话框的背景颜色也是如此。在 Honeycomb 设备上,对话框背景是白色的。所以我所做的是,我添加了一个 dialogTextColor=whitestyles.xmlvalues文件夹和 dialogTextColor=blackvalues-v11文件夹。然后我必须将样式属性添加到每个 TextView我在自定义对话框中使用的。这在 ICS 之前一直有效,并且很清楚为什么 -> v11。我可以更改它,但我想要一个自定义对话框,它可以正确执行所有操作:基于应用程序主题、对话框宽度的 pre-Honeycomb、Honeycomb、ICS(以及将来出现的任何内容)上的文本颜色, AlertDialog 中的标准按钮、标题、图标.

最佳答案

这里的技巧是上下文与主题相关联。该主题决定了各种事情,例如默认文本颜色等。

在 Honeycomb Dialogs 之前,无论它们是由浅色主题还是深色主题 Activity 生成的,它们始终具有相同的主题,并且列表对话框除外,背景为深色,前景为浅色。在 Honeycomb 和 forward 中,对话框具有不同的主题,由生成它们的 Activity 决定。

在 Dialog 中扩充内容时,始终使用 Dialog#getContext() 方法返回的 Context 而不是生成 Dialog 的 Activity。不要使用上面用来获取 LayoutInflater 的代码行,而是尝试:

LayoutInflater inflater = LayoutInflater.from(getContext());

编辑:看起来您使用的是 AlertDialog.Builder 而不是 Dialog。 AlertDialog.Builder 为此目的在 API 11(Android 3.0,又名 Honeycomb)中添加了一个 getContext() 方法,但在此之前它并不存在。您可以使用 ContextThemeWrapper 为旧设备构建自己的主题上下文。只要确保您永远不会尝试在旧版本的平台上调用该方法即可。您可以通过简单的检查来保护它:

Context themedContext;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    themedContext = getContext();
} else {
    themedContext = new ContextThemeWrapper(activity, android.R.style.Theme_Dialog);
}
LayoutInflater inflater = LayoutInflater.from(themedContext);

关于android - 具有标准图标、标题和按钮的独立于平台版本的自定义对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8547720/

相关文章:

javascript - NFC 读取器 Apache · Cordova

android - 如何设置 fable-elmish-react native 应用程序?

android - 查找按钮的父对话框

delphi - 如何使 'Showmessage' 对话框更宽以适合文本?

checkbox - 请求对话框复选框选项 "don' 发送前询问...”

css - 为什么谷歌的 infoWindow CSS 没有暴露?定制太难

java gson在序列化时替换密码值

android - android编程中如何将EditText中的特殊字改成特殊颜色?

android - 如何打印百分比字符?

azure - 如何将环境相关文本添加到 Azure AD 登录页面