先看效果圖
黃色的就是彈出的popup window
首先自定義一個view用來顯示,文件名為layout_my_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_tips"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="13dp"
android:textColor="#333333"
android:text="。。。"/>
</LinearLayout>
java 代碼實現
public class TipsView extends LinearLayout { public TipsView(Context context) { super(context); init(); } public TipsView(Context context, AttributeSet attrs) { super(context, attrs); init(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public TipsView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { inflate(getContext(), R.layout.layout_my_view, this); } }
調用代碼
private void showTips() { if (mTipsView == null) { mTipsView = new TipsView(this); mPopupWindow = new PopupWindow(mTipsView, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT, true); // 如果不設置PopupWindow的背景,無論是點擊外部區域還是Back鍵都無法dismiss彈框 mPopupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color .transparent)); mPopupWindow.setFocusable(true); mPopupWindow.setOutsideTouchable(true); } if (mPopupWindow.isShowing()) { return; } // 設置好參數之后再show int local[] = new int[2]; //彈出控件的位置,坐標存在local數組 mTvBindFlag.getLocationOnScreen(local); int width = mTipsView.getWidth(); int height = mTipsView.getHeight(); if (width == 0 || height == 0) { // 獲取測量后的寬度 int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); mTipsView.measure(w, h); width = mTipsView.getMeasuredWidth(); height = mTipsView.getMeasuredHeight(); } // x坐標計算方式:complete_count_txt的x坐標加上他的長度一半(相當於complete_count_txt的橫向居中位置) // ,再減少彈出氣泡寬度的一半(相當於向左移動氣泡一半的寬度,就居中顯示在complete_count_txt了) int x = local[0] + (mTvBindFlag.getWidth() / 2) - width / 2; // y坐標計算方式:complete_count_txt的y坐標減去氣泡的高度 int y = local[1] - height; // 通過絕對位置顯示 @param parent a parent view to get the {@link android.view.View#getWindowToken()} token from * @param gravity the gravity which controls the placement of the popup window * @param x the popup's x location offset * @param y the popup's y location offset */ // public void showAtLocation(View parent, int gravity, int x, int y) mPopupWindow.showAtLocation(mTvBindFlag, Gravity.NO_GRAVITY, x, y); }