在Android eclipse中使用Intent

问题描述

| 嗨,我有一个layout.xml,带有3个链接到单独布局的按钮。 我已经设法使用意图对1个按钮进行编码。但是,我不知道如何在接下来的按钮中添加内容,以使它们分别进入单独的布局。这是我的代码
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Activity1 extends Activity implements OnClickListener {
    Button hello1,hello2,hello3;
    /** Called when the activity is first created. */

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

            hello1 = (Button)findViewById(R.id.hello1);
            hello2 = (Button)findViewById(R.id.hello2);
                hello3 = (Button)findViewById(R.id.hello3);
            hello1.setonClickListener(this);
            hello2.setonClickListener(this);
                hello3.setonClickListener(this);             
        }

        public void onClick(View src) {
          Intent hello1 = new Intent(this,Hello1Activity.class);
          startActivity(hello1);         
          Intent hello2 = new Intent(this,Hello2Activity.class);
          startActivity(oltp);
              Intent hello3 = new Intent(this,Hello3Activity.class);
          startActivity(oltp);
        }
    }
这根本不起作用..单击时,第一个按钮转到hello3。如果我删除hello2和hello3,那么hello1效果很好。任何想法请。     

解决方法

您已将相同的单击侦听器附加到所有三个按钮上,并且正在onClick方法中启动所有这三个活动。 Hello3活动是在Hello2Activity和Hello1Activity之后启动的活动,因此始终会启动。要实现您要执行的操作,您应该为每个按钮附加一个不同的侦听器,并将特定于该按钮的代码放在此处。就像是:
    hello1.setOnClickListener(new View.OnClickListener(){
    public void onClick(View src){
    Intent hello1 = new Intent(this,Hello1Activity.class);
          startActivity(hello1);  }
    });
    ,由于您将onClickListener的所有3个按钮都设置为
this
,因此
onClick
应该看起来像这样:
public void onClick(View src) {
    switch(src.getId())
    {
    case R.id.hello1:
        Intent hello1Intent = new Intent(this,Hello1Activity.class);
        startActivity(hello1Intent);
        break;
    case R.id.hello2:
        Intent hello2Intent = new Intent(this,Hello2Activity.class);
        startActivity(hello2Intent);
        break;
    case R.id.hello3:
        Intent hello3Intent = new Intent(this,Hello3Activity.class);
        startActivity(hello3Intent);
        break;
    }
}
另一个解决方案是为每个按钮使用单独的onClickListener。