在实际开始种,每个android应用或多或少都会有一些dialog的弹窗,系统自带v7的还能看,v4就实在看不下去了,太他妈丑了。有些开发者闲麻烦,只能自己写一个layout实现,但是这样又不麻烦吗?要是有一个library用下,是不是就觉得舒服多了,随时随用。没错,今天我就是给大家带来这样的福利,分享两个效果不错的dialog项目,注释我都写上了,主要代码在这里贴出来看下,demo在最后会附上。
demo效果:
NitifyDialog:
AlertViewDialog:
是不是有你想要的效果?哈哈,
我们先看下NitifyDialog 的MainActivity,先看下到底怎么用,自定义类里面有什么东西。
MainActivity代码如下:
package com.gitonway.lee.niftymodaldialogeffects;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;
public class MainActivity extends Activity {
private Effectstype effect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 点击事件
* @param v
*/
public void dialogShow(View v) {
final NiftyDialogBuilder dialogBuilder = NiftyDialogBuilder.getInstance(this);
switch (v.getId()) {
//根据每个窗口的类型展现不同的dialog 效果
case R.id.fadein:
effect = Effectstype.Fadein;
break;
case R.id.slideright:
effect = Effectstype.Slideright;
break;
case R.id.slideleft:
effect = Effectstype.Slideleft;
break;
case R.id.slidetop:
effect = Effectstype.Slidetop;
break;
case R.id.slideBottom:
effect = Effectstype.SlideBottom;
break;
case R.id.newspager:
effect = Effectstype.Newspager;
break;
case R.id.fall:
effect = Effectstype.Fall;
break;
case R.id.sidefall:
effect = Effectstype.Sidefill;
break;
case R.id.fliph:
effect = Effectstype.Fliph;
break;
case R.id.flipv:
effect = Effectstype.Flipv;
break;
case R.id.rotatebottom:
effect = Effectstype.RotateBottom;
break;
case R.id.rotateleft:
effect = Effectstype.RotateLeft;
break;
case R.id.slit:
effect = Effectstype.Slit;
break;
case R.id.shake:
effect = Effectstype.Shake;
break;
}
/**
* 设置dialog样式
*/
dialogBuilder
.withTitle("弹窗样式") //窗口标题
.withTitleColor("#FFFFFF") //窗口字体颜色
.withDividerColor("#11000000") //线条颜色
.withMessage("这是小窗口内容") //内容
.withMessageColor("#FFFFFFFF") //里面内容的字体颜色
.withDialogColor("#A5CD4E") //窗口颜色
.withIcon(getResources().getDrawable(R.drawable.ic_launcher)) //窗口的icon(直接用withIcon(R.drawable.ic_launcher会出现异常))
.isCancelableOnTouchOutside(true) //是否可点击窗口外边取消窗口
.withDuration(500) //动画速度
.withEffect(effect) //窗口类型
.withButton1Text("确定") //两个button按钮
.withButton2Text("取消")
.setCustomView(R.layout.custom_view, v.getContext()) //窗口内容下面的layout
.setButton1Click(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "确定", Toast.LENGTH_SHORT).show();
dialogBuilder.dismiss();
}
})
.setButton2Click(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "取消", Toast.LENGTH_SHORT).show();
dialogBuilder.dismiss();
}
})
.show();
}
}
我都写上注释了。
看下自定义的dialog,NiftyDialogBuilder类,代码如下:
package com.gitonway.lee.niftymodaldialogeffects.lib;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gitonway.lee.niftymodaldialogeffects.lib.effects.BaseEffects;
/**
* 自定义dialog
*/
public class NiftyDialogBuilder extends Dialog implements DialogInterface {
private final String defTextColor = "#FFFFFFFF";//字体颜色
private final String defDividerColor = "#11000000";//线条颜色
private final String defMsgColor = "#FFFFFFFF";//内容字体颜色
private final String defDialogColor = "#FFE74C3C";//dialog的背景色
private static Context tmpContext;//上下文
private Effectstype type = null;//各个窗口的类型
private LinearLayout mLinearLayoutView;
private RelativeLayout mRelativeLayoutView;
private LinearLayout mLinearLayoutMsgView;
private LinearLayout mLinearLayoutTopView;
private FrameLayout mFrameLayoutCustomView;
private View mDialogView;
private View mDivider;
private TextView mTitle;
private TextView mMessage;
private ImageView mIcon;
private Button mButton1;//两个按钮
private Button mButton2;
private int mDuration = -1;
private static int mOrientation = 1;
private boolean isCancelable = true;//是否可取消
private static NiftyDialogBuilder instance;
public NiftyDialogBuilder(Context context) {
super(context);
init(context);
}
/**
* 构造器
* @param context
* @param theme
*/
public NiftyDialogBuilder(Context context, int theme) {
super(context, theme);
init(context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager.LayoutParams params = getWindow().getAttributes();//获取屏幕的宽高并设置
params.height = ViewGroup.LayoutParams.MATCH_PARENT;
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
}
public static NiftyDialogBuilder getInstance(Context context) {//单例
if (instance == null || !tmpContext.equals(context)) {
synchronized (NiftyDialogBuilder.class) {
if (instance == null || !tmpContext.equals(context)) {
instance = new NiftyDialogBuilder(context, R.style.dialog_untran);
}
}
}
tmpContext = context;
return instance;
}
/**
* 初始化控件
* @param context
*/
private void init(Context context) {
mDialogView = View.inflate(context, R.layout.dialog_layout, null);
mLinearLayoutView = (LinearLayout) mDialogView.findViewById(R.id.parentPanel);
mRelativeLayoutView = (RelativeLayout) mDialogView.findViewById(R.id.main);
mLinearLayoutTopView = (LinearLayout) mDialogView.findViewById(R.id.topPanel);
mLinearLayoutMsgView = (LinearLayout) mDialogView.findViewById(R.id.contentPanel);
mFrameLayoutCustomView = (FrameLayout) mDialogView.findViewById(R.id.customPanel);
mTitle = (TextView) mDialogView.findViewById(R.id.alertTitle);
mMessage = (TextView) mDialogView.findViewById(R.id.message);
mIcon = (ImageView) mDialogView.findViewById(R.id.icon);
mDivider = mDialogView.findViewById(R.id.titleDivider);
mButton1 = (Button) mDialogView.findViewById(R.id.button1);
mButton2 = (Button) mDialogView.findViewById(R.id.button2);
setContentView(mDialogView);
this.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
mLinearLayoutView.setVisibility(View.VISIBLE);
if (type == null) {
type = Effectstype.Slidetop;
}
start(type);
}
});
mRelativeLayoutView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isCancelable) dismiss();
}
});
}
/**
* 设置控件
*/
public void toDefault() {
mTitle.setTextColor(Color.parseColor(defTextColor));
mDivider.setBackgroundColor(Color.parseColor(defDividerColor));
mMessage.setTextColor(Color.parseColor(defMsgColor));
mLinearLayoutView.setBackgroundColor(Color.parseColor(defDialogColor));
}
/**
* 设置间隔线条的颜色 参数类型为字符串
* @param colorString
* @return
*/
public NiftyDialogBuilder withDividerColor(String colorString) {
mDivider.setBackgroundColor(Color.parseColor(colorString));
return this;
}
/**
* 设置间隔线条颜色,参数类型是int
* @param color
* @return
*/
public NiftyDialogBuilder withDividerColor(int color) {
mDivider.setBackgroundColor(color);
return this;
}
/**
* 设置title字体
* @param title
* @return
*/
public NiftyDialogBuilder withTitle(CharSequence title) {
toggleView(mLinearLayoutTopView, title);
mTitle.setText(title);
return this;
}
/**
* 设置title的字体颜色 String类型
* @param colorString
* @return
*/
public NiftyDialogBuilder withTitleColor(String colorString) {
mTitle.setTextColor(Color.parseColor(colorString));
return this;
}
/**
* 设置title的字体颜色 int类型
* @param color
* @return
*/
public NiftyDialogBuilder withTitleColor(int color) {
mTitle.setTextColor(color);
return this;
}
/**
* 设置内容字体 int 类型(配置在string.xml中的)
* @param textResId
* @return
*/
public NiftyDialogBuilder withMessage(int textResId) {
toggleView(mLinearLayoutMsgView, textResId);
mMessage.setText(textResId);
return this;
}
/**
* 设置内容字体 CharSequence类型
* @param msg
* @return
*/
public NiftyDialogBuilder withMessage(CharSequence msg) {
toggleView(mLinearLayoutMsgView, msg);
mMessage.setText(msg);
return this;
}
/**
* 内容字体颜色 string
* @param colorString
* @return
*/
public NiftyDialogBuilder withMessageColor(String colorString) {
mMessage.setTextColor(Color.parseColor(colorString));
return this;
}
/**
* 内容字体颜色 int
* @param color
* @return
*/
public NiftyDialogBuilder withMessageColor(int color) {
mMessage.setTextColor(color);
return this;
}
/**
* 设置dialog的背景颜色 string
* @param colorString
* @return
*/
public NiftyDialogBuilder withDialogColor(String colorString) {
mLinearLayoutView.getBackground().setColorFilter(ColorUtils.getColorFilter(Color
.parseColor(colorString)));
return this;
}
/**
* 设置dialog的背景颜色 int
* @param color
* @return
*/
public NiftyDialogBuilder withDialogColor(int color) {
mLinearLayoutView.getBackground().setColorFilter(ColorUtils.getColorFilter(color));
return this;
}
/**
* 设置dialog的icon
* @param drawableResId
* @return
*/
public NiftyDialogBuilder withIcon(int drawableResId) {
mIcon.setImageResource(drawableResId);
return this;
}
/**
* 设置dialog的icon
* @param icon
* @return
*/
public NiftyDialogBuilder withIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
return this;
}
/**
* 设置dialog出现的速度
* @param duration
* @return
*/
public NiftyDialogBuilder withDuration(int duration) {
this.mDuration = duration;
return this;
}
public NiftyDialogBuilder withEffect(Effectstype type) {
this.type = type;
return this;
}
/**
* 设置button的背景
* @param resid
* @return
*/
public NiftyDialogBuilder withButtonDrawable(int resid) {
mButton1.setBackgroundResource(resid);
mButton2.setBackgroundResource(resid);
return this;
}
/**
* 设置button的字体
* @param text
* @return
*/
public NiftyDialogBuilder withButton1Text(CharSequence text) {
mButton1.setVisibility(View.VISIBLE);
mButton1.setText(text);
return this;
}
public NiftyDialogBuilder withButton2Text(CharSequence text) {
mButton2.setVisibility(View.VISIBLE);
mButton2.setText(text);
return this;
}
/**
* 给button添加点击
* @param click
* @return
*/
public NiftyDialogBuilder setButton1Click(View.OnClickListener click) {
mButton1.setOnClickListener(click);
return this;
}
public NiftyDialogBuilder setButton2Click(View.OnClickListener click) {
mButton2.setOnClickListener(click);
return this;
}
/**
* 添加自定义的layout
* @param resId
* @param context
* @return
*/
public NiftyDialogBuilder setCustomView(int resId, Context context) {
View customView = View.inflate(context, resId, null);
if (mFrameLayoutCustomView.getChildCount() > 0) {
mFrameLayoutCustomView.removeAllViews();
}
mFrameLayoutCustomView.addView(customView);
mFrameLayoutCustomView.setVisibility(View.VISIBLE);
return this;
}
public NiftyDialogBuilder setCustomView(View view, Context context) {
if (mFrameLayoutCustomView.getChildCount() > 0) {
mFrameLayoutCustomView.removeAllViews();
}
mFrameLayoutCustomView.addView(view);
mFrameLayoutCustomView.setVisibility(View.VISIBLE);
return this;
}
/**
* 设置dialog点击外边界是否可取消
* @param cancelable
* @return
*/
public NiftyDialogBuilder isCancelableOnTouchOutside(boolean cancelable) {
this.isCancelable = cancelable;
this.setCanceledOnTouchOutside(cancelable);
return this;
}
/**
* 设置dialog是否可取消
* @param cancelable
* @return
*/
public NiftyDialogBuilder isCancelable(boolean cancelable) {
this.isCancelable = cancelable;
this.setCancelable(cancelable);
return this;
}
/**
* 设置view隐藏
* @param view
* @param obj
*/
private void toggleView(View view, Object obj) {
if (obj == null) {
view.setVisibility(View.GONE);
} else {
view.setVisibility(View.VISIBLE);
}
}
/**
* 显示
*/
@Override
public void show() {
super.show();
}
/**
* 动画开始
* @param type
*/
private void start(Effectstype type) {
BaseEffects animator = type.getAnimator();
if (mDuration != -1) {
animator.setDuration(Math.abs(mDuration));
}
animator.start(mRelativeLayoutView);
}
/**
* 消灭dialog
*/
@Override
public void dismiss() {
super.dismiss();
mButton1.setVisibility(View.GONE);
mButton2.setVisibility(View.GONE);
}
}
其实也很简单,设置dialog 我们想要的样式。
第一个demo先介绍这里,下面看下第二个demo,效果图上面也有了,这个不是dialog,而是一个自定义的view,很适合初学者学习自定义view。
先看MainActivity,如下:
package com.bigkoo.alertviewdemo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
/**
* 精仿iOS AlertViewController控件Demo
*/
public class MainActivity extends Activity implements OnItemClickListener, OnDismissListener {
private AlertView mAlertView;//避免创建重复View,先创建View,然后需要的时候show出来,推荐这个做法
private AlertView mAlertViewExt;//窗口拓展例子
private EditText etName;//拓展View内容
private InputMethodManager imm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mAlertView = new AlertView("标题", "内容", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this).setCancelable(true).setOnDismissListener(this);
//拓展窗口
mAlertViewExt = new AlertView("提示", "请完善你的个人资料!", "取消", null, new String[]{"完成"}, this, AlertView.Style.Alert, this);
ViewGroup extView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.alertext_form, null);
etName = (EditText) extView.findViewById(R.id.etName);
etName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean focus) {
//输入框出来则往上移动
boolean isOpen = imm.isActive();
mAlertViewExt.setMarginBottom(isOpen && focus ? 120 : 0);
System.out.println(isOpen);
}
});
mAlertViewExt.addExtView(extView);
}
public void alertShow1(View view) {
mAlertView.show();
}
public void alertShow2(View view) {
new AlertView("标题", "内容", null, new String[]{"确定"}, null, this, AlertView.Style.Alert, this).show();
}
public void alertShow3(View view) {
new AlertView(null, null, null, new String[]{"高亮按钮1", "高亮按钮2", "高亮按钮3"},
new String[]{"其他按钮1", "其他按钮2", "其他按钮3", "其他按钮4", "其他按钮5", "其他按钮6",
"其他按钮7", "其他按钮8", "其他按钮9", "其他按钮10", "其他按钮11", "其他按钮12"},
this, AlertView.Style.Alert, this).show();
}
public void alertShow4(View view) {
new AlertView("标题", null, "取消", new String[]{"高亮按钮1"}, new String[]{"其他按钮1", "其他按钮2", "其他按钮3"}, this, AlertView.Style.ActionSheet, this).show();
}
public void alertShow5(View view) {
new AlertView("标题", "内容", "取消", null, null, this, AlertView.Style.ActionSheet, this).setCancelable(true).show();
}
public void alertShow6(View view) {
new AlertView("上传头像", null, "取消", null,
new String[]{"拍照", "从相册中选择"},
this, AlertView.Style.ActionSheet, this).show();
}
public void alertShowExt(View view) {
mAlertViewExt.show();
}
private void closeKeyboard() {
//关闭软键盘
imm.hideSoftInputFromWindow(etName.getWindowToken(), 0);
//恢复位置
mAlertViewExt.setMarginBottom(0);
}
@Override
public void onItemClick(Object o, int position) {
closeKeyboard();
//判断是否是拓展窗口View,而且点击的是非取消按钮
if (o == mAlertViewExt && position != AlertView.CANCELPOSITION) {
String name = etName.getText().toString();
if (name.isEmpty()) {
Toast.makeText(this, "啥都没填呢", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "hello," + name, Toast.LENGTH_SHORT).show();
}
return;
}
Toast.makeText(this, "点击了第" + position + "个", Toast.LENGTH_SHORT).show();
}
@Override
public void onDismiss(Object o) {
closeKeyboard();
Toast.makeText(this, "消失了", Toast.LENGTH_SHORT).show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if (mAlertView != null && mAlertView.isShowing()) {
mAlertView.dismiss();
return false;
}
}
return super.onKeyDown(keyCode, event);
}
}
代码看上去比较凌乱,但是简单明了,注释都写上了。
AlertView类是自定义View,代码比较长,有注释,大家稍微耐心点看完。
package com.bigkoo.alertview;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 精仿iOS AlertViewController控件
* 点击取消按钮返回 -1,其他按钮从0开始算
*/
public class AlertView {
public static enum Style{
ActionSheet,
Alert
}
private final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM
);
public static final int HORIZONTAL_BUTTONS_MAXCOUNT = 2;
public static final String OTHERS = "others";
public static final String DESTRUCTIVE = "destructive";
public static final String CANCEL = "cancel";
public static final String TITLE = "title";
public static final String MSG = "msg";
public static final int CANCELPOSITION = -1;//点击取消按钮返回 -1,其他按钮从0开始算
private String title;//标题title
private String msg; //内容
private List mDestructive;
private List mOthers;
private String cancel;
private ArrayList mDatas = new ArrayList();
private Context context;
private ViewGroup contentContainer;
private ViewGroup decorView;//activity的根View
private ViewGroup rootView;//AlertView 的 根View
private ViewGroup loAlertHeader;//窗口headerView
private Style style = Style.Alert;
private OnDismissListener onDismissListener;
private OnItemClickListener onItemClickListener;
private boolean isDismissing;
private Animation outAnim; //淡入淡出效果
private Animation inAnim;
private int gravity = Gravity.CENTER;
/**
* 一个view的样式及事件处理
* @param title
* @param msg
* @param cancel
* @param destructive
* @param others
* @param context
* @param style
* @param onItemClickListener
*/
public AlertView(String title, String msg, String cancel, String[] destructive, String[] others, Context context, Style style,OnItemClickListener onItemClickListener){
this.context = context;
if(style != null)this.style = style;
this.onItemClickListener = onItemClickListener;
initData(title, msg, cancel, destructive, others);//初始化数据
initViews();//初始化控件及样式
init();//动画
initEvents();//添加view
}
/**
* 获取数据
*/
protected void initData(String title, String msg, String cancel, String[] destructive, String[] others) {
this.title = title;
this.msg = msg;
if (destructive != null){
this.mDestructive = Arrays.asList(destructive);
this.mDatas.addAll(mDestructive);
}
if (others != null){
this.mOthers = Arrays.asList(others);
this.mDatas.addAll(mOthers);
}
if (cancel != null){
this.cancel = cancel;
if(style == Style.Alert && mDatas.size() < HORIZONTAL_BUTTONS_MAXCOUNT){
this.mDatas.add(0,cancel);
}
}
}
/**
* 初始化控件及样式处理
*/
protected void initViews(){
LayoutInflater layoutInflater = LayoutInflater.from(context);
decorView = (ViewGroup) ((Activity)context).getWindow().getDecorView().findViewById(android.R.id.content);
rootView = (ViewGroup) layoutInflater.inflate(R.layout.layout_alertview, decorView, false);
rootView.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
));
contentContainer = (ViewGroup) rootView.findViewById(R.id.content_container);
int margin_alert_left_right = 0;
switch (style){
case ActionSheet:
params.gravity = Gravity.BOTTOM;
margin_alert_left_right = context.getResources().getDimensionPixelSize(R.dimen.margin_actionsheet_left_right);
params.setMargins(margin_alert_left_right,0,margin_alert_left_right,margin_alert_left_right);
contentContainer.setLayoutParams(params);
gravity = Gravity.BOTTOM;
initActionSheetViews(layoutInflater);
break;
case Alert:
params.gravity = Gravity.CENTER;
margin_alert_left_right = context.getResources().getDimensionPixelSize(R.dimen.margin_alert_left_right);
params.setMargins(margin_alert_left_right,0,margin_alert_left_right,0);
contentContainer.setLayoutParams(params);
gravity = Gravity.CENTER;
initAlertViews(layoutInflater);
break;
}
}
/**
* 头部的title及message
* @param viewGroup
*/
protected void initHeaderView(ViewGroup viewGroup){
loAlertHeader = (ViewGroup) viewGroup.findViewById(R.id.loAlertHeader);
//标题和消息
TextView tvAlertTitle = (TextView) viewGroup.findViewById(R.id.tvAlertTitle);
TextView tvAlertMsg = (TextView) viewGroup.findViewById(R.id.tvAlertMsg);
if(title != null) {
tvAlertTitle.setText(title);
}else{
tvAlertTitle.setVisibility(View.GONE);
}
if(msg != null) {
tvAlertMsg.setText(msg);
}else{
tvAlertMsg.setVisibility(View.GONE);
}
}
/**
* 底部的取消及list列表
*/
protected void initListView(){
ListView alertButtonListView = (ListView) contentContainer.findViewById(R.id.alertButtonListView);
//把cancel作为footerView
if(cancel != null && style == Style.Alert){
View itemView = LayoutInflater.from(context).inflate(R.layout.item_alertbutton, null);
TextView tvAlert = (TextView) itemView.findViewById(R.id.tvAlert);
tvAlert.setText(cancel);
tvAlert.setClickable(true);
tvAlert.setTypeface(Typeface.DEFAULT_BOLD);
tvAlert.setTextColor(context.getResources().getColor(R.color.textColor_alert_button_cancel));
tvAlert.setBackgroundResource(R.drawable.bg_alertbutton_bottom);
tvAlert.setOnClickListener(new OnTextClickListener(CANCELPOSITION));
alertButtonListView.addFooterView(itemView);
}
AlertViewAdapter adapter = new AlertViewAdapter(mDatas,mDestructive);
alertButtonListView.setAdapter(adapter);
alertButtonListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> adapterView, View view, int position, long l) {
if(onItemClickListener != null)onItemClickListener.onItemClick(AlertView.this,position);
dismiss();
}
});
}
protected void initActionSheetViews(LayoutInflater layoutInflater) {
ViewGroup viewGroup = (ViewGroup) layoutInflater.inflate(R.layout.layout_alertview_actionsheet,contentContainer);
initHeaderView(viewGroup);
initListView();
TextView tvAlertCancel = (TextView) contentContainer.findViewById(R.id.tvAlertCancel);
if(cancel != null){
tvAlertCancel.setVisibility(View.VISIBLE);
tvAlertCancel.setText(cancel);
}
tvAlertCancel.setOnClickListener(new OnTextClickListener(CANCELPOSITION));
}
/**
* item的样式
* @param layoutInflater
*/
protected void initAlertViews(LayoutInflater layoutInflater) {
ViewGroup viewGroup = (ViewGroup) layoutInflater.inflate(R.layout.layout_alertview_alert, contentContainer);
initHeaderView(viewGroup);
int position = 0;
//如果总数据小于等于HORIZONTAL_BUTTONS_MAXCOUNT,则是横向button
if(mDatas.size()<=HORIZONTAL_BUTTONS_MAXCOUNT){
ViewStub viewStub = (ViewStub) contentContainer.findViewById(R.id.viewStubHorizontal);
viewStub.inflate();
LinearLayout loAlertButtons = (LinearLayout) contentContainer.findViewById(R.id.loAlertButtons);
for (int i = 0; i < mDatas.size(); i ++) {
//如果不是第一个按钮
if (i != 0){
//添加上按钮之间的分割线
View divier = new View(context);
divier.setBackgroundColor(context.getResources().getColor(R.color.bgColor_divier));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int)context.getResources().getDimension(R.dimen.size_divier), LinearLayout.LayoutParams.MATCH_PARENT);
loAlertButtons.addView(divier,params);
}
View itemView = LayoutInflater.from(context).inflate(R.layout.item_alertbutton, null);
TextView tvAlert = (TextView) itemView.findViewById(R.id.tvAlert);
tvAlert.setClickable(true);
//设置点击效果
if(mDatas.size() == 1){
tvAlert.setBackgroundResource(R.drawable.bg_alertbutton_bottom);
}
else if(i == 0){//设置最左边的按钮效果
tvAlert.setBackgroundResource(R.drawable.bg_alertbutton_left);
}
else if(i == mDatas.size() - 1){//设置最右边的按钮效果
tvAlert.setBackgroundResource(R.drawable.bg_alertbutton_right);
}
String data = mDatas.get(i);
tvAlert.setText(data);
//取消按钮的样式
if (data == cancel){
tvAlert.setTypeface(Typeface.DEFAULT_BOLD);
tvAlert.setTextColor(context.getResources().getColor(R.color.textColor_alert_button_cancel));
tvAlert.setOnClickListener(new OnTextClickListener(CANCELPOSITION));
position = position - 1;
}
//高亮按钮的样式
else if (mDestructive!= null && mDestructive.contains(data)){
tvAlert.setTextColor(context.getResources().getColor(R.color.textColor_alert_button_destructive));
}
tvAlert.setOnClickListener(new OnTextClickListener(position));
position++;
loAlertButtons.addView(itemView,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT, 1));
}
}
else{
ViewStub viewStub = (ViewStub) contentContainer.findViewById(R.id.viewStubVertical);
viewStub.inflate();
initListView();
}
}
/**
* 初始化动画
*/
protected void init() {
inAnim = getInAnimation();
outAnim = getOutAnimation();
}
protected void initEvents() {
}
/**
* 添加view
* @param extView
* @return
*/
public AlertView addExtView(View extView){
loAlertHeader.addView(extView);
return this;
}
/**
* show的时候调用
*
* @param view 这个View
*/
private void onAttached(View view) {
decorView.addView(view);
contentContainer.startAnimation(inAnim);
}
/**
* 添加这个View到Activity的根视图
*/
public void show() {
if (isShowing()) {
return;
}
onAttached(rootView);
}
/**
* 检测该View是不是已经添加到根视图
*
* @return 如果视图已经存在该View返回true
*/
public boolean isShowing() {
View view = decorView.findViewById(R.id.outmost_container);
return view != null;
}
public void dismiss() {
if (isDismissing) {
return;
}
//消失动画
outAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
decorView.post(new Runnable() {
@Override
public void run() {
//从activity根视图移除
decorView.removeView(rootView);
isDismissing = false;
if (onDismissListener != null) {
onDismissListener.onDismiss(AlertView.this);
}
}
});
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
contentContainer.startAnimation(outAnim);
isDismissing = true;
}
public Animation getInAnimation() {
int res = AlertAnimateUtil.getAnimationResource(this.gravity, true);
return AnimationUtils.loadAnimation(context, res);
}
public Animation getOutAnimation() {
int res = AlertAnimateUtil.getAnimationResource(this.gravity, false);
return AnimationUtils.loadAnimation(context, res);
}
public AlertView setOnDismissListener(OnDismissListener onDismissListener) {
this.onDismissListener = onDismissListener;
return this;
}
class OnTextClickListener implements View.OnClickListener{
private int position;
public OnTextClickListener(int position){
this.position = position;
}
@Override
public void onClick(View view) {
if(onItemClickListener != null)onItemClickListener.onItemClick(AlertView.this,position);
dismiss();
}
}
/**
* 主要用于拓展View的时候有输入框,键盘弹出则设置MarginBottom往上顶,避免输入法挡住界面
*/
public void setMarginBottom(int marginBottom){
int margin_alert_left_right = context.getResources().getDimensionPixelSize(R.dimen.margin_alert_left_right);
params.setMargins(margin_alert_left_right,0,margin_alert_left_right,marginBottom);
contentContainer.setLayoutParams(params);
}
public AlertView setCancelable(boolean isCancelable) {
View view = rootView.findViewById(R.id.outmost_container);
if (isCancelable) {
view.setOnTouchListener(onCancelableTouchListener);
}
else{
view.setOnTouchListener(null);
}
return this;
}
/**
* Called when the user touch on black overlay in order to dismiss the dialog
*/
private final View.OnTouchListener onCancelableTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
dismiss();
}
return false;
}
};
}
主要代码就上述这些,下面贴出下载地址: