[英]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 我在MainActivity中有一个名为PlaySong()
,并且从MainActivity中,我正在像这样调用自定义AlertDialog类。
SongListDialog songlistDialog = new SongListDialog(this, songsList);
songlistDialog.show();
how can I call PlaySong() from songlist which is inside the SonglistDialog. 如何从SonglistDialog内部的歌曲列表中调用PlaySong()。 Currently I have this ListView and I can track the click on any song using the following code: 目前,我拥有此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
}
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
. 所以songSelectedListener
将是MainActivity.this
。
Then in the onClick you do: 然后在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
}
the best way to avoid leaks is to create a listener interface 避免泄漏的最佳方法是创建一个侦听器接口
public interface SongListListener {
void playSong(Song song);
}
then on your SongListDialog constructor 然后在你的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);
}
Finally implements SongListListener in your MainActivity 最后在您的MainActivity中实现SongListListener
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 由于您要在new SongListDialog(this, songsList)
中传递MainActivity
new SongListDialog(this, songsList)
可以通过强制转换直接在其上调用playSong
public SongListDialog(Context ctx, ...) {
((MainActivity) ctx).playSong();
}
you want to pass context in adapter from your activity and use that context 您想从活动中传递适配器中的上下文并使用该上下文
((MainActivity)context).playSong(); ((MainActivity)上下文).playSong();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.