有没有办法在不通过 startActivity 发送意图的情况下为 listView 项注册 onClick 事件,而只需使用 EventBus 发送和事件。
@Override
public void onClickListener(AdapterView<?> av,View v, int position, long id){
cursor.moveToPosition(position);
String st = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
Log.d("item slected",st);
MusicPlayerEvent playerevent = new MusicPlayerEvent(uri);
EventBus.getDefault().post(playerevent);
}
分段:
public class MusicPlayer extends Fragment {
MediaPlayer mp;
public MusicPlayer() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
mp = new MediaPlayer();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_music_player, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
EventBus.getDefault().unregister(this);
super.onDetach();
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
public void onEvent(MusicPlayerEvent playerevent){
try {
mp.setDataSource(this.getActivity(), playerevent.uri);
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
}
事件类:
public class MusicPlayerEvent {
Uri uri;
MusicPlayerEvent(Uri uri){
this.uri = uri;
}
}
我敢肯定这里有很多问题,但我想至少了解我正在尝试做的事情是否可行,也许是指向一些相关示例或阅读的指针。在尝试使用 EventBus 之前,我可能应该更熟悉常规意图,但如果我可以先学习更灵活的选项,那就太好了。