3

我有一個基於片段的佈局與兩個ListFragments(A和B),都包含在一個活動(稱爲ListingActivity 1)。當應用程序啓動時,將調用ListingActivity 1,並根據設備是縱向還是橫向來顯示ListFragment A或僅顯示兩個ListFragment。處理setDisplayHomeAsUpEnabled與片段

當您單擊片段A的ListView中的項目時,將顯示片段B的ListView。當你點擊Fragment B的ListView中的一個項目時,它會轉到一個新的活動(活動1)。

我使用這個代碼(稱爲ListingActivity 2),以確定是否在它自己的顯示ListFragment B或連同ListFragment答:

public class ListingActivity extends SherlockFragmentActivity 
{ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 

     if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { 
      // If the screen is now in landscape mode, we can show the 
      // dialog in-line so we don't need this activity. 
      finish(); 
      return; 
     } 

     if (savedInstanceState == null) { 
      // During initial setup, plug in the details fragment. 
      final ListingFragment details = new ListingFragment(); 
      details.setArguments(getIntent().getExtras()); 

      getSupportFragmentManager().beginTransaction().add(android.R.id.content, details).commit(); 
     } 
    } 
} 

在活動1,我使用setDisplayHomeAsUpEnabled,以使Actionbar徽標作爲後退按鈕,但我不知道如何處理家庭意圖。當設備處於肖像模式時,用戶應該返回到ListingActivity 2,但是如果它們處於橫向模式,他們應該返回到ListingActivity 1。

我打算做這樣的事情,但它似乎真的hacky:

@Override 
public boolean onOptionsItemSelected(final MenuItem item) 
{ 
    if (item.getItemId() == android.R.id.home) 
    { 
     final Intent intent; 

     if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) 
      intent = new Intent(this, ListingActivity1.class); 
     else 
      intent = new Intent(this, ListingActivity2.class); 

     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
     startActivity(intent); 
     return true; 
    } else { 
     return super.onOptionsItemSelected(item); 
    } 
} 

回答

1

老實說,我認爲你的解決方案是實現上述行爲的正確方法。它遵守所有關於上行導航的Android標準(在這種情況下,我認爲它應該像「後退」按鈕那樣行事)。我會重新考慮的唯一事情就是使用Intent.FLAG_ACTIVITY_NEW_TASK標誌。從Android文檔:

任務是用戶爲完成目標而執行的一系列活動。

在這種情況下,您似乎沒有開始一項新任務。

+0

聽起來不錯。我猜如果我檢查ListActivity中的方向是否處於橫向,我應該可以選擇「向上」按鈕。理想情況下,我想檢查'smallestScreenWidthDp',但這並未引入Android 3.2。至於使用'Intent.FLAG_ACTIVITY_NEW_TASK',我用'addFlags'方法在上面的代碼中使用它,不確定是否應該在其他地方使用它。 – 2012-04-22 13:36:16

+0

@Alex使用向上導航它會轉到所需的片段,但它會重新加載以顯示。如何避免這種情況?我正在實施這個解決方案http://stackoverflow.com/questions/24596036/actionbar-up-button-go-to-previous-activity-with-prev-fragment,但它重新加載該片段。原因很明顯,它是加載活動。但如何避免這種情況? – Roon13 2015-06-19 07:09:54