2013-03-06 27 views
2

我正在創建具有兩種佈局的Android應用程序。所有的佈局都有一些共同的特徵,如頂部是相同的,唯一的區別在底部。使用多種佈局優化Android代碼

目前我已經爲兩種佈局創建了兩個單獨的java文件。我已經簡單地複製,它實現如按鈕等

​​

類似功能的代碼

看到的部分是PIC是它是在兩個相同的佈局的佈局的頂部部分;

有沒有用,我可以通過具有可重用的代碼

+0

分割的公用部分進行,使用在您的佈局 – Simon 2013-03-06 22:43:59

+0

我正在考慮爲可重用代碼創建單獨的類。 – user2129794 2013-03-06 22:50:58

+0

我們可以爲xml做些什麼嗎? – user2129794 2013-03-06 22:51:15

回答

3

在我看來,這在主佈局使用<include>有利於優化功能的任何方式。

步驟:

你必須創建一個XML文件,爲常見的佈局。

topbar.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width=」match_parent」 
    android:layout_height="wrap_content" 
    android:background="@color/titlebar_bg"> 

    <ImageView android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/gafricalogo" /> 
</FrameLayout> 

這樣的方式,現在,你必須包含這個XML文件,你必須需要。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"  
    android:gravity="center_horizontal"> 

    <include layout="@layout/topbar"/> 

     ... 

</LinearLayout> 
+0

與這行有點混淆'它如何在行''include layout =「@ layout/titlebar中包含'topbar.xml?'或它的'topbar' 「/>'而不是'titlebar' – user2129794 2013-03-07 10:07:14

+0

看到我的更新代碼.. – Harshid 2013-03-07 10:14:07

+0

如果這對你有幫助然後接受 – Harshid 2013-03-07 10:14:54