自定义对话框中的图标(Android)

4

有没有一种方法可以在自定义对话框中设置图标,而不使用AlertDialog的方法? Dialog有标题,但缺少漂亮的分隔线和设置图标的能力,但肯定有一种方法可以同时获得这两个功能,而不必使用AlertDialog。

2个回答

19

你可以使用以下代码添加图标:

Dialog dialog = new Dialog(context);

dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Dialog Title");

dialog.show();
dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.your_icon);

如果要在对话框中添加分隔符,您可以简单地在布局中添加一个ImageView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:src="@android:drawable/divider_horizontal_dim_dark"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:text="content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

似乎也不起作用...我得到了一个01-24 04:46:24.037: ERROR/AndroidRuntime(1693): android.util.AndroidRuntimeException: requestFeature() 必须在添加内容之前调用的错误。 - Maxrunner
1
你是否在调用setContentView()之前调用了requestWindowFeature()函数? - Gubbel
谢谢Gubbel,这对我很有效。注意:在“show()”之后设置Drawable是不必要的,这很好,因为通常Dialog是在“onCreateDialog()”中创建的,而“show()”在其他地方调用。 - Ridcully
但是需要在setContentView之下设置setFeatureDrawable,请查看https://groups.google.com/forum/?fromgroups=#!topic/android-developers/G_5MAq8v4jc - Himanshu Virmani

2

使用渐变形状是添加分隔符的一种好方法。

只需在res/drawable/目录中创建一个名为gradient.xml的文件,并将以下内容放入其中:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:shape="rectangle">

<gradient android:startColor="#424542" 
          android:centerColor="#FFFFFF"
          android:endColor="#424542" 
          android:angle="0" />
</shape>

然后在你的LinearLayout里面,你可以放置一个View:

<View android:id="@+id/divider" 
      android:layout_width="fill_parent"
      android:layout_height="1dip"
      android:background="@drawable/gradient">
</View>

然后它会绘制一个漂亮的渐变分隔线 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接