官方还提示我们,一般使用Dialog类来创建对话框,是需要setTitle的,不设置的话,标题占用的空间保持为空,但仍然可见。而不想要那个标题,那应该使用警告对话框AlertDialog来创建自定义对话框。然而,因为警告对话框可以很简单的通过AlertDialog.Builder 类来创建,你并不需要访问上面使用的setContentView(int) 方法。相反,你必须使用setView(View),则需要使用LayoutInflater来加载Layout得到View。
LayoutInflater这个类还是非常有用的,它的作用类似于 findViewById(),不同点是,LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体 widget控件(如:Button,TextView等)。
custom_dialog.xml文件如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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="#7CFC00" />
</LinearLayout>
自定义对框代码如下:
public void showCustomDialog(){
AlertDialog.Builder builder;
AlertDialog alertDialog;
Context mContext = this;
//下面两种方法都可以获取LayoutInflater对象
LayoutInflater inflater = getLayoutInflater();
// LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
//设置控件属性值
View layout = inflater.inflate(R.layout.alert_style, null);
TextView text = (TextView)layout.findViewById(R.id.text);
text.setText("Hello, Welcome to xh blog");
ImageView image = (ImageView)layout.findViewById(R.id.image);
image.setImageResource(R.drawable.icon);//给ImageView 设置图标
//将layout绑定到AlertDialog,并且显示
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
alertDialog.show();
}
运行效果如下: