Android如何自定义dialog

package com.example.aqua.myapplicationtesthttp;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
* Created by Aqua on 2015/12/15.
*/
public class PopUpView extends Dialog {

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

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


public static class Builder {
private Context context;
private String message;
private String positiveButtonText;
private DialogInterface.OnClickListener positiveButtonClickListener;

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

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

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

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

public PopUpView create() {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// instantiate the dialog with the custom Theme
final PopUpView dialog = new PopUpView(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View layout = inflater.inflate(R.layout.popupview, null);
// ViewGroup.LayoutParams pp = new ViewGroup.LayoutParams(500,300);//使用此处修改Dialog的宽和高
ViewGroup.LayoutParams pp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.addContentView(layout, pp);
dialog.setCancelable(false);//使dialog不会消失

//修改Dialog的宽度和高度
Window window = dialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.alpha = 0.7f;
lp.width = 500;
lp.height = 300;
window.setAttributes(lp);

// set the confirm button
if (positiveButtonClickListener != null) {
((Button) layout.findViewById(R.id.btn))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
positiveButtonClickListener.onClick(dialog,
DialogInterface.BUTTON_POSITIVE);
}
});
}

// set the content message
if (message != null) {
((TextView) layout.findViewById(R.id.msg)).setText(message);
}

// dialog.setContentView(layout);切忌不需要这一句
return dialog;
}




}
}
posted on 2015-12-17 23:39  ISAN_Liu  阅读(235)  评论(0编辑  收藏  举报