繁体   English   中英

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

[英]How to pass integer variable through intent in android ?

我曾经尝试过通过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);  
     }  
}

补习班:

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
}
}

您应该使用getIntExtra()方法:

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

将默认值参数(第二个参数)更改为所需的值。

然后显示值

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM