我正在尝试在片段内的Button上添加onTouchListner。此代码在主要活动中正常工作,但在片段上没有。只要按下按钮,我想要做的就是播放一定的声音文件。任何帮助将不胜感激。
代码是
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
message1();
return inflater.inflate(R.layout.fragment_fragment_a, container, false);
}
public void message1() {
// TODO Auto-generated method stub
ImageButton one1 = (ImageButton) getView().findViewById(R.id.imageButton1);
one1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int resID = R.raw.a;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//mp.setLooping(true);
if (mp != null) {
mp.release();
}
// Create a new MediaPlayer to play this sound
mp = MediaPlayer.create( getActivity(), resID);
mp.start();
break;
case MotionEvent.ACTION_UP:
mp.stop();
break;
}
return true;
}
});
答案 0 :(得分:0)
致电message1()
时,布局没有膨胀。因此,findViewById
无法找到您的按钮,因为它在视图层次结构中不存在。
尝试以下方法:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_a, container, false)
ImageButton one1 = (ImageButton) view.findViewById(R.id.imageButton1);
one1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int resID = R.raw.a;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//mp.setLooping(true);
if (mp != null) {
mp.release();
}
// Create a new MediaPlayer to play this sound
mp = MediaPlayer.create( getActivity(), resID);
mp.start();
break;
case MotionEvent.ACTION_UP:
mp.stop();
break;
}
return true;
}
});
return view;
}