3

我找到了很多关于如何制作没有文本的自定义 ProgressDialog 的教程。使用自定义图像和消息创建自定义 ProgressDialog 的最简单方法是什么。像这样的东西...

在此处输入图像描述

4

1 回答 1

21

创建自定义对话框

如果您想要自定义的对话框设计,您可以使用布局和小部件元素为对话框​​窗口创建自己的布局。定义布局后,将根视图对象或布局资源 ID 传递给 setContentView(View)。

例如,要创建如右图所示的对话框:

创建一个保存为 custom_dialog.xml 的 XML 布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              >
    <ImageView android:id="@+id/image"
               android:layout_width="wrap_content"
               android:layout_height="fill_parent"
               android:layout_marginRight="10dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FFF"
              />
</LinearLayout>

此 XML 在 LinearLayout 中定义了一个 ImageView 和一个 TextView。将上述布局设置为对话框的内容视图,并为 ImageView 和 TextView 元素定义内容:

Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);

dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");

TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);

实例化对话框后,使用 setContentView(int) 将自定义布局设置为对话框的内容视图,并将布局资源 ID 传递给它。现在 Dialog 已经定义了布局,您可以使用 findViewById(int) 从布局中捕获 View 对象并修改它们的内容。而已。您现在可以显示对话框,如显示对话框中所述。使用基本 Dialog 类创建的对话框必须有标题。如果您不调用 setTitle(),则用于标题的空间仍然是空的,但仍然可见。如果您根本不想要标题,那么您应该使用 AlertDialog 类创建自定义对话框。但是,由于使用 AlertDialog.Builder 类最容易创建 AlertDialog,因此您无法访问上面使用的 setContentView(int) 方法。相反,您必须使用 setView(View)。

要膨胀 XML 布局,请使用 getLayoutInflater()(或 getSystemService())检索 LayoutInflater,然后调用 inflate(int, ViewGroup),其中第一个参数是布局资源 ID,第二个参数是根 View 的 ID。此时,您可以使用膨胀布局在布局中查找 View 对象,并为 ImageView 和 TextView 元素定义内容。然后实例化 AlertDialog.Builder 并使用 setView(View) 设置对话框的膨胀布局。

这是一个示例,在 AlertDialog 中创建自定义布局:

AlertDialog.Builder builder;
AlertDialog alertDialog;

Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
                               (ViewGroup) findViewById(R.id.layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);

builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();

为您的自定义布局使用 AlertDialog 可让您利用内置的 AlertDialog 功能,如托管按钮、可选列表、标题、图标等。

有关详细信息,请参阅 Dialog 和 AlertDialog.Builder 类的参考文档。

于 2012-08-24T19:19:26.307 回答