有没有办法为listView项注册onClick事件而不通过startActivity发送意图,而只是使用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之前,我可能会更熟悉常规意图,但如果我能够首先学习更灵活的选项,那就更好了。
答案 0 :(得分:0)
我应该发布剩余的活动。我想如果我有这个问题会更容易回答。我将来不会犯这个错误。我正在使用列表活动..因此对我们来说正确的方法是onListItemClick。
@Override
public void onListItemClick(ListView parent,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);
}