2011-03-14 164 views
0

我不知道崩溃的原因。android上的应用程序崩溃

package com.tct.soundTouch; 

//imports();;;;;;; 

    public class Main extends Activity implements OnClickListener{ 

     private MediaPlayer mp; 
     private MotionEvent event; 

     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
      this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
        WindowManager.LayoutParams.FLAG_FULLSCREEN); 
      setContentView(R.layout.main); 

      final ImageButton zero = (ImageButton) this.findViewById(R.id.button); 
      zero.setOnClickListener(this); 

      mp = MediaPlayer.create(this, R.raw.sound); 

     } 


     public void onClick(View v) { 
      switch (event.getAction()) { 

      case MotionEvent.ACTION_DOWN: 
       mp.setLooping(true); 
       mp.start(); 
       break; 

      case MotionEvent.ACTION_UP: 
       mp.pause(); 
       break; 

      } 
     } 

    } 

日志 enter image description here

感谢

+0

这是34行吗? – Farrell 2011-03-14 16:36:19

+0

第34行:switch(event.getAction()){ – anvd 2011-03-14 16:40:20

+0

现在我100%确定我的回答是正确的:D – RoflcoptrException 2011-03-14 16:41:57

回答

1

我没有看到event在您发布的代码中设置为非空值。不幸的是,通过OnClickListener收到的点击事件没有“向上”或“向下”。如果您需要处理MotionEvent.UPMotionEvent.DOWN,那么你应该实现View.OnTouchListener

public void onClick(View v) { 
    if (mp.isPlaying()) { 
     mp.pause(); 
    } else { 
     mp.setLooping(true); 
     mp.start(); 
    } 
} 

@Override 
public boolean onTouch(View v, MotionEvent event) { 
    switch (event.getAction()) { 
     case MotionEvent.ACTION_DOWN: 
      mp.setLooping(true); 
      mp.start(); 
      return true; 
     case MotionEvent.ACTION_UP: 
      mp.pause(); 
      return true; 
    } 
    return false; 
} 

如果你正在寻找一个肘般的效果,你可以使用MediaPlayer#isPlaying()然后将其设置为使用setOnTouchListener

zero.setOnTouchListener(this);

+0

感谢您的回答。但我需要使用事件ACTION_UP和ACTION_DOWN。当按下按钮时,播放声音,当btn没有按下音乐停止时 – anvd 2011-03-14 16:54:28

+0

我只是改变为onTouch,谢谢 – anvd 2011-03-14 17:04:16

+0

是的,这是我将使用的解决方案:) – anvd 2011-03-14 17:06:14

2

我认为这个问题是在该行switch (event.getAction()) {。你在哪里初始化事件?我认为这会导致NullPointerException。

Btw ...你不应该命名你的类的主要。至少使用Main。

+0

我在代码中使用了:private MotionEvent event;所以它被定义。 谢谢 – anvd 2011-03-14 16:37:11

+0

@费尔是的,但没有初始化 – RoflcoptrException 2011-03-14 16:37:34

+0

所以,你有什么建议?我如何初始化事件? – anvd 2011-03-14 16:41:59