2012-08-24 47 views

回答

19

创建自定义对话框

如果你想为一个对话框,以定制的设计,您可以用布局和widget元素的对话窗口中创建自己的布局。在定义布局之后,将根视图对象或布局资源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定义了一个ImageView的和的LinearLayout内一个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。既然对话框具有已定义的布局,您可以使用findViewById(int)从布局中捕获视图对象并修改其内容。 就是这样。您现在可以按照显示对话框中所述显示对话框。 使用基础Dialog类进行的对话框必须有标题。如果您不调用setTitle(),则用于标题的空间保持空白,但仍然可见。如果您根本不需要标题,那么您应该使用AlertDialog类创建自定义对话框。但是,由于AlertDialog是使用AlertDialog.Builder类创建的最简单的方法,因此无法访问上面使用的setContentView(int)方法。相反,你必须使用setView(View)。该方法接受一个View对象,所以你需要从XML中扩展布局的根视图对象。

要扩充XML布局,请使用getLayoutInflater()(或getSystemService())检索LayoutInflater,然后调用inflate(int,ViewGroup),其中第一个参数是布局资源ID,第二个参数是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类的参考文档。

+4

感谢您对我的搜索引擎优化,我会在角落里坐几分钟的时间来处罚。 –