如何在android中通过intent传递整数变量?

时间:2014-03-06 02:33:04

标签: android android-intent integer

之前我曾尝试通过Intent传递变量。但似乎我遗漏了一些我无法通过整数变量时间的东西。其他人之前已经问过这个问题,但我不能让它在这种情况下工作。

我想将整数变量时间的值传递给另一个通过intent意图的aftertap.class类。

我有这个代码。

public class ingame extends Activity {
private TextView textTimer;
int time = 0;  
Timer t;  
TimerTask task;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ingame);
    Button button = (Button)findViewById(R.id.my_button);
    final RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

    params.leftMargin = button.getWidth()+ new Random().nextInt(displaymetrics.widthPixels - 2*button.getWidth());
    params.topMargin = button.getHeight()+ new Random().nextInt(displaymetrics.heightPixels - 3*button.getHeight());
    Log.v("widthPixels", ""+ displaymetrics.widthPixels);
    Log.v("heightPixels", ""+ displaymetrics.heightPixels);
    button.setLayoutParams(params);
    startTimer();

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
              t.cancel();  
              t.purge(); 

            //Starting a new Intent
              Intent thirdscreen = new Intent(getApplicationContext(), aftertap.class);

                //Sending data to another Activity
                thirdscreen.putExtra("time", time);
                startActivity(thirdscreen);
        }
    });
}
public void startTimer(){  
      t = new Timer();     
      task = new TimerTask() {  

        @Override  
       public void run() {  
        runOnUiThread(new Runnable() {  

          @Override  
         public void run() {
              textTimer = (TextView) findViewById(R.id.textTimer);
              textTimer.setText(time + "");  
              time = time + 1;  
         }  
        });  
       }  
      };  
      t.scheduleAtFixedRate(task, 0, 1);  
     }  
}

Aftertap课程:

public class aftertap extends Activity{
TextView score;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.aftertap);
    TextView gameover = (TextView)findViewById(R.id.gameover);
    score = (TextView)findViewById(R.id.score);

    Intent i = getIntent();
    // Receiving the Data
   //I do not know how to get the value of the integer variable time. I want to display the value of time in the TextView score
}
}

1 个答案:

答案 0 :(得分:1)

您应该使用getIntExtra()方法:

int value = i.getIntExtra("time", 0); 

将默认值参数(第二个参数)更改为您想要的值。

然后显示值

score.setText(String.valueOf(value));