从Fragment调用Activity然后返回Fragment

时间:2014-02-28 00:17:25

标签: android android-fragments

我有一个有几个标签的应用。这些标签都是片段。在第一个标签片段上,我有一个文本视图和一个按钮,我按这个按钮来调用活动。

此活动显示项目列表,车名。

我希望能够点击列表中的汽车并返回到调用片段,并使用我选择的汽车名称更新文本视图。

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:10)

startActivityForResult()可能就是你要找的东西。因此,一个快速示例(对数据结构进行超基本假设 - 根据需要替换)将使您的片段覆盖onActivityResult(),定义请求代码,然后使用该请求代码启动活动:

// Arbitrary value
private static final int REQUEST_CODE_GET_CAR = 1;

private void startCarActivity() {
    Intent i = new Intent(getActivity(), CarActivity.class);
    startActivityForResult(i, REQUEST_CODE_GET_CAR);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // If the activity result was received from the "Get Car" request
    if (REQUEST_CODE_GET_CAR == requestCode) {
        // If the activity confirmed a selection
        if (Activity.RESULT_OK == resultCode) {
            // Grab whatever data identifies that car that was sent in
            // setResult(int, Intent)
            final int carId = data.getIntExtra(CarActivity.EXTRA_CAR_ID, -1);
        } else {
            // You can handle a case where no selection was made if you want
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

然后,在CarActivity中,无论您为列表设置点击侦听器,请设置结果并在Intent中传回您需要的任何数据:

public static final String EXTRA_CAR_ID = "com.my.application.CarActivity.EXTRA_CAR_ID";

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // Assuming you have an adapter that returns a Car object
    Car car = (Car) parent.getItemAtPosition(position);
    Intent i = new Intent();

    // Throw in some identifier
    i.putExtra(EXTRA_CAR_ID, car.getId());

    // Set the result with this data, and finish the activity
    setResult(RESULT_OK, i);
    finish();
}

答案 1 :(得分:9)

致电startActivityForResult(theIntent, 1);

在开始的活动中,一旦用户选择了汽车,请确保将汽车置于意图中并将活动的结果设置为该意图

Intent returnIntent = new Intent();
returnIntent.putExtra("result", theCar);
setResult(RESULT_OK, returnIntent);     
finish();

然后,在您的片段中,实施onActivityResult

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

  if (requestCode == 1) {

     if(resultCode == RESULT_OK){      
         String result = data.getStringExtra("result");          
     }
     if (resultCode == RESULT_CANCELED) {    
         //Write your code if there's no result
     }
  }
}  //onActivityResult

确保覆盖片段托管活动中的onActivityResult(),并调用超级

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

这是因为父活动劫持了onActivityResult方法,如果你不调用super()那么它就不会传递给片段来处理它