项目中那些事|初探 弹出框 PopupWindows

本文详细介绍了Android中PopupWindow组件的使用方法,包括初始化设置、显示位置调整及如何响应外部触摸事件等关键技术点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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弹出菜单


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值