2013-10-18 30 views
1

是否可以將參數傳遞給android中包含的佈局?例如,我想要在橫向模式下在水平LinearLayout中顯示一組按鈕,並使用相同的include將LinearLayout的方向更改爲「垂直」。Android在景觀和人像中重複使用佈局

<include layout="buttons.xml" orientation="horizontal"/> 

在用於人像模式佈局XML我想這樣做:

<include layout="buttons.xml" orientation="vertical"/> 

而在buttons.xml我會:

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 

    <Button 
     android:id="@+id/btn1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="doSomething" 
     android:text="foo" > 
    </Button> 


    <Button 
     android:id="@+id/btn2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="doSomethingElse" 
     android:text="bar" > 
    </Button> 

如果我正確解釋文檔只能覆蓋包含的佈局*屬性。

有沒有其他的方法/解決方法來做到這一點,而不重複佈局xml? 感謝您的意見!

回答

0

還好我最後還是沒買是我的佈局分爲3個部分:

button_container。 xml只包含一個LinearLayout和兩個額外的包含

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="**horizontal**" > 

    <include layout="@layout/button_top_row" /> 
    <include layout="@layout/button_bottom_row" /> 

</LinearLayout> 
  • button_row_top包含應該排在前列進去的按鈕(在手持端口視圖)

-button_row_bottom包含應該走在最後一行(再次手持端口視圖)

按鈕

button_container。xml存在兩種版本,一種是水平方向(用於平板電腦,landsacpe爲移動手持設備)和一種垂直方向(用於手持端口)的版本。 所以我設法儘量減少代碼複製,儘管它不像我希望的那樣容易。

歡迎任何其他提示。 Bye, Markus

4

Android通過爲不同的配置提供不同的文件夾來處理這個問題。

從技術文檔:

再舉一個例子,這裏是一個替代佈局橫向項目:

MyProject的/

RES/ 佈局/

 main.xml 

    layout-land/ 

     main.xml 

默認情況下,layout/main.xml文件用於縱向定位。

我相信你應該那樣做,因爲它是在docummentation推薦的方式,但你可以改變方向yourseft如果你決定control orientation changes

,並以此來改變佈局方向:

LinearLayout layout = (get layout from view); 
layout.setOrientation(LinearLayout.VERTICAL); 

layout.setOrientation(LinearLayout.HORIZONTAL); 
+0

嗨Mikel,在代碼中動態地改變佈局並不是我想到的。我正在尋找一種方法來做到這一點在XML中。我知道資源選擇器可以覆蓋特定的佈局資源,但我擔心使用選擇器總是會產生冗餘資源,這些資源在以後很難維護。任何其他想法/提示? – markus

1

這有點遲了,但這裏有另一種可能性,沒有拆分佈局:您也可以將LinearLayout的方向值設置爲xml文件。由於定向值整數(0:水平,1:垂直),你也可以用這樣的方式:

<LinearLayout 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:orientation="@integer/orientation" > 

然後設置/覆蓋XML的文件這個方向值:

夢詩.XML

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <integer name="orientation">1</integer> <!-- vertical //--> 
</resources> 

夢詩-land.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <integer name="orientation">0</integer> <!-- horizontal //--> 
</resources>