创建自定义对话框

 

        官方还提示我们,一般使用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();   
    }

 

运行效果如下:




 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值