2012-03-05 72 views
0

我正在开发一个Android 2.1应用程序。新手:设置内容视图由两部分组成

我已经定义了一个LinearLayout

public class MyTopBar extends LinearLayout { 
    ... 
} 

然后,我有一个布局xml文件(content.xml):

<LinearLayout> 
    ... 
</LienarLayout> 

我有RootActivity.java,我想设置MyTopBar作为此RootActivity中的内容。

然后,我有MyActivity延伸RootActivity

public class MyActivity extends RootActivity{ 
     //set xml layout as content here  
} 

我想设置的content.xml为MyActivity的内容。

总的来说,我想用上面的方式来实现MyTopBar应该位于之上的布局,总是在屏幕上的。其他延伸RootActivity的活动的内容低于MyTopBar。如何实现这一点??

回答

1

1你可以直接添加自定义LinearLayoutMyActivity类的XML布局是这样的:

<LinearLayout> 
    <com.full.package.MyTopBar 
     attributes here like on any other xml views 
    /> 
    ... 
</LinearLayout> 

,或者您可以使用include标签包括与自定义视图的布局:

<LinearLayout> 
    <include layout="@layout/xml_file_containing_mytopbar" 
    /> 
    ... 
</LinearLayout> 

2用途:

setContentView(R.layout.other_content); 
+0

嗨,我已更新我的文章,请看看。基本上,我想将MyTopBar从XML布局中分离出来,以便我只在RootActivity中启动MyTopBar,其他扩展根活性的活动只设置xml内容,作为一个整体,我希望在屏幕上方显示MyTopBar,并使用其他xml下面的布局显示... – 2012-03-05 09:54:37

+0

@ Leem.fin我知道你在做什么,可能是你所有活动的一个酒吧。我认为最好的办法是使用'include'标签,并简单地包含一个只包含您自己的自定义视图的xml布局。你不能在'RootActivity'中设置'contentView',因为它将在子类中被替换。 – Luksprog 2012-03-05 10:08:03

+0

@ Leem.fin这里是一个链接从谷歌http://developer.android.com/resources/articles/layout-tricks-reuse.html – Luksprog 2012-03-05 10:10:39

0

为TopBar腾出布局,并使用layout.addView(topbarObject); 将Topbar添加到它中关于第二个问题,据我所知,setContentView只能调用一次。然而,您可以使用View.inflate(other_content.xml)来扩充这两个xml文件,并在您需要时在父xml布局中添加。您可以在父布局上使用removeView(),在使用新的布局文件。

编辑: 对于这两个问题的解决方案,你可以有一个父布局的例如。像下面这样:

//Omitting the obvious tags 
//parent.xml 
<RelativeLayout 
    android:id="@+id/parentLayout"> 
    <RelativeLayout 
     android:id="@+id/topLayout"> 
    </RelativeLayout> 
    <RelativeLayout 
     android:id="@+id/contentLayout"> 
    </RelativeLayout> 
</RelativeLayout> 

现在在代码中设置父布局内容视图,让你的顶栏布局的对象,并将其添加到topLayout。

setContentView(R.layout.parent); 
MyTopBar topBar=new MyTopBar(this); 
RelativeLayout toplayout=(RelativeLayout)findViewByid(R.id.topLayout); 
topLayout.addView(topBar); //or you can directly add it to the parentLayout, but it won't work for the first question. So better stick to it. 

现在膨胀所需的xml布局。并将其添加到contentLayout。

RelativeLayout layout=(RelativeLayout)View.inflate(R.layout.content,null); 
contentLayout.addView(layout);//Assuming you've done the findViewById on this. 

当您需要显示其他内容xml时,只需调用以下代码即可。

contentLayout.removeAllView(); 
RelativeLayout layout2=(RelativeLayout)View.inflate(R.layout.other_content,null); 
contentLayout.addView(layout2); 
+0

嗨,听起来很好的解决方案,你可以请更具体的代码。谢谢。 (至少第一个,希望也是我的第二个问题的答案) – 2012-03-05 09:58:56

+0

我已经更新了我的答案,有完整的代码,但由于我的懒惰,我已经省略了一些明显的东西。我希望你能填补它们。 – noob 2012-03-05 10:13:02