2013-03-06 45 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