Tin_Ram Tin_Ram - 4 months ago 7
Android Question

Know which item selected?

I have an application where you can select an item from a AlertDialog spinner like, but I don't know how to make my app, to memorize the selected choice, and then behave my button to this. This is what I have now:

@Override
public void onClick(View v) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mp = MediaPlayer.create(getApplicationContext(), R.raw.ais);
mp.start();
Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
MainActivity.this.startActivity(myIntent);
}
}, 9000);
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
});
}


And somehow to this code, I want to add my last selected item button, for example:

If ( last selected item from AlertDialog was = dance)

do the code, that I wrote above.

Answer

One way to do it is with an interface. Define an interface in your Alert Dialog fragment and instantiate it like this:

public interface MyDialogListener {
    //put whatever data you want to pass as a paramenter, below I have two examples
    public void onDataSelectedEvent( String action); 
}

MyDialogListener myListener;

The listener will have to be instantiated in the dialog by typecasting your activity to a MyDialogListener.

You could do it like this:

myListener = (MyDialogListener) MainActivity.this;

Or even better would be to use the activity parameter in the dialog's onAttach(...) method.

We are able to do this because later, we will make your activity implement the MyDialogListener interface, which will effectively make the activity a MyDialogListener.

Put this line in the method or listener, maybe an onClick() in your alert dialog. This is for a spinner:

myListener.onDataSelectedEvent(mySpinner.getSelectedItem().toString())

Implement the interface in your Activity that receives the data like this:

public class MyActivity extends Activity
                      implements MyAlertDialog.MyDialogListener{

Then, in the activity receiving the data, have the interface method look like this:

@Override
public void onDataSelectedEvent(String action) {

    //probably better to use a switch statement
    if(action == "dance") {
         // dance()
    } else if(action == "stand") {
      .......etc 
    }
}

There is a good example here: http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents