我有一个应用程序有几个标签。这些标签都是碎片。在第一个选项卡片段上,我有一个文本视图和一个按钮,我按下它来调用一个活动。
此活动显示项目列表、车辆名称。
我希望能够点击列表中的一辆车,返回到调用片段,并用我选择的车名更新文本视图。
有人能帮我解决这个问题吗?

最佳答案

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();
}

07-24 09:49
查看更多