android 自定义 Dialog

本文介绍了一种使用Android的AlertDialog.Builder创建自定义对话框的方法。通过一个具体的例子展示了如何在一个按钮点击事件中弹出自定义的对话框,并加载特定的布局文件作为对话框的内容。

自定义的dialog是我们在平时开发和学习经常用到,网上有很多是关于AlterDialog或者是Dialog.builder

的类创建的。

我们常常最好是,我们在一个layout.xml中定义好我们的布局以后,能够用都dialog的形式表示出来,这也是我比较喜欢的。

 

下面就就来下

 

package endual.man;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	
	private Button btn ;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainx);
        
        btn = (Button) this.findViewById(R.id.button1) ;
        
    	
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog myDialog = new AlertDialog.Builder(MainActivity.this).create();
		        myDialog.show();
		       //这里注意一定要先show dialog 再去加载 contentView。否则会出现异常。(requestFeature must
		      // be called before add content)
		       myDialog.getWindow().setContentView(R.layout.main);
			}
			
		}) ;
        
    }
}

mainx.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.android.gif"
    android:orientation="vertical"
    android:layout_width="220px"
    android:layout_height="176px"
    android:background="@drawable/ic_launcher"
    android:id="@+id/layout_root"
    >


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.android.gif"
    android:orientation="vertical"
    android:layout_width="220px"
    android:layout_height="176px"
    android:background="@drawable/ic_launcher"
    android:id="@+id/layout_root"
    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:layout_marginLeft="10px"
    />
    <TextView
           android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="loading......"
        android:gravity="center"
    />
</LinearLayout>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值