单击两个按钮同时出现问题

时间:2014-10-31 12:59:48

标签: android button android-intent android-activity

我有3项活动。 在activity_Second中,当用户单击button_right时,activity_Second将销毁并且activity_Third启动; 再次在activity_Second中,当用户单击button_left时,activity_Second将销毁并且activity_First将启动。

一切正常,直到用户同时点击两个按钮,然后BANG,应用程序崩溃。 为什么会发生这种情况,我该如何解决这个问题。

注意:我需要销毁activity_Second,因为它会获得一些媒体播放器,因此需要释放大量内存。

这是activity_Second的java代码:

public class Second extends Activity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        right = new Intent(getApplicationContext(), Third.class);
        left = new Intent(getApplicationContext(), First.class);
        ImageView button_left = (ImageView) findViewById(R.id.button_left);
        ImageView button_right = (ImageView) findViewById(R.id.button_right);

        button_left.setOnClickListener(this);
        button_right.setOnClickListener(this);

    }
    @Override
    public void onClick(View item) {
        if(item.getId() == R.id.button_left)
        {
            left.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(left);
            this.onDestroy();
        }
        else if(item.getId() == R.id.button_right)
        {
            right.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(right);
            this.onDestroy();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试这样可以帮到你,

public class Second extends Activity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        ImageView button_left = (ImageView) findViewById(R.id.button_left);
        ImageView button_right = (ImageView) findViewById(R.id.button_right);

        button_left.setOnClickListener(this);
        button_right.setOnClickListener(this);

    }
    @Override
    public void onClick(View item) {
        if(item.getId() == R.id.button_left)
        {
            Intent left = new Intent(Second.this, First.class);
            left.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(left);

            finish();
        }
        else if(item.getId() == R.id.button_right)
        {
            Intent right = new Intent(Second.this, Third.class);
            right.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(right);

            finish();
        }
    }
}