10

我需要你的帮助:我想在完成当前活动之前将额外数据放入上一个活动。

例如:活动 A 开始活动 B 当我完成活动 BI 时想要活动 A 中的新数据。

我怎么能这样做?非常感谢之前

4

3 回答 3

9

Android SDK解释在这里,更好的SO问题答案+示例在这里

于 2012-11-29T14:35:21.243 回答
7

用于startActivityforResult打开活动 B..然后覆盖onActivityResult(int, int, Intent)您的活动 A..

例子:

public class MyActivity extends Activity {
 ...

 static final int PICK_CONTACT_REQUEST = 0;

 protected boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
         // When the user center presses, let them pick a contact.
         startActivityForResult(
             new Intent(Intent.ACTION_PICK,
             new Uri("content://contacts")),
             PICK_CONTACT_REQUEST);
        return true;
     }
     return false;
 }

 protected void onActivityResult(int requestCode, int resultCode,
         Intent data) {
     if (requestCode == PICK_CONTACT_REQUEST) {
         if (resultCode == RESULT_OK) {
             // A contact was picked.  Here we will just display it
             // to the user.
             startActivity(new Intent(Intent.ACTION_VIEW, data));
         }
     }
 }
}

检查http://developer.android.com/reference/android/app/Activity.html

于 2012-11-29T14:34:49.240 回答
3

使用 startActivityforResult 启动 Activity B。在 Activity A 中实现 override onActivityResult(int, int, Intent) 方法,在 ActivityB 中实现 setResult。

例子:

public class ActivityA extends Activity {

static final int REQUEST_CODE = 0;

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

        setContentView(R.layout.xyz);

        DateBtn.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    startActivityForResult(new Intent(ActivityA.this,ActivityB.class), REQUEST_CODE);
                }
            });
    }

 protected void onActivityResult(int requestCode, int resultCode,
         Intent data) {
     if (requestCode == REQUEST_CODE) {
         if (resultCode == RESULT_OK) {
             // A contact was picked.  Here we will just display it
             // to the user.
             startActivity(new Intent(Intent.ACTION_VIEW, data));
         }
     }
 }
}


public class ActivityB extends Activity {

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

        setContentView(R.layout.xyz);

        BackBtn.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
            Intent intent = new Intent();
            intent.putExtra("DATA", "your string");
            setResult(RESULT_OK, intent);
            finish();
                }
            });
    }

}
于 2015-10-30T07:50:00.183 回答