Android Popupwindow 拖动

声明:转载自http://blog.csdn.net/wangjinyu501/article/details/24697229

        关于View的拖动大家应该比较了解了,比如对一个控件IamgeView拖动,或者一个视图View拖动,实现方式也很容易,继承OnTouchListener接口,然后重写onTouch方法,在触屏事件进行处理即可。但是Popupwindow如何实现拖动呢,我们都知道它和普通的View不一样,因为它不是继承于View类的,但是它的实现却是和View密切相关的,因为我们都知道Android视图的显示都是由View来处理的,所以一定离不开它。从Popupwindow的实现就可以看出来,

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import com.android.internal.R;  
  2.   
  3. import android.content.Context;  
  4. import android.content.res.Resources;  
  5. import android.content.res.TypedArray;  
  6. import android.graphics.PixelFormat;  
  7. import android.graphics.Rect;  
  8. import android.graphics.drawable.Drawable;  
  9. import android.graphics.drawable.StateListDrawable;  
  10. import android.os.Build;  
  11. import android.os.IBinder;  
  12. import android.util.AttributeSet;  
  13. import android.view.Gravity;  
  14. import android.view.KeyEvent;  
  15. import android.view.MotionEvent;  
  16. import android.view.View;  
  17. import android.view.View.OnTouchListener;  
  18. import android.view.ViewGroup;  
  19. import android.view.ViewTreeObserver;  
  20. import android.view.ViewTreeObserver.OnScrollChangedListener;  
  21. import android.view.WindowManager;  
  22.   
  23. import java.lang.ref.WeakReference;  
  上面是它的导包情况,基本上不是和View相关,就是和绘图相关。因此关于Popupwindow的拖动这一块,也和View有联系。首先看一下它的API,看一看有没有和View移动、变化相关的方法,果然在最后有几个update()方法,如下:


  update()方法用来更新Popupwindow的位置和大小的,那么问题就好解决了。看代码:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.drag_and_drop_movablepopupwindow;  
  2.   
  3. import android.support.v7.app.ActionBarActivity;  
  4. import android.graphics.Color;  
  5. import android.os.Bundle;  
  6. import android.view.Gravity;  
  7. import android.view.LayoutInflater;  
  8. import android.view.Menu;  
  9. import android.view.MenuItem;  
  10. import android.view.MotionEvent;  
  11. import android.view.View;  
  12. import android.view.View.OnTouchListener;  
  13. import android.view.ViewGroup.LayoutParams;  
  14. import android.widget.Button;  
  15. import android.widget.PopupWindow;  
  16. import android.widget.TextView;  
  17.   
  18. public class MainActivity extends ActionBarActivity {  
  19.   
  20.     private Button btnOpenPopup;  
  21.   
  22.     private int mCurrentX;  
  23.     private int mCurrentY;  
  24.       
  25.     private PopupWindow mPopup;  
  26.        
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.           
  31.         setContentView(R.layout.activity_main);  
  32.         btnOpenPopup = (Button) findViewById(R.id.openpopup);  
  33.         btnOpenPopup.setOnClickListener(new Button.OnClickListener() {  
  34.   
  35.             @Override  
  36.             public void onClick(View arg0) {  
  37.                 creatPopubWindow_1();  
  38.             }  
  39.         });  
  40.     }  
  41.   
  42.     /** 
  43.      * 1 
  44.      */  
  45.     private void creatPopubWindow_1() {  
  46.         LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()  
  47.                 .getSystemService(LAYOUT_INFLATER_SERVICE);  
  48.         View popupView = layoutInflater.inflate(R.layout.popup, null);  
  49.         final PopupWindow popupWindow = new PopupWindow(popupView,  
  50.                 200200);  
  51.   
  52.         Button btnDismiss = (Button) popupView.findViewById(R.id.dismiss);  
  53.         btnDismiss.setOnClickListener(new Button.OnClickListener() {  
  54.   
  55.             @Override  
  56.             public void onClick(View v) {  
  57.                 popupWindow.dismiss();  
  58.             }  
  59.         });  
  60.   
  61.         popupWindow.showAsDropDown(btnOpenPopup, 5050);  
  62.   
  63.         popupView.setOnTouchListener(new OnTouchListener() {  
  64.             int orgX, orgY;  
  65.             int offsetX, offsetY;  
  66.   
  67.             @Override  
  68.             public boolean onTouch(View v, MotionEvent event) {  
  69.                 switch (event.getAction()) {  
  70.                 case MotionEvent.ACTION_DOWN:  
  71.                     orgX = (int) event.getX();  
  72.                     orgY = (int) event.getY();  
  73.                     break;  
  74.                 case MotionEvent.ACTION_MOVE:  
  75.                     offsetX = (int) event.getRawX() - orgX;  
  76.                     offsetY = (int) event.getRawY() - orgY;  
  77.                     popupWindow.update(offsetX, offsetY, -1, -1true);  
  78.                     break;  
  79.                 }  
  80.                 return true;  
  81.             }  
  82.         });  
  83.     }  
  84. }  

  效果如图:


  首先对Popupwindow设置触摸事件,然后在回调方法中进行计算,如果手指拖动了Popupwindow,那么就调用update()方法来更新它的位置。有些同学可能不太理解参数-1是什么意思,在上面的API中,写明的是宽和高,这里怎么变成-1了呢,看一下Popupwindow源代码就明白了。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.     * <p>Updates the position and the dimension of the popup window. Width and 
  3.     * height can be set to -1 to update location only.  Calling this function 
  4.     * also updates the window with the current popup state as 
  5.     * described for {@link #update()}.</p> 
  6.     * 
  7.     * @param x the new x location 
  8.     * @param y the new y location 
  9.     * @param width the new width, can be -1 to ignore 
  10.     * @param height the new height, can be -1 to ignore 
  11.     * @param force reposition the window even if the specified position 
  12.     *              already seems to correspond to the LayoutParams 
  13.     */  
  14.    public void update(int x, int y, int width, int height, boolean force) {  
  15.        if (width != -1) {  
  16.            mLastWidth = width;  
  17.            setWidth(width);  
  18.        }  
  19.   
  20.        if (height != -1) {  
  21.            mLastHeight = height;  
  22.            setHeight(height);  
  23.        }  
  24.   
  25.        if (!isShowing() || mContentView == null) {  
  26.            return;  
  27.        }  
  28.   
  29.        WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams();  
  30.   
  31.        boolean update = force;  
  32.   
  33.        final int finalWidth = mWidthMode < 0 ? mWidthMode : mLastWidth;  
  34.        if (width != -1 && p.width != finalWidth) {  
  35.            p.width = mLastWidth = finalWidth;  
  36.            update = true;  
  37.        }  
  38.   
  39.        final int finalHeight = mHeightMode < 0 ? mHeightMode : mLastHeight;  
  40.        if (height != -1 && p.height != finalHeight) {  
  41.            p.height = mLastHeight = finalHeight;  
  42.            update = true;  
  43.        }  
  44.   
  45.        if (p.x != x) {  
  46.            p.x = x;  
  47.            update = true;  
  48.        }  
  49.   
  50.        if (p.y != y) {  
  51.            p.y = y;  
  52.            update = true;  
  53.        }  
  54.   
  55.        final int newAnim = computeAnimationResource();  
  56.        if (newAnim != p.windowAnimations) {  
  57.            p.windowAnimations = newAnim;  
  58.            update = true;  
  59.        }  
  60.   
  61.        final int newFlags = computeFlags(p.flags);  
  62.        if (newFlags != p.flags) {  
  63.            p.flags = newFlags;  
  64.            update = true;  
  65.        }  
  66.   
  67.        if (update) {  
  68.            setLayoutDirectionFromAnchor();  
  69.            mWindowManager.updateViewLayout(mPopupView, p);  
  70.        }  
  71.    }  
  前两个if判断已经说得很清楚了,如果参数是-1的话,就不改变Popupwindow的大小了,因为我们只是移动位置,所以才这样写。那关于Popupwindow的移动最后是怎么实现的呢,可以看出就是调用WindowManager的updateViewLayout()方法,这个方法在WindowManager中并没有实现,它是ViewManager接口里面的方法,WindowManager继承了ViewManager。说到ViewManager,它里面定义的方法都很常用,看代码:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** Interface to let you add and remove child views to an Activity. To get an instance 
  2.   * of this class, call {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}. 
  3.   */  
  4. public interface ViewManager  
  5. {  
  6.     /** 
  7.      * Assign the passed LayoutParams to the passed View and add the view to the window. 
  8.      * <p>Throws {@link android.view.WindowManager.BadTokenException} for certain programming 
  9.      * errors, such as adding a second view to a window without removing the first view. 
  10.      * <p>Throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a 
  11.      * secondary {@link Display} and the specified display can't be found 
  12.      * (see {@link android.app.Presentation}). 
  13.      * @param view The view to be added to this window. 
  14.      * @param params The LayoutParams to assign to view. 
  15.      */  
  16.     public void addView(View view, ViewGroup.LayoutParams params);  
  17.     public void updateViewLayout(View view, ViewGroup.LayoutParams params);  
  18.     public void removeView(View view);  
  19. }  
  这下大家应该明了,我们经常用的addView、removeView方法就是在这里面定义的,那么谁去实现呢?就是Layout控件,比如LinearLayout、RelativeLayout等,所以我们刚才用的updateViewLayout()方法也是在xml布局文件中的layout定义好的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值