如何从Custom AlertDialog调用MainActivity类?

时间:2017-10-12 14:41:05

标签: java android

我在MainActivity中有一个名为PlaySong()的方法,而在MainActivity中,我正在调用这样的自定义AlertDialog类

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

如何从SonglistDialog中的歌曲列表中调用PlaySong()。目前我有这个ListView,我可以使用以下代码跟踪任何歌曲的点击:

@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
}

知道怎么做吗?

4 个答案:

答案 0 :(得分:2)

您可以使用回调。

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


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

理想情况下,Activity本身应该实现接口。因此songSelectedListener将是MainActivity.this

然后在onClick中你做:

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
}

答案 1 :(得分:2)

避免泄漏的最佳方法是创建一个侦听器界面

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

然后在SongListDialog构造函数

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);
}

最后在MainActivity中实现SongListListener

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

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

答案 2 :(得分:0)

由于您通过了MainActivity中的new SongListDialog(this, songsList),您可以通过举例来直接致电playSong

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

答案 3 :(得分:0)

  

您希望从活动中传递适配器中的上下文并使用该上下文

((MainActivity)上下文).playSong();