【发布时间】:2012-10-03 16:30:12
【问题描述】:
为了显示具有丰富内容和输入元素的对话框,我使用Android的AlertDialog.Builder创建AlertDialog的对象,然后使用系统的LayoutInflater将内容(setView(...))设置为一些XML布局文件。
这在 Android 2.X 上看起来很完美(深色背景,白色文本):
但在 Android 4.X 上它根本不可读:
注意:当然,这些对话框并不相同,但两个对话框都会出现问题。
那我做错了什么?我在 API 级别 Theme.Light,在 >= 11 上使用 Theme.Holo.Light。
编辑 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:这是“选择日期”视图的膨胀 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 = 3.0 上使用时正确呈现mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);。所以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 替换为Activity 的上下文在onCreate() 中分配的变量mContext(例如)?
【问题讨论】:
-
而不是发布标准的通胀代码,xml文件怎么样?
-
这也没什么特别的 ;)
-
不久前我遇到了类似的事情。尝试在布局上明确设置 textcolor。你必须为不同的 api 版本创建不同的布局,但我认为这是你必须做的。
-
没有别的办法了吗?我的意思是,我使用标准主题和简单的 XML 进行布局。那么为什么看起来这么糟糕呢? API 级别 >= 11 是否不再支持在对话框中膨胀视图?
-
是的。文档希望人们改用对话片段,但我认为这不会有所作为。看看您是否可以在主题中为 api > 11 指定自定义文本颜色 - 您可能必须为其创建样式并在主题中设置属性,例如
android:textViewStyle或其他内容。
标签: android android-layout android-theme android-inflate android-version