在Android片段中的按钮上添加onTouchListener on

用户3521965

我试图在片段内的按钮上添加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;

            }

});

拉杰什

呼叫时版式尚未膨胀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;


}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章