如何使用两个按钮启动活动

时间:2018-01-07 12:53:24

标签: android button

如何编写代码,以便在按第一个按钮(btn1)然后按第二个按钮(btn2)时,第二个活动(SecondActivity)是否开始?

1 个答案:

答案 0 :(得分:0)

试试这个

public class MainActivity extends AppCompatActivity {

Boolean launch = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn1 = (Button) findViewById(R.id.button);
    Button btn2 = (Button) findViewById(R.id.button2);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launch = true;
        }
    });

    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (launch == true)
            {
                Intent i = new Intent(MainActivity.this,Main2Activity.class);
                startActivity(i);
            }
            else
            {
                //do your stuff
            }
        }
    });
}
}