2014-01-21 131 views
0

我正在使用片段的android應用程序。我使用了創建嚮導中生成的片段的標準模板。現在,我想爲'mTwoPane'爲true(屏幕尺寸大於600dp)使用不同的'ItemListFragment'佈局。單個窗格設備上的佈局將有一個標題和一個2x3圖標佈局,而mTwoPane設備將不會有標題並且將具有1x6佈局,因此所有圖標都將處於對方之下。基於設備的不同片段佈局android

在我的ItemListActivity.java中,檢查或存在item_detail_container。如果是這樣,mTwoPane設置爲true。

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_item_list); 

     if (findViewById(R.id.item_detail_container) != null) { 
      // The detail container view will be present only in the 
      // large-screen layouts (res/values-large and 
      // res/values-sw600dp). If this view is present, then the 
      // activity should be in two-pane mode. 
      mTwoPane = true; 

      // In two-pane mode, list items should be given the 
      // 'activated' state when touched. 
      ((ItemListFragment) getSupportFragmentManager() 
        .findFragmentById(R.id.item_list)) 
        .setActivateOnItemClick(true); 
     } 


    } 

我的第一個想法是檢查我的ItemListFragment中的mTwoPane,並根據此選擇RootView。但我無法得到這個工作。以下是我在做ItemListFragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
     View view; 
     boolean mTwoPane; 
     if (getView().findViewById(R.id.item_detail_container) != null) { 
      mTwoPane = true; 
     } 
     else mTwoPane = false; 

     if(!mTwoPane){ 
      view = inflater.inflate(R.layout.mobile_list, container, false); 
     } 
     else{ 
      view = inflater.inflate(R.layout.tablet_list, container, false); 
     } 

     return view; 
    } 

但是,這顯然是行不通的,因爲視圖需要之前有可能被選中或item_detail_container存在被實例化。

然後我開始想,應該讓碎片知道佈局嗎?也許我應該有2個列表佈局,一個用於平板電腦,另一個用於移動設備。但是再次,

setContentView(R.layout.activity_item_list); 

必須首先調用以檢查mTwoPane是否爲true。

什麼是最好的方法來做到這一點?

回答

1

Android將根據資源限定符或存儲桶選擇要使用的佈局資源。

例如

佈局MDPI 佈局HDPI 佈局XLARGE 佈局端口 佈局sw600dp

這些都是資源桶,比一切可以包含命名activity_item_list佈局文件。 Android會根據當前的設備屬性選擇要使用的佈局文件。

因此,解決方案是創建一個存在於佈局文件夾中的list_fragment佈局文件,以及layout-sw600dp文件夾(或任何您當前擁有的)。可以針對平板電腦調整layout-sw600dp文件夾中的佈局。

有這些文章以瞭解更多信息讀了起來:

http://android-developers.blogspot.co.uk/2011/07/new-tools-for-managing-screen-sizes.html http://developer.android.com/guide/practices/screens_support.html http://developer.android.com/guide/topics/resources/providing-resources.html

+1

謝謝您的回答。我沒有考慮使用碎片的佈局文件夾。但是這當然是顯而易見的。不能相信我沒弄明白我自己! – Arnout

+0

酷沒問題:) – athor