使用Intent for android eclipse

时间:2011-05-24 05:08:31

标签: android android-intent

我有一个layout.xml,其中3个按钮链接到不同的布局。

我已经设法使用intent编写了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运行良好。任何想法,请。

2 个答案:

答案 0 :(得分:0)

您已将相同的点击侦听器附加到所有三个按钮,并且您将在onClick方法中启动所有这三个活动。 Hello3活动是在Hello2Activity和Hello1Activity之后启动的活动,因此它始终启动。要实现您要执行的操作,您应该为每个按钮附加一个不同的侦听器,并将特定于该按钮的代码放在那里。类似的东西:

    hello1.setOnClickListener(new View.OnClickListener(){
    public void onClick(View src){
    Intent hello1 = new Intent(this, Hello1Activity.class);
          startActivity(hello1);  }
    });

答案 1 :(得分:0)

由于您将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。