(原创)关于PopupWindow的showAsDropDown()和showAtLocation()使用方式及其区别
先看下demo的效果图,说明都在代码里面注释。
以下是个人编写代码:
1.MainActivity部分
package com.example.lainanzhou.popupwindoewlocation;
import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.Interpolator;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Android的对话框有两种:PopupWindow和AlertDialog。它们的不同点在于:
* •AlertDialog的位置固定,而PopupWindow的位置可以随意
* •AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的
* •PopupWindow的位置按照有无偏移分,可以分为偏移和无偏移两种;按照参照物的不同,
* 可以分为相对于某个控件(Anchor锚)和相对于父控件。具体如下
* •showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
* •showAsDropDown(View anchor,int xoff,int yoff):相对某个控件的位置,有偏移
* •showAtLocation(View parent,int gravity,int x,int y):相对于父控件的位置
* (例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移
*/
public class MainActivity extends Activity implements View.OnClickListener {
private TextView mTv;
private TextView mMainView;
private RelativeLayout mRl_parent;
private PopupWindow mPopupWindow;
private int mWidth;
private boolean mIsClick5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTv = (TextView) findViewById(R.id.tv);
mMainView = (TextView) findViewById(R.id.tv_mainView);
mRl_parent = (RelativeLayout) findViewById(R.id.rl_parent);
Button mButton01 = (Button) findViewById(R.id.button01);
Button mButton02 = (Button) findViewById(R.id.button02);
Button mButton03 = (Button) findViewById(R.id.button03);
Button mButton04 = (Button) findViewById(R.id.button04);
Button mButton05 = (Button) findViewById(R.id.button05);
mButton01.setOnClickListener(this);
mButton02.setOnClickListener(this);
mButton03.setOnClickListener(this);
mButton04.setOnClickListener(this);
mButton05.setOnClickListener(this);
}
/**
* 根据类型设置显示的popupWindow方式
*
* @param type 1.为直接显示在某控件下方+点击外部不可关闭
* 2.显示在某控件下方+点击外部可关闭
* 3.相对父容器中心显示位置+点击外部可关闭
* 4.相对父容器脚部显示位置+点击外部可关闭
* 5.默认点击外部可关闭
*/
private void initPopupWindow(int type) {
LayoutInflater layoutInflater = LayoutInflater.from(this);
View popupWindow = layoutInflater.inflat