I'm new to Java/Android developing, and I have the habit of creating a tool library when learning a new platform, wher开发者_开发百科e I put functions for very common tasks. In this case, an OK/Cancel-Dialog.
What I want to achieve is something like this:
if (tools.ask("Are you sure")) {
//do something
}
else {
//don't do it
}
tools.ask() should create and display an OK/Cancel-Dialog, if user clicks OK returns true, otherwise (cancel clicked, backbutton clicked, application terminated, whatever) returns false.
I looked into AlertDialog, and I know how to implement this with X lines of code. But since this is event driven I have no idea about how to put this in a method with a return value.
Is it even possible?
Thanks in advance!
You need to have class that implements event listeners. These implemented methods specified by the event listener will be called back when an UI event happens, which will not cause your UI thread to hang.
For example
public class MyActivity extends Activity implements OnClickListener
And then implement the method
public void onClick(View v) {
int id = v.getId();
if (id == R.id.widget_id){
//Do something
}
}
Also you need to add the listener to the UI widget
widget.setOnClickListener(this);
Take a look here: http://developer.android.com/guide/topics/ui/ui-events.html.
You should not try to create a method that blocks, and waits for a result since you then will block the UI thread, and the OS will then report to the user that your application isn't responding.
Your UI should be event driven.
Have a look at the below class. I suggest you do the event handling part in your activity. Call the function that creates a needed alert dialog for you.
public class AlertUtil {
/** Single AlertUtil Object*/
private static AlertUtil mAlertUtil;
/**
* method that prepares Dialog
* @param context
* @param title
* @param message
* @return Alert Dialog
*/
public AlertDialog getAlertDialog1(Context context, int title,int icon,
String message){
AlertDialog alert = new AlertDialog.Builder(context).create();
alert.setTitle(title);
alert.setIcon(icon);
alert.setMessage(message);
alert.setCancelable(true);
return alert;
}
public static void setAlertUtil(AlertUtil mAlertUtil) {
AlertUtil.mAlertUtil = mAlertUtil;
}
public static AlertUtil getAlertUtil() {
if(mAlertUtil == null){
setAlertUtil(new AlertUtil());
}
return mAlertUtil;
}
}
精彩评论