3

我要存档的内容:我想要一个包含自定义视图的对话框,但我想要标准图标、标题、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 设备上,对话框背景是白色的。所以我所做的是,我dialogTextColor=white在文件夹和文件夹styles.xml中添加了一个。然后我必须将样式属性添加到每个valuesdialogTextColor=blackvalues-v11TextView我在自定义对话框中使用。这在 ICS 之前一直有效,并且很清楚为什么 -> v11。我可以更改它,但我想要一个自定义对话框,它可以做所有正确的事情:基于应用程序主题的 pre-Honeycomb、Honeycomb、ICS(以及将来会出现的任何内容)上的文本颜色、对话框的宽度、标准按钮、标题、图标AlertDialog

4

1 回答 1

11

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

在 Honeycomb 对话框之前,无论它们是由浅色或深色主题的活动生成的,它们总是具有相同的主题,除了列表之外,对话框是深色背景,浅色前景。在 Honeycomb 和 forward 中,Dialog 具有不同的主题,由生成它们的 Activity 决定。

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

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

编辑:看起来您使用的是 AlertDialog.Builder 而不是对话框。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);
于 2011-12-17T20:49:42.547 回答