【发布时间】:2012-08-24 19:13:16
【问题描述】:
我找到了很多关于如何制作没有文本的自定义 ProgressDialog 的教程。使用自定义图像和消息创建自定义 ProgressDialog 的最简单方法是什么。像这样的……
【问题讨论】:
我找到了很多关于如何制作没有文本的自定义 ProgressDialog 的教程。使用自定义图像和消息创建自定义 ProgressDialog 的最简单方法是什么。像这样的……
【问题讨论】:
创建自定义对话框
如果您想要自定义的对话框设计,您可以使用布局和小部件元素为对话框窗口创建自己的布局。定义布局后,将根视图对象或布局资源 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)。此方法接受一个 View 对象,因此您需要从 XML 扩展布局的根 View 对象。
要对 XML 布局进行膨胀,使用 getLayoutInflater()(或 getSystemService())检索 LayoutInflater,然后调用 inflate(int, ViewGroup),其中第一个参数是布局资源 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 类的参考文档。
【讨论】: