android - 未显示自定义警报对话框

标签 android android-alertdialog

我想显示一个自定义警告对话框,其结构已在 XML 文件中定义。这是我使用的代码。

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(findViewById(R.layout.inputform));
builder.show();

点击按钮时触发。但是,窗口没有显示。我在屏幕顶部得到了这个透明的灰色层,无法点击任何东西。不过,一些基本代码(例如使用 setMessage 或显示复选框)效果很好。谁能指出我哪里做错了?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" android:layout_height="fill_parent">

<TableLayout android:id="@+id/TableLayout01"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

<TableRow android:id="@+id/TableRow01" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:text="Room name" android:id="@+id/TextView01"
        android:layout_width="fill_parent" android:layout_height="wrap_content"/>
    <EditText android:hint="Enter room name" android:id="@+id/EditText01"
        android:layout_width="0dp" android:layout_height="wrap_content"
        android:layout_weight="1"/>
</TableRow>

<TableRow android:id="@+id/TableRow02" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:text="Point id" android:id="@+id/TextView02"
        android:layout_width="fill_parent" android:layout_height="wrap_content"/>
    <EditText android:hint="Enter point id" android:id="@+id/EditText02"
        android:layout_width="0dp" android:layout_height="wrap_content"
        android:layout_weight="1"/>
</TableRow>

<TableRow android:id="@+id/TableRow03" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button android:text="OK" android:id="@+id/btnOK"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</TableRow>

</TableLayout>
</LinearLayout>

最佳答案

这是因为 findViewById 用于在当前 Activity 的布局中查找特定 View ,而不是用于加载整个布局。

您可以使用 @Matt's回答或者你可以用 LayoutInflater 扩充布局像这样:

LayoutInflater li = getLayoutInflater();
View v = li.inflate(R.layout.inputform);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(v);
builder.show();

(没试过,但我认为应该可以)。

关于android - 未显示自定义警报对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4828329/

相关文章:

android - 在 Android 中从 ListView 切换到子 ListView

android - 在对话框之间显示 ProgressDialog

android - Alert Dialog.builder object.create() vs object.show() vs obj.create().show() 之间的区别

android - 如何更改 DatePickerDialog 中按钮的背景颜色?

android - 需要帮助获得自定义布局以使用我的 Android AlertDialog

android - 运行 Android ActivityUnitTestCase 结果为 "RuntimeException: could not find test class"

java - 如何在 Github 包中添加我的 Android 库的依赖项?

android - 为什么我不能从 json Retrofit 中获取特殊字段?

java - 无法使用 ADT 20 在 Eclipse 中创建 Android 项目

android - 警报对话框主题