我多次单击图像按钮后出现错误的原因

时间:2017-05-31 04:10:00

标签: java android

当我单击图像按钮超过15次时,它应该停止运行。我在这里可以使用的代码是什么? 我是新开发者,我真的需要你的帮助。我希望你能帮助我

这是我的代码:

public class MainActivity extends Activity{
    MediaPlayer mp;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                         WindowManager.LayoutParams.FLAG_FULLSCREEN);
                        setContentView(R.layout.main);                   

        ImageButton One = (ImageButton) findViewById(R.id.btnkick);
        One.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.kick1);  
                try
                {
                    mp.prepare();
                }
                catch (IOException e)
                {}
                catch (IllegalStateException e)
                {}
                mp.start();
            }
        });

    ImageButton two = (ImageButton) findViewById(R.id.btnkick1);
    two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.kick1);  
                try
                {
                    mp.prepare();
                }
                catch (IOException e)
                {}
                catch (IllegalStateException e)
                {}
                mp.start();
            }
        }); 

1 个答案:

答案 0 :(得分:0)

int count=0;
One.setOnClickListener(new View.OnClickListener()
 {
    @Override
    public void onClick(View v)
     {
        count=count+1;
        if(count<=15)
        {
            MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.kick1);  
            try
            {
                mp.prepare();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            mp.start();
        }

    }
});

int counttwo=0;
 two.setOnClickListener(new View.OnClickListener() 
 {
    @Override
    public void onClick(View v) 
    {
        counttwo=counttwo+1;
        if(counttwo<=15)
        {
            MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.kick1);  
            try
            {
                mp.prepare();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            mp.start();
        }
    }
}); 

在您的代码中使用它。