我有一个应用程序,其中包含几个选项卡。这些选项卡都是片段。在第一个选项卡片段上,我有一个文本视图和一个按钮,我按下该按钮以调用活动。
此活动显示一个项目列表,即汽车名称。
我希望能够单击列表中的汽车并返回到调用片段,并使用我选择的汽车名称更新文本视图。
有人能帮帮我吗?
此活动显示一个项目列表,即汽车名称。
我希望能够单击列表中的汽车并返回到调用片段,并使用我选择的汽车名称更新文本视图。
有人能帮帮我吗?
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();
}
使用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()
,并调用super函数。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
startActivityForResult
。 - rperryng