如何在一个活动中拥有多个按钮

Int*_*pps 1 java android

我的Android应用程序有很多按钮.

我的main.xml布局有三个按钮.

我知道如何使用按钮从一个活动转到另一个活动,但我不知道如何在一个活动上有多个按钮,每个按钮启动的活动与另一个活动不同.

main.xml中

Button1 Button2

Main2.xml

由button1发起

About.xml

由Button2发起

我如何使main.java文件这样做?

Pin*_*nki 6

public class NL extends Activity {



     public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
          Button b1=(Button)findViewById(R.id.Button01);
          Button b2=(Button)findViewById(R.id.Button02);
          b1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent myintent2 = new Intent(NL.this,Button1.class);
                startActivity(myintent2);

            }
        });
          b2.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    Intent myintent2 = new Intent(NL.this,Button2.class);
                    startActivity(myintent2);

                }
            }); 
    }
}
Run Code Online (Sandbox Code Playgroud)

使用intent从一个活动移动到另一个活动.我们在按钮单击侦听器中编写该代码


Nic*_*ion 5

这是一个相当广泛的问题,所以我的回答可能看起来同样广泛.

1.)首先要了解的是如何构建布局.你说你已经有了3个按钮的布局.在每个按钮的定义中,您需要指定一个android:id属性.这将允许您稍后从您的活动挂钩到该按钮.有关更多信息,请参阅此处

2.)一旦你用android:id定义了3个按钮(为了便于讨论,我们使用R.id.1,R.id.2和R.id.3)你想要将Java对象挂钩到这些元素在您的活动onCreate方法:

Button button3 = (Button) getViewById(R.id.3)
Run Code Online (Sandbox Code Playgroud)

为3个按钮执行此操作.

3.)下一步是将onClick监听器附加到按钮上

button3.setOnClickListener(new OnClickListener(){
  public void onClick(View v){
    //place code to execute here
  }
});
Run Code Online (Sandbox Code Playgroud)

与java中的大多数gui框架一样,此机制定义了单击按钮时执行的代码.如果要从此按钮启动一个新的Activity,您将创建一个intent对象并启动它,如:

Intent intent = new Intent(this, TheActivityClassYouWantToLaunch.class);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

将TheActivityClassYouWantToLaunch替换为扩展要启动的Activity的类的名称.要了解更多信息[请查看Intents上的文档](http://developer.android.com/reference/android/content/Intent.html)