PopupWindow 使用介紹

PopupWindow 使用介紹

一、popupWindow使用時候需要注意的方法

public void setFocusable(boolean focusable) ;
​
public void setOutsideTouchable(boolean touchable);

1、setFocusable(true)的時候,會獲取屏幕焦點,這時候點擊外部彈框會消失,會攔截事件,即觸控事件不會傳入popupWindow外的控件。

2、setOutsideTouchable(touchable) 只有在setFocusable(false)的時候生效。表示外部是否可以被點擊,即事件是否可以傳入popupWindow下面的控件。

  • setOutsideTouchable(false)點擊的事件會傳入popupWindow外的控件,popupWindow不消失

  • setOutsideTouchable(true) 點擊的事件會傳入popupWindow外的控件,popupWindow消失

Notice:需要手動設置popupWindow.setWidth(value); popupWindow.setHeight(value);寬高,否則可能popupWindow不顯示。

3、setTouchListener,設置監聽事件,即可攔截事件是否下發。

private void setTouchListener( PopupWindow popupWindow){ 
   popupWindow.setTouchInterceptor(new View.OnTouchListener(){        
    @Override        
    public boolean onTouch(View v, MotionEvent event) {            
        Log.e("lammy", "envent .........." + event.getRawX());           
        Log.e("lammy", "envent .........." + event.getRawY());            
        return false;        
        }    
    });
 }

通過log發現,event.getRawX、event.getRawY()獲得的是以屏幕左上角爲座標原點的座標。這裏可以根據獲得點擊座標,和其他控件在屏幕中位置,來寫比較複雜的邏輯。

二、顯示

  1. showAtLocation

public void showAtLocation(View parent, int gravity, int x, int y) ;
  • parent:一般傳入開啓顯示的view

  • gravity: Gravity.LEFT|Gravity.TOP等一個或者多個,window裏內容的對齊方式

  • x: x座標

  • y:y座標從狀態欄下開始

2、showAsDropDown

public void showAsDropDown(View anchor, int xoff, int yoff);
​
public void showAsDropDown(View anchor);
​
public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) ;
  • anchor 一般是在哪個控件下顯示

  • xoff 相對於anchor

  • yoff 相對於anchor

  • gravity 存放控件對其方式

Notice:無論哪種顯示方式,如果設置偏移量,屏幕顯示不全, 都會更改位置,讓其顯示完整。

 

示例:

    private void initPopWindow(View view){
        PopupWindow popupWindow = new PopupWindow(this);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setWidth(500);
        popupWindow.setHeight(200);
        TextView textView = new TextView(this);
        textView.setTextColor(0xff000000);
        textView.setBackgroundColor(0xff00ff00);
        textView.setText("lammy test pop Window");
        popupWindow.setContentView(textView);
        setTouchListener(popupWindow);
        popupWindow.showAsDropDown(view, 30,0 );
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章