Friday, January 24, 2014

Implement drag-and-drop movable PopupWindow

This example implement OnTouchListener() for PopupWindow to detect user action of drag-and-drop, to move PopupWindow.

movable PopupWindow
Movable PopupWindow

package com.example.androidpopupwindow;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Spinner;

public class MainActivity extends Activity {
 String[] DayOfWeek = {"Sunday", "Monday", "Tuesday", 
   "Wednesday", "Thursday", "Friday", "Saturday"};

 protected void onCreate(Bundle savedInstanceState) {

  final Button btnOpenPopup = (Button) findViewById(;
  btnOpenPopup.setOnClickListener(new Button.OnClickListener() {

   public void onClick(View arg0) {
    LayoutInflater layoutInflater = 
    View popupView = layoutInflater.inflate(R.layout.popup, null);
    final PopupWindow popupWindow = new PopupWindow(
      popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    Button btnDismiss = (Button)popupView.findViewById(;
    Spinner popupSpinner = (Spinner)popupView.findViewById(;
    ArrayAdapter<String> adapter = 
      new ArrayAdapter<String>(MainActivity.this, 
        android.R.layout.simple_spinner_item, DayOfWeek);
    btnDismiss.setOnClickListener(new Button.OnClickListener(){

     public void onClick(View v) {
    popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
    popupView.setOnTouchListener(new OnTouchListener() {
     int orgX, orgY;
     int offsetX, offsetY;

     public boolean onTouch(View v, MotionEvent event) {
      switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
       orgX = (int) event.getX();
       orgY = (int) event.getY();
      case MotionEvent.ACTION_MOVE:
       offsetX = (int)event.getRawX() - orgX;
       offsetY = (int)event.getRawY() - orgY;
       popupWindow.update(offsetX, offsetY, -1, -1, true);
      return true;



For other files, such as layout, customborder.xml...etc, refer to last exercise "PopupWindow with transparent background" and "Create background of Popup Window with custom shape".

download filesDownload the files.

Related: Interactive resizable PopupWindow


Unknown said...

Thanks a lot, this is exactly what I needed, it really really helps !!
I tried first with Dialogs, but had some problems, your solution is better.
So thanks again !

Unknown said...

there is this type of widget like activity that stays on top of all other apps and activities in some android aapps like 360 mobile security, is it also a popup window???

Unknown said...

Good tutorial,just out of curiosity,how about the spinner + imageview ?