如何在一个布局的活动中实现两个或更多按钮?

时间:2013-12-29 11:04:59

标签: android button android-activity

我有一个布局和更多按钮,但我无法实现更多按钮。 我只能在一个活动中实现一个按钮来打开另一个布局。我该如何解决这个问题?

这是我的代码:

public class AppActivity extends Activity {
    Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        addListenerOnButton();
    }

    public void addListenerOnButton() {

        final Context context = this;

        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(context, App2Activity.class);
                startActivity(intent);
            }
        });
    }
}

2 个答案:

答案 0 :(得分:2)

这样做:

button1 = (Button) findViewById(R.id.button1);

button1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

        Intent intent = new Intent(context, App2Activity.class);
        startActivity(intent);   

    }

});
button2 = (Button) findViewById(R.id.button2);

button2.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

        second Button code;   

    }

});

其中button2是xml

中定义的第二个按钮的id

答案 1 :(得分:0)

你可以这样做 -

public class AppActivity extends Activity {
    Button button1, button2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        addListenerOnButton();
    }

    public void addListenerOnButton() {
        final Context context = this;

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(context, App2Activity.class);
                startActivity(intent);
            }
        });
        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(context, App3Activity.class);
                startActivity(intent);
            }
        });
    }
}