为了显示具有丰富内容和输入元素的对话框,我使用Android的AlertDialog.Builder
创建 AlertDialog
的对象然后我使用系统的LayoutInflater
将内容 ( setView(...)
) 设置为某个 XML 布局文件。
这在 Android 2.X 上看起来很完美(深色背景,白色文本):
但在 Android 4.X 上它根本不可读:
注意:当然,这些对话框并不相同,但是两个对话框都会出现问题。
那我做错了什么?我正在使用Theme.Light
API 级别 < 11 和 Theme.Holo.Light
>= 11 上。
编辑1:这是我用于膨胀的代码:
private LayoutInflater mGlobalInflater; // in Activity class
mGlobalInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE); // in Activity's onCreate()
mGlobalInflater.inflate(R.layout.input_dialog, null); // when needed
编辑 2: 这是“选择日期” View 的膨胀 XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="15dp">
<DatePicker
android:id="@+id/input_date"
android:startYear="1900"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:text="@string/hint" />
</LinearLayout>
编辑 3: 正如我现在发现的,使用 mGlobalInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
时,膨胀的对话框内容可以在 Android <= 2.3.3 上正确呈现。当使用 mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
时,它在 Android >= 3.0 上正确呈现。所以Context
有所作为。为什么?
编辑4:
该对话框在onContextItemSelected()
内创建并膨胀。的Activity
:
AlertDialog.Builder dialogPoup = new AlertDialog.Builder(MainActivity.this);
dialogPoup.setTitle("abc123");
final View inputDialog = mGlobalInflater.inflate(R.layout.input_dialog, null);
// setting some properties of the view and its child views
dialogPoup.setView(inputDialog);
这是正确的吗?或者我必须更换MainActivity.this
通过变量 mContext
(例如)Activity
的上下文被分配到 onCreate()
?
最佳答案
不要像上面的代码中那样使用 getApplicationContext()
获取 LayoutInflater,而是使用 Activity 中的一个,如下所示:
mGlobalInflater = LayoutInflater.from(this); // in Activity's onCreate()
这应该使用与对话框匹配的主题。
关于android - 膨胀的 AlertDialogs 在 Android 4.X 上不可读,而在 Android 2.X 上看起来很完美,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12712827/