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

4

2 回答 2

1

1 您可以像这样LinearLayout直接将自定义添加到MyActivity类的 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);
于 2012-03-05T09:50:41.227 回答
0

有一个 TopBar 的 Layout 空置,并通过使用添加 Your Topbarlayout.addView(topbarObject); 关于您的第二个问题,据我所知,setContentView 只能调用一次。但是,您可以在需要时将这两个 xml 文件使用View.inflate(other_content.xml)并添加到父 xml 布局中。您可以removeView()在父布局上并addView()使用新的布局文件。

编辑:对于这两个问题的解决方案,您可以有一个父布局,例如。如下所示:

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

现在在您的代码中将父布局设置为内容视图,创建一个 TopBar 布局对象并将其添加到 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);
于 2012-03-05T09:55:28.333 回答