2014-02-28 76 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似乎已經打了你幾分鐘。 你的重寫超級方法的解釋非常棒。 –