android 自定义Dialog.Builder弹出框

1.自定义Diolog类
package com.test.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.test.R;

/**
 * 自定义弹出框
 * 
 * @author Administrator
 * 
 */
@SuppressWarnings("all")
public class CustomDialog extends Dialog {

	public CustomDialog(Context context) {
		super(context);
	}

	public CustomDialog(Context context, int theme) {
		super(context, theme);
	}

	// 主要是重写Bulder内部类
	public static class Builder {

		private Context context;
		private String title;
		private String message;
		private String positiveButtonText;
		private String negativeButtonText;
		private View contentView;
		private DialogInterface.OnClickListener positiveButtonClickListener;
		private DialogInterface.OnClickListener negativeButtonClickListener;

		public Builder(Context context) {
			this.context = context;
		}

		public Builder setMessage(String message) {
			this.message = message;
			return this;
		}

		/**
		 * 设置的内容
		 * 
		 * @param message
		 * @return
		 */
		public Builder setMessage(int message) {
			this.message = (String) context.getText(message);
			return this;
		}

		/**
		 * 设置标题
		 * 
		 * @param title
		 * @return
		 */
		public Builder setTitle(int title) {
			this.title = (String) context.getText(title);
			return this;
		}

		/**
		 * 设置标题
		 * 
		 * @param title
		 * @return
		 */

		public Builder setTitle(String title) {
			this.title = title;
			return this;
		}

		public Builder setContentView(View v) {
			this.contentView = v;
			return this;
		}

		/**
		 * 设置确定按钮
		 * 
		 * @param positiveButtonText
		 * @param listener
		 * @return
		 */
		public Builder setPositiveButton(int positiveButtonText,
				DialogInterface.OnClickListener listener) {
			this.positiveButtonText = (String) context
					.getText(positiveButtonText);
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setPositiveButton(String positiveButtonText,
				DialogInterface.OnClickListener listener) {
			this.positiveButtonText = positiveButtonText;
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(int negativeButtonText,
				DialogInterface.OnClickListener listener) {
			this.negativeButtonText = (String) context
					.getText(negativeButtonText);
			this.negativeButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(String negativeButtonText,
				DialogInterface.OnClickListener listener) {
			this.negativeButtonText = negativeButtonText;
			this.negativeButtonClickListener = listener;
			return this;
		}
		// 这是自定义弹出框的关键
		public CustomDialog create() {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			// instantiate the dialog with the custom Theme
			final CustomDialog dialog = new CustomDialog(context,
					R.style.Dialog);
			View layout = inflater.inflate(R.layout.dialog, null);
			dialog.addContentView(layout, new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			// 设置标题
			((TextView) layout.findViewById(R.id.title)).setText(title);
			// 设置确认按钮
			if (positiveButtonText != null) {
				((Button) layout.findViewById(R.id.positiveButton))
						.setText(positiveButtonText);
				if (positiveButtonClickListener != null) {
					((Button) layout.findViewById(R.id.positiveButton))
							.setOnClickListener(new View.OnClickListener() {
								public void onClick(View v) {
									positiveButtonClickListener.onClick(dialog,
											DialogInterface.BUTTON_POSITIVE);
								}
							});
				}
			} else {
				//如果没有确认按钮则隐藏
				layout.findViewById(R.id.positiveButton).setVisibility(
						View.GONE);
			}
			// 设置取消按钮
			if (negativeButtonText != null) {
				((Button) layout.findViewById(R.id.negativeButton))
						.setText(negativeButtonText);
				if (negativeButtonClickListener != null) {
					((Button) layout.findViewById(R.id.negativeButton))
							.setOnClickListener(new View.OnClickListener() {
								public void onClick(View v) {
									negativeButtonClickListener.onClick(dialog,
											DialogInterface.BUTTON_NEGATIVE);
								}
							});
				}
			} else {
				//如果没有取消按钮则隐藏
				layout.findViewById(R.id.negativeButton).setVisibility(
						View.GONE);
			}
			// 设置消息
			if (message != null) {
				((TextView) layout.findViewById(R.id.message)).setText(message);
			} else if (contentView != null) {
				((LinearLayout) layout.findViewById(R.id.content))
						.removeAllViews();
				((LinearLayout) layout.findViewById(R.id.content)).addView(
						contentView, new LayoutParams(LayoutParams.MATCH_PARENT,
								LayoutParams.MATCH_PARENT));
			}
			// 把设置好的View加载到弹出框
			dialog.setContentView(layout);
			return dialog;
		}
	}
}



2.弹出框所使用的布局文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="false"
    android:orientation="vertical"
    android:padding="20.0dip" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/bg_bombbox"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/title"
            style="@style/text_18_ffffff"
            android:layout_width="fill_parent"
            android:layout_height="40.0dip"
            android:gravity="center"
            android:text="@string/title_alert"
            android:visibility="visible" />

        <LinearLayout
			android:id="@+id/content"
    		android:layout_width="fill_parent"
     		android:layout_height="wrap_content"
            android:gravity="center" >
		      <TextView
		        android:id="@+id/message"
		        style="@style/text_16_666666"
		        android:layout_width="fill_parent"
		        android:layout_height="wrap_content"
		        android:gravity="left|center"
		        android:lineSpacingMultiplier="1.5"
		        android:minHeight="120.0dip"
		        android:paddingBottom="15.0dip"
		        android:paddingLeft="20.0dip"
		        android:paddingRight="20.0dip"
		        android:paddingTop="15.0dip" />
    	</LinearLayout>
		<!-- 设置分割线 -->
        <View
            android:layout_width="fill_parent"
            android:layout_height="1.0px"
            android:background="#8CC34B" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="60.0dip"
            android:layout_gravity="bottom"
            android:background="@drawable/dialog_bottom_bg"
            android:gravity="center"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/positiveButton"
                style="@style/text_15_ffffff_sdw"
                android:layout_width="114.0dip"
                android:layout_height="40.0dip"
                android:background="@drawable/btn_ok_selector"
                android:gravity="center"
                android:text="@string/ok" />

            <Button
                android:id="@+id/negativeButton"
                style="@style/text_15_666666_sdw"
                android:layout_width="114.0dip"
                android:layout_height="40.0dip"
                android:layout_marginLeft="20.0dip"
                android:background="@drawable/btn_cancel_selector"
                android:gravity="center"
                android:text="@string/cancel" />
        </LinearLayout>
    </LinearLayout>

</FrameLayout>


3.activity内容

package com.test.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Window;

import com.test.R;
import com.test.widget.CustomDialog;

public class DialogActivity extends Activity{
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.dialogmain);
		// 自定义标题
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	public void showAlertDialog(View view) {

		CustomDialog.Builder builder = new CustomDialog.Builder(this);
		builder.setMessage("这个就是自定义的提示框");
		builder.setTitle("提示");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// 隐藏dialog
				dialog.dismiss();
				System.out.println("------------------点击确定----------------");
			}
		});

		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// 隐藏dialog
						dialog.dismiss();
						System.out.println("------------------点击取消----------------");
					}
				});
		builder.create().show();
	}
}



使用替换layout布局文件的方法

页面布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:orientation="vertical" >     
<!-- 顶部椭园边缘 -->
<ImageView        
  android:layout_width="400dp"        
  android:layout_height="22dp"        
  android:src="@drawable/dialog_top" >
</ImageView>
<!-- 中间白色背景,两个TextView,标题和内容,留一个LinearLayout,在代码中根据调用动态加上按钮 -->
<LinearLayout        
android:layout_width="400dp"        
android:layout_height="wrap_content"        android:background="@drawable/dialog_center"        
android:orientation="vertical" >         
<TextView android:textColor="#000000"            
android:textSize="35dp"            
android:gravity="center"            
android:id="@+id/title"            
android:layout_width="fill_parent"            
android:layout_height="wrap_content" />         
<TextView android:layout_marginLeft="20dp"            android:layout_marginRight="10dp"            
android:id="@+id/message"            
android:layout_marginBottom="10dp"            
android:layout_marginTop="20dp"            
android:textColor="#000000"            
android:textSize="25dp"            
android:layout_width="fill_parent"            
android:layout_height="wrap_content" />
<!-- 在LinearLayout中加按钮 -->
<LinearLayout            
android:id="@+id/buttonLayout"            
android:layout_width="fill_parent"            
android:layout_height="fill_parent"            
android:layout_gravity="center"            
android:gravity="center"            
android:orientation="horizontal" >         
</LinearLayout>
</LinearLayout>
<!-- 底部椭园边缘 -->
<ImageView        
android:layout_marginTop="-2dp"        
android:layout_width="400dp"       
android:layout_height="22dp"        
android:src="@drawable/dialog_bottom" >
</ImageView>
</LinearLayout>


selector

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:drawable="@drawable/dialog_button_pressed" />
    <item android:state_focused="true" android:drawable="@drawable/dialog_button_pressed" />
    <item android:drawable="@drawable/dialog_button" />
</selector>



public class AlertDialog {
    Context context;
    android.app.AlertDialog ad;
    TextView titleView;
    TextView messageView;
    LinearLayout buttonLayout;
    public AlertDialog(Context context) {
        // TODO Auto-generated constructor stub
        this.context=context;
        ad=new android.app.AlertDialog.Builder(context).create();
        ad.show();
        //关键在下面的两行,使用window.setContentView,替换整个对话框窗口的布局
        Window window = ad.getWindow();
        window.setContentView(R.layout.alertdialog);
        titleView=(TextView)window.findViewById(R.id.title);
        messageView=(TextView)window.findViewById(R.id.message);
        buttonLayout=(LinearLayout)window.findViewById(R.id.buttonLayout);
    }
    public void setTitle(int resId)
    {
        titleView.setText(resId);
    }
    public void setTitle(String title) {
        titleView.setText(title);
    }
    public void setMessage(int resId) {
        messageView.setText(resId);
    }  public void setMessage(String message)
    {
        messageView.setText(message);
    }
    /**
     * 设置按钮
     * @param text
     * @param listener
     */
    public void setPositiveButton(String text,final View.OnClickListener listener)
    {
        Button button=new Button(context);
        LinearLayout.LayoutParams params=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        button.setLayoutParams(params);
        button.setBackgroundResource(R.drawable.alertdialog_button);
        button.setText(text);
        button.setTextColor(Color.WHITE);
        button.setTextSize(20);
        button.setOnClickListener(listener);
        buttonLayout.addView(button);
    }  /**
     * 设置按钮
     * @param text
     * @param listener
     */
    public void setNegativeButton(String text,final View.OnClickListener listener)
    {
        Button button=new Button(context);
        LinearLayout.LayoutParams params=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        button.setLayoutParams(params);
        button.setBackgroundResource(R.drawable.alertdialog_button);
        button.setText(text);
        button.setTextColor(Color.WHITE);
        button.setTextSize(20);
        button.setOnClickListener(listener);
        if(buttonLayout.getChildCount()>0)
        {
            params.setMargins(20, 0, 0, 0);
            button.setLayoutParams(params);
            buttonLayout.addView(button, 1);
        }else{
            button.setLayoutParams(params);
            buttonLayout.addView(button);
        }  }
    /**
     * 关闭对话框
     */
    public void dismiss() {
        ad.dismiss();
    } }


调用方法

final AlertDialog ad=new AlertDialog(Test.this);
ad.setTitle("标题");
ad.setMessage("内容sdfsafdasf内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容");
ad.setPositiveButton("确定", new OnClickListener() { 
@Override                  
public void onClick(View v) {
    // TODO Auto-generated method stub
    ad.dismiss();
    Toast.makeText(Test.this, "被点到确定", Toast.LENGTH_LONG).show();        
}
}); 
ad.setNegativeButton("取消", new OnClickListener() { 
@Override                  
public void onClick(View v) {
// TODO Auto-generated method stub
ad.dismiss();
Toast.makeText(Test.this, "被点到取消", Toast.LENGTH_LONG).show();
}
});





转自: http://my.oschina.net/u/1036767/blog/266318?p=1

猜你喜欢

转载自forlan.iteye.com/blog/2257155