Tin_Ram Tin_Ram - 1 year ago 36
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:

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

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 Source

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:


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:

public void onDataSelectedEvent(String action) {

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

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