2014-03-06 38 views
0

我曾尝试通过Intent传递变量。但似乎我错过了一些我不能传递整数变量时间的东西。这个问题已经被其他人问过了,但是我不能在这种情况下使用它。如何在android中通过intent传递整数变量?

我想通过intent将整型变量time的值传递给另一个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 
} 
} 
+0

你做了什么错误? – Kedarnath

回答

1

您应该使用getIntExtra()方法:

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

更改默认值参数(第二个参数)到你希望它是什么。

,然后显示值

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

我将如何在textview分数中显示可变时间的值? – murrmurr

+0

@murrmurr我更新了我的答案。 – Szymon

+0

它不起作用。该代码有错误。 – murrmurr