2014-02-28 79 views
5

我有一个有几个选项卡的应用程序。这些标签都是碎片。在第一个标签片段上,我有一个文本视图和一个按钮,我按下它可以调用一个活动。从片段调用活动,然后返回片段

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

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

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

+0

你或许应该考虑使用[DialogFragment(HTTP: //developer.android.com/reference/android/app/DialogFragment.html)或调用'startActivityForResult' – rperryng

回答

9

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

要注意的是,如果宿主活动重写了onActivityResult()方法,它应该调用super.onActivityResult(requestCode,resultCode,data)以便片段有机会接收它 – rperryng

+1

是的,这是一件好事。由于没有严格的要求来调用超级实现,因此离开并花费数小时调试将是一件容易的事情。 :) – kcoppock

6

呼叫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(),那么它不会得到传递给片段处理它

+0

谢谢,Rperryng。我也会接受你的回答,但@kcoppock似乎已经打了你几分钟。 你的重写超级方法的解释非常棒。 –