logo logo

How to Create QuickAction Dialog in Android

Home » Information Technology » Programming » Android » How to Create QuickAction Dialog in Android




[Update 15/07/2011]

I have updated the quickaction implementation code so it can be used more efficient and the dialog will be automatically dismissed after pressing the action item. All the source codes now available via github so you can track the changes.

Official Twitter application for Android  has introduced new Android UI features and behavior patterns such as Dashboard, Search Bar, QuickAction and Action Bar. One of the interesting pattern is QuickActions that displays contextual actions in a list view. This pattern actually already exists in QuickContact dialog/bar in default Contact application (since Android 2.0).

QuickContact QuickContact

The QuickActions dialog is not included in standard Android SDK, so we have to create it manually. At first, i had no idea on how to create it so i decided to download and read the Contact app source code from  Android git. I found that the QuickContact dialog  uses private API call (com.android.internal.policy.PolicyManager) that does not exists in standard SDK. After posting question about it on google groups and stack overflow, i got the solution for it from Qberticus (thanx Qberticus!).

Qberticus’s QuickActions uses simple/plain layout so i have to create a custom layout so it will look like QuickContact in Contact app or QuickActions in Twitter app. Based on QuickContact source code, i made a slight modification on Qberticus’s BetterPopupWindow class and extended it to implement custom layout. I also made it customizeable, so the icon and text in action list can be customized.

Here are the screenshoots of QuickActions demo:

QuickContact / Twitter-like QuickActions

Code snippet
Create action items

//Add action item
ActionItem addAction = new ActionItem();

addAction.setTitle("Add");
addAction.setIcon(getResources().getDrawable(R.drawable.ic_add));

//Accept action item
ActionItem accAction = new ActionItem();

accAction.setTitle("Accept");
accAction.setIcon(getResources().getDrawable(R.drawable.ic_accept));

//Upload action item
ActionItem upAction = new ActionItem();

upAction.setTitle("Upload");
upAction.setIcon(getResources().getDrawable(R.drawable.ic_up));

Line 02: Create new action item
Line 04: Set action title
Line 05: Set action icon

Create quickaction instance and setup listener

final QuickAction mQuickAction 	= new QuickAction(this);

mQuickAction.addActionItem(addAction);
mQuickAction.addActionItem(accAction);
mQuickAction.addActionItem(upAction);

//setup the action item click listener
mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
	@Override
        public void onItemClick(int pos) {
		if (pos == 0) { //Add item selected
		   Toast.makeText(Example1Activity.this, "Add item selected", Toast.LENGTH_SHORT).show();
		} else if (pos == 1) { //Accept item selected
		   Toast.makeText(Example1Activity.this, "Accept item selected", Toast.LENGTH_SHORT).show();
		} else if (pos == 2) { //Upload item selected
		   Toast.makeText(Example1Activity.this, "Upload items selected", Toast.LENGTH_SHORT).show();
		}
	}
});

Line 1: Create quickaction instance
Line 3-5: Add the action items into quikaction
Line 8: Setup listener for action item clicked, the pos argument on onItemClick method shows which action item is clicked.

Show quickAction dialog

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
	mQuickAction.show(v);
}
});

Line 04: Show quickaction dialog, the v argument used as the anchor where the quickaction displayed.

Gallery3D-like QuickActions

Implementation on My Application

BlitzDroid

Minapolitan (Prototype)

Buy me a coffee

If you found this stuff useful to your work, please consider a donation.
By doing this you will be helping me to keep improving this stuff and to continue to help anyone who needs, and maybe keep on helping you in the future.


Thanks for your support, will do my best to keep the info fresh and useful.

Share
Related post:
bottom

216 Responses to “How to Create QuickAction Dialog in Android”

  1. CamDroid says:

    Thanks a bunch for the code – I’m really looking forward to building an app with this included! :D

    One thing, though – when I try to implement your files into my app, they cause it to crash. PopupWindows line 35 (mWindow = new PopupWindow(context) ) causes an IllegalStateException – “System services not available to Activities before onCreate()”

    I’ve called setContentView() in another class, and I’m pretty sure I’ve copied the files over correctly, so if you have any helpful tips, that would be amazing. :D

    Thanks for all of your hard work!

  2. Andy says:

    Hi lorenz,

    awesome work, again and thanks for publishing it on github. I am using your previous version of the code so. The new version which uses only one listener for all items doesn’t work for me. The problem with your solution is, you rely on the position of the clicked item. My quickaction list contains different amounts of actions depending on the state of the clicked item.

    So even though your solution is shorter/simpler it isn’t as flexible as your first solution.

    Just my two cents. Again, thanks for sharing this with the dev community.

    Andy

  3. Aitor says:

    Hi Lorenz,
    Thanks so much for sharing this.
    I’ve just included your code in one app I am working with and all seemed to work fine.
    However, when I was playing around at one moment I doubled clicked too fast on the button that shows the quickaction dialog, not intentionally, but I did and the application force closed.
    It was weird and I did not know if it was something in my code.
    Then I opened your example and start noticing the same problem, but only on Example1 (on the list this is not happening). If I click repeatedly and too fast on the buttons (I know that this is not how you are going to use your app but it happened unintentionally the first time) the app crashes with the following error

    ERROR/AndroidRuntime(8350): FATAL EXCEPTION: main
    ERROR/AndroidRuntime(8350): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams
    ERROR/AndroidRuntime(8350): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3129)
    ERROR/AndroidRuntime(8350): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
    ERROR/AndroidRuntime(8350): at android.view.View.measure(View.java:8313)
    ERROR/AndroidRuntime(8350): at android.view.ViewRoot.performTraversals(ViewRoot.java:839)
    ERROR/AndroidRuntime(8350): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
    ERROR/AndroidRuntime(8350): at android.os.Handler.dispatchMessage(Handler.java:99)
    ERROR/AndroidRuntime(8350): at android.os.Looper.loop(Looper.java:130)
    ERROR/AndroidRuntime(8350): at android.app.ActivityThread.main(ActivityThread.java:3683)
    ERROR/AndroidRuntime(8350): at java.lang.reflect.Method.invokeNative(Native Method)
    ERROR/AndroidRuntime(8350): at java.lang.reflect.Method.invoke(Method.java:507)
    ERROR/AndroidRuntime(8350): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    ERROR/AndroidRuntime(8350): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    ERROR/AndroidRuntime(8350): at dalvik.system.NativeStart.main(Native Method)

    I am using a Nexus One (Android 2.3.4), let me know if this is happening to you.

    Thanks so much

  4. angie says:

    hello,
    first of all it’s an awsome work!
    i’m trying to integrate the quickActionBar, Gallery 3D like to my Action Bar(a reusable layout)
    i’m getting a bug , the triangle it’s no longer attached to the square. i think it’s a problem of context , i have no idea how to fix it help!

  5. sahir says:

    thanks great Work

  6. Ron says:

    Very good work and article. I am planning to include this thing in my project. Thanks a bunch

  7. Igor says:

    Thank you, this article is very helpful! Good work!!!!!!!!!

  8. Connor says:

    Great example! I’m currently trying to implement this into my application, but unfortunately I use a custom view (onDraw and a canvas). Ideally, I’d like for the user to be able to touch any part of the screen and depending on where they touch, the quickaction menu pops up and has custom content (depending on the location of the touch). So currently I’m using an onTouchEvent, then locating the touch, then performing an action based on that location. How could I implement your code so when I touch the screen, the quickAction menu pops up and populates itself based on location?

    So for example:

    public boolean onTouchEvent(MotionEvent event) {
    int eventaction = event.getAction();

    int X = (int)event.getX();
    int Y = (int)event.getY();

    switch (eventaction ) {

    case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on a ball
    int centerX = 80;
    int centerY = 80;

    if (X > centerX – 30 && X centerY – 30 && Y < centerY + 30){//POPS UP QUICK ACTION MENU WITH CUSTOM CONTENT HERE
    }
    }
    break;
    }
    return true;
    }

    Thanks.

  9. Matthew Versaggi says:

    Great stuff! Big Kudos!

  10. Matthew Versaggi says:

    OK …. just perused you code … EXACTLY what I was looking for … BIG thanks again! :-)

  11. Cfanboy says:

    Thank you very much, I am looking for this codes long long time. Appreciated you shared on Github.

  12. Matthew says:

    Hello Lorenz, your code is what exactly im looking for, however the popup.9.png doesn’t seem to appear. see attached screenshot: http://i.imgur.com/zaTrB.png

  13. I think this code would be better for the onClick listener :

    container.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v)
    {
    if (mListener != null)
    mListener.onItemClick(pos);
    v.post(new Runnable()
    {

    @Override
    public void run()
    {
    dismiss();
    }
    });

    }
    });

  14. Adam says:

    Has anyone figured out how to use this with Fragments? I have a Left Fragment and a Right Fragment, both ListFragments. I want the QuickAction dialog to pop up when I click on a ListItem on the right. It pops up in the right spot vertically, but it’s within the Left Fragment, not the Right. Any ideas?

    Thank you…it’s a great bit of code!

  15. Ashish says:

    Thanks for bunch of code.

  16. Arpit Hada says:

    Hey thanks alot. A perfect example to implement QuickAction.
    Thanks again

  17. Awais says:

    Bundle of thanks lorenz.. It really helped alot.
    Keep posting

    Cheers

  18. TheVaan says:

    Thanks for this amazing code!
    I love it!

    One question: Is there a way to modify the code so that this popup is able to show only something like an information, so that there is only text, without clickListner and so on?
    I’m not a really pro in coding and hope you can help me :)

    Greetings

  19. Zammbi says:

    Working good but I am having one issue. When calling quickAction.show(v); in a button click it can crash with this in the log:

    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3129)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at android.view.View.measure(View.java:8330)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at android.view.ViewRoot.performTraversals(ViewRoot.java:843)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at android.os.Handler.dispatchMessage(Handler.java:99)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at android.os.Looper.loop(Looper.java:130)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at android.app.ActivityThread.main(ActivityThread.java:3835)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at java.lang.reflect.Method.invokeNative(Native Method)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at java.lang.reflect.Method.invoke(Method.java:507)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
    10-05 15:55:05.702: ERROR/AndroidRuntime(11608): at dalvik.system.NativeStart.main(Native Method)

  20. This was really very helpful. Thank you so much.

  21. TheVaan says:

    Hi!

    May I found a solution for your issue on github: https://github.com/lorensiuswlt/NewQuickAction3D/issues/1

  22. lendski says:

    mantap mas… saya punya 2 listview mas deng orientasi vertical, isinya banyak data tapi yang keliatan hanya 3 row aja gimana ya mas?jadi bisa di scrool buat liat semua datanya?thank you..

  23. Kevin Peck says:

    I have made a number of changes to the code that others may find helpful.

    1) Action Item – new constructor with action id, title, icon

    2) Callback enhanced to return QuickAction object as source and action id (allows you to add items in any order as you base what was clicked on by the ID, not the pos)

    3) Action item supports sticky mode, if that is enabled the menu does not dismiss post button press. I needed this for my application.

    4) QuickAction has getActionItem(pos) call so you can get action item back. QuickAction has ArrayList of added items to support this.

    5) QuickAction supports constructor with horizontal flag so you can run menu horizontally instead of just vertically.

    6) If doing horizontal QuickAction loads the action_item_horiz.xml and popuphoriz.xml files instead of the vertical ones.

    7) Added action_item_horiz.xml with a centered image over a centered text label

    8) Added horiz_separator.xml file so you can show a separator between items in a horizontal layout

    9) Updated NewQuickAction3DActivity to show the toast message based on label of action item clicked as you now have enough info in callback to do that generically

    I want to attempt to have all horizontal items show up same width by rolling through post add and getting max width and using that for all items. Not sure if that is possible.

    I would also like to add a spacer action so you can group items with an extra gap. Might do that as a parameter to addActionItem(action)

    I can send the code to you if you to look it over and see if my changes are acceptable and useful. I might take a day or so to polish it up and implement a few things mentioned above.

    The existing code has been very helpful and I wanted to give back to others who are using it.

  24. Karl Kristian says:

    Thanks for sharing this code I really like it.

    Defiantly going to use this on my app.

  25. Shilpy Pandey says:

    Hi,
    i want the arrow in the middle of the popup as its everytime either displayed on right or left side.Any option to make it in center

    • lorenz says:

      The position of the arrow is based on where the anchor view is placed. If you place the anchor view at the center of screen, the arrow will be displayed at the center too.

  26. Harsha says:

    lorenz,
    I am trying to use your quick action for menu item on action bar (3.0) and not being able to place at the right place.

    How can I do this in.
    mActionBarView = getLayoutInflater().inflate(
    R.layout.action_bar_custom, null);

    public boolean onOptionsItemSelected(MenuItem item)
    {
    switch (item.getItemId())
    {

    mQuickAction.show(mActionBarView);

    }
    }

    I know its because I am passing actionbar view as anchor view, how do I pass the menu item as the anchor view, is it possible?.

    Help on this is highly appreciated.

    Waiting for quick response :)

    Thanks,
    Harsha

  27. Harsha says:

    sorry for the typo, Its because of the actionbar view am passing as anchor view.

    Thanks,
    Harsha

  28. Jean-Michel says:

    Hi Lorenz,
    this is really great work and it seems it will suit my needs.

    I just have a question re the implementation.

    It is meant to be used as a library project, or should I rather copy everything in my own project tree ?

    Thanks in advance,
    JM

    • Lorenz says:

      Hi Jean, thanks for choosing quickaction. You should copy everything into your project. You can also make changes to the drawables if you want to make custom theme. ;)

  29. Jean-Michel says:

    Hi Lorenz,
    I did this as it was simpler indeed.

    I have just made a small modification to your code.

    I have added a tag object (like in View)to ActionItem. This allows “embedding” stuff into the ActionItem.
    It proved necessary in my case and might be useful to other users (the code is VERY simple, just added the instance variable and getter/setter).

    Thanks again for your great work.

  30. [...] How to Create QuickAction Dialog in Android | All About Web & Mobile Application Development [...]

  31. Harut says:

    Hi, I’m trying to adopt it to my project, I’d like to know do you have implementation for this to pop-up not from the top or bottom but from left or right?

    Thanks.
    Harut M.

  32. Zerho says:

    Hi i’m trying to use this on my app but when i click on a quick action item too “quickly” the image doesn’t behave like it should, it disappear and shows the background color, if i click it “slowly” it works properly,
    is there a way to fix it?
    do you experience the same thing?

    thanks

    Matteo

    • lorenz says:

      Hi Zerho, yes there is a bug on quickaction. the solution is to create separate background drawable for popup menu. i’ll try to update the fix soon on github.

  33. Plamen says:

    The transparent background bug still happens – android 2.2 HTC Desire. What is the problem there?

  34. Sandy says:

    Awesome code, thanks alot!

  35. Felix says:

    What is the minimum api level for the quick action?
    Good work. I like this feature.

  36. Rob says:

    Hey Lorenz,

    Thanks for this cool code!!!

    Is there any way to change an ActionItem’s icon or text, AFTER it has been added to the QuickAction?

    I’ve tried…

    myActionItem.setIcon(getResources().getDrawable(R.drawable.ic_checked));

    and

    quickAction.getActionItem(0).setIcon(getResources().getDrawable(R.drawable.ic_checked));

    but without success. I’m trying to implement a checked/unchecked state on a sticky ActionItem. Any suggestion on how to do this?

    Thanks,
    Rob

  37. Igor says:

    I have finally found the solution for transparent background problem. The thing is that popup window is dismissed too early so just put this piece of code in PopupWindows class, dismiss() method:

    public void dismiss() {

    new Thread(new Runnable() {

    @Override
    public void run() {
    try {
    Thread.sleep(1500);
    mWindow.dismiss();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }
    }).start();

    }

    I hope it helps…

  38. shinjidev says:

    Nice work and article :) . I’m using quickaction in my project, it works very well in smartphone app, but i have a problem when i try to show it in a Dialog, the quickaction appears in other place outside the dialog, what can i do in this case? :(

  39. Dorin says:

    Good job !!!

  40. George H. K. says:

    The code works perfect and the design is very easily customiziable, Great work!

    The only problem I currently have is that the PopupWindow consumes the touch event needed to dismiss itself, without delegating it to the other controls.

    I tried various ways to work around this, including unsuccessful try to set FLAG_NOT_TOUCH_MODAL but still not working.

    Any help will be greatly appreciated!

    • George H. K. says:

      Have anyone else had this problem and managed to fix it somehow?

      I see that the default camera app in Android 3.1 have quite nice kind of quick action menus, but the focus is not consumed, so you ca switch to (open) the next menu directly while closing the current one. So it is possible for sure :-)

  41. Andy says:

    Great article. I’ve used the QuickAction bar in the Greendroid library but never seen how to create the Gallery Like one. Really like this quick action, thanks for sharing.

  42. gil says:

    incredibly helpful thank you!!

    would be nice to just download the source project and work with that

    but still helped a lot :)

  43. cypressious says:

    I recently noticed, that on a big screen (like a Honeycomb tablet) the popup is positioned very weirdly and also the triangle below (above) the popup isn’t displayed.

    The strange thing is: Although this happens in landscape mode, it doesn’t in portrait mode.

  44. Spencer says:

    This works perfectly for a project I’ve been working on. I have a couple of questions though. First, I notice that the 3D version doesn’t scroll horizontally if there are more items than can be displayed. Also, is there a way to make the quick actions pop up to the side of the anchor instead of above/below? A fix to either the horizontal one not scrolling or popping a vertical list to the side of an anchor would help a lot. Let me know if I’m missing something. Thanks again!

Leave a Reply

 
bottom