January 2013
M T W T F S S
« Oct   Aug »
 123456
78910111213
14151617181920
21222324252627
28293031  

Categories

Meta


« | Main | »

Android custom AlertDialog

By Bart | January 7, 2013

For our Snøg Android app, I was browsing the web, figuring out how to add the UnlockBar I wrote to a Dialog, to create a slide-to-OK dialog. I reckoned this would be a simple case of extending the Dialog or AlertDialog class, build it and be done with  it. Well I was wrong. There is a lot of information to be found on the internet about Android programming in general and Dialogs in particular. But not the simple application I wanted. The official documentation tells me to subclass DialogFragment, but it seems like I need to have an ActivityFragment to support that correctly. That’s where I stopped, because the app is a plain simple phone Activity-app. So I ditched that. Then, a lot of blogs and info talking about the onCreateDialog method (nobody telling me in which class it is supposed to be overridden; tip: it’s Activity), that I haven’t had as well. I was just using the AlertDialog.Builder class to create dialogs, and all I wanted was to replace the OK button with my UnlockBar. That’s it! So, after looking around and experimenting a little, I got it: subclass the AlertDialog.Builder class:

public class UnlockDialog extends AlertDialog.Builder {
    UnlockBar unlockbar = null;

    protected UnlockDialog(Activity context) {
        super(context);

        LayoutInflater inflater = context.getLayoutInflater();
        View dlgView =inflater.inflate(R.layout.unlock_dialog, null); 
        setView(dlgView);
        unlockbar = (UnlockBar)dlgView.findViewById(R.id.unlockbar);
    }
}

Then, to use it, simply use this in your Activity to show the Dialog:

UnlockDialog builder = new UnlockDialog(this);
builder.setTitle(R.string.are_you_sure_);
builder.setMessage(R.string.slide_to_quit_snog).setNegativeButton(R.string.cancel, null);
builder.show();

Topics: Geekstuff, Opinie | Geen reacties »