Android “Best Practice” returning values from a dialog

后端 未结 6 1639
闹比i
闹比i 2020-12-07 18:27

What is the \"correct\" way to return the values to the calling activity from a complex custom dialog - say, text fields, date or time picker, a bunch of radio buttons, etc,

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 19:05

    Perhaps I'm mis-understanding your question, but why not just use the built in listener system:

    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // run whatever code you want to run here
            // if you need to pass data back, just call a function in your
            // activity and pass it some parameters
        }
    })
    

    This is how I've always handled data from dialog boxes.

    EDIT: Let me give you a more concrete example which will better answer your question. I'm going to steal some sample code from this page, which you should read:

    http://developer.android.com/guide/topics/ui/dialogs.html

    // Alert Dialog code (mostly copied from the Android docs
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Pick a color");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            myFunction(item);
        }
    });
    AlertDialog alert = builder.create();
    

    ...

    // Now elsewhere in your Activity class, you would have this function
    private void myFunction(int result){
        // Now the data has been "returned" (as pointed out, that's not
        // the right terminology)
    }
    

提交回复
热议问题