Android的对话框有两种:PopupWindow和AlertDialog。他们都可以自定义view,而不同相对于位置固定的AlertDialog,PopupWindow的位置可以随意。且AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的。个人认为PopupWindow使用会更加灵活方便。废话就不多说了,下面具体根据代码来讲解一下:
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;
/**
*
* @description
* TODO
* @author zs
* @version 1.0
*/
public class QuetsDetailView extends PopupWindow{
private static final String TAG = "QuetsDetailView";
private Context mContext;
private LayoutInflater inflater;
private View showView;//依附控件
private View view;
public QuetsDetailView(Context context,View v){
LogUtil.d(TAG, "【初始化...】");
this.mContext = context;
this.showView = v;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
init();
}
/**
* 初始化
*/
private void init(){
view = inflater.inflate(R.layout.popup_question_detail_layout, null);
this.update();
// this.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
// this.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
/**
* 这里要指定具体值,要不在下面指定控件位置之上时无效,具体原因不知道,
请知道的回复我,谢谢
*
*/
this.setWidth(750);
this.setHeight(500);
//自定义布局
this.setContentView(view);
this.setFocusable(true);
this.setTouchable(true);
/**
* 使点击 PopupWindow 之外,能使之消失。
* 这里要注意的是:1.setTouchable(true) 2.this.setBackgroundDrawable(cd)
是必须的,反之,无效果
*
*/
this.setOutsideTouchable(true);
ColorDrawable cd = new ColorDrawable(Color.TRANSPARENT);
this.setBackgroundDrawable(cd);
}
/**
* 在指定控件之上显示
* 下方显示 :this.showAsDropDown(view);
* 左方方显示 :this.showAtLocation(view, Gravity.NO_GRAVITY,
location[0]-popupWindow.getWidth(), location[1]);
* 右方方显示 :this.showAtLocation(view, Gravity.NO_GRAVITY,
location[0]+v.getWidth(), location[1]);
*/
public void showWindow(){
if(!isShowing()){
int[] location = new int[2];
showView.getLocationOnScreen(location);
int offsetY = location[1] - this.getHeight();
int offsetX = location[0];
this.showAtLocation(showView, Gravity.NO_GRAVITY, offsetX, offsetY);
}
}
/**
* 隐藏popup
*/
public void cancleWindow(){
if(isShowing()){
this.dismiss();
}
}
}
关于点击popupwindow以外区域 popupwindow自动消失问题
android自定义menu,PopUpWindow弹出菜单