1

I have a problem with passing int variable to another class. I've tried many methods of passing this variable but none have worked. Help me pass variable randomNum from MainActivity to HistoryActivity. Thanks!

public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    ........

        int min, max;
        max = 1;
        min = 0;
        int randomNum = min + (int) (Math.random() * ((max - min) + 1));


        int backgroundImages[] = {R.drawable.background1,
                R.drawable.background2};
        final Drawable backgroundImage = getResources().getDrawable(
                backgroundImages[randomNum]);
        linearLayoutBackground.setBackgroundDrawable(backgroundImage);



        // // WHAT TO DO NOW POGA
        buttonWhatToDoNow.setOnClickListener(new View.OnClickListener() {

                .........    

            }

        });


        buttonHistory.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent i = new Intent(MainActivity.this, HistoryActivity.class);
                startActivity(i);
                finish();

            }
        });    
    }
}

public class HistoryActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

            .......

        randomNum =..............;

        int backgroundImages[] = {R.drawable.background1,
                R.drawable.background2};
        final Drawable backgroundImage = getResources().getDrawable(
                backgroundImages[randomNum]);
        linearLayoutBackground.setBackgroundDrawable(backgroundImage);
    }

}
4

3 回答 3

1
Intent i = new Intent(MainActivity.this, HistoryActivity.class);
i.putExtra("intVariableName", randomNum);
startActivity(i);

例如在创建方法中的历史活动

 Intent mIntent = getIntent();
 int intValue = mIntent.getIntExtra("intVariableName", 0);
于 2013-06-07T12:29:02.117 回答
0

在您的 onclick 中:

    //onclick MainActivity
    Bundle bundle = new Bundle();
    bundle.putInt("key", randomInt);
    Intent intent = new Intent(MainActivity.this, HistoryActivity.class);
    intent.putExtras(bundle);
    finish();
    startActivity(intent);

    //then in your HistoryActivity onCreate
    int randomNum = getIntent().getExtras().getInt("key");`
于 2013-06-07T12:34:32.077 回答
0

假设我们有 2 个课程和 2 个活动。

如果您希望您的值在 HistoryActivity 中,只需在 HistoryActivity 的类中声明值(这是第二页的),并从第一个活动到 historyactivity 的意图......就是这样!!!!

于 2013-06-07T12:32:59.100 回答