0
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);

Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}

我的情况有点不同:我的主要活动调用了另一个(索引活动):

Intent index = new Intent(this, Index.class);
startActivity(index);

从索引活动中,用户可以从列表中进行选择。

所以,我需要将索引的类变量传递给主要活动。如何?

谢谢!

4

3 回答 3

0

好的,我完成了:

主要活动:

Intent i = new Intent(this, Index.class);
  startActivityForResult(i, 1);

指数:活动:

 button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {   
            String result = "1";
            Intent returnIntent = new Intent();
             returnIntent.putExtra("result",result);
             setResult(RESULT_OK,returnIntent);     
             finish();

主要活动:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {

         if(resultCode == RESULT_OK){

          String result=data.getStringExtra("result");
          value=result;
     }

    if (resultCode == RESULT_CANCELED) {
         //Write your code on no result return 

    }}
    }

“结果”是索引活动中的正确变量,但我需要将该变量用于主类,而不仅仅是在该方法中。

所以我希望将“结果”变量分享给整个班级。

方法是什么?

谢谢!

于 2012-11-25T18:36:09.207 回答
0

您需要使用 Activity 的方法startActivityforResult

请参阅此处应如何使用它的示例。

基本上这个想法是用来Bundles在活动之间传递数据。这样,即使活动因资源不足而在一段时间前被破坏,系统也可以恢复活动。

于 2012-11-25T16:47:00.947 回答
0
Intent intent= new Intent(this, Index.class);
i.putExtra("data", "data");
startActivity(intent);

在 Index 类中使用这个:

Bundle extras = getIntent().getExtras();
String data = extras.getString("data");
于 2012-11-25T16:50:26.327 回答