简体   繁体   中英

How to call a MainActivity class from Custom AlertDialog?

I have a method inside MainActivity named PlaySong() , and from MainActivity, I'm calling a custom AlertDialog class like this

SongListDialog songlistDialog = new SongListDialog(this, songsList);
songlistDialog.show();

how can I call PlaySong() from songlist which is inside the SonglistDialog. Currently I have this ListView and I can track the click on any song using the following code:

@OnClick(R.id.card_view)
void onClick() {
     Song song = songs.get(getAdapterPosition());
     dialog.dismiss();

    // here I want to call PlaySong() method which is inside MainActivity
}

Any idea how to do this?

You can use a callback.

public interface OnSongSelectedListener{
    void onSongSelected(Song song);
}


// Then in your Activity
SongListDialog songlistDialog = new SongListDialog(this, songsList, songSelectedListener);
songlistDialog.show();

Ideally, the Activity itself should implement the interface. So songSelectedListener will be MainActivity.this .

Then in the onClick you do:

void onClick() {
    Song song = songs.get(getAdapterPosition());
    listener.onSongSelected(song); // Return the selected song
    dialog.dismiss();

    // here I want to call PlaySong() method which is inside MainActivity
}

the best way to avoid leaks is to create a listener interface

public interface SongListListener {
   void playSong(Song song);
}

then on your SongListDialog constructor

private final SongListListener mListener;

public SongListDialog(SongListListener listener, ...) {
    mListener = listener;
}


@OnClick(R.id.card_view)
void onClick() {
     Song song = songs.get(getAdapterPosition());
     dialog.dismiss();

    // notify listener
    mListener.PlaySong(song);
}

Finally implements SongListListener in your MainActivity

public class MainActivity extends Activity implements SongListListener  {
   //...

  @Override
   void playSong(Song song){
   //do whatever you want with the song here
   }
//...
}

Since you are passing the MainActivity in new SongListDialog(this, songsList) you can directly call playSong on it by casting eg

public SongListDialog(Context ctx, ...) {
    ((MainActivity) ctx).playSong();
}

you want to pass context in adapter from your activity and use that context

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM