在所有布局上,我有一个共同的页眉和页脚,如何在运行时更改布局?
main_latout.xml -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <include android:id="@+id/header" layout="@layout/mytask_header" android:layout_width="fill_parent" android:layout_height="60dp" android:layout_alignParentTop="true"/> <include android:id="@+id/footer" layout="@layout/mytask_footer_ads" android:layout_width="fill_parent" android:layout_height="60dp" android:layout_alignParentBottom="true"/> <RelativeLayout android:id="@+id/common_place_for_xml" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@id/header" android:layout_above="@id/footer" android:background="@android:color/darker_gray"> </RelativeLayout> </RelativeLayout>
我想更改ID为RelativeLayout
的{{1}}中的其他布局?
我是新手?请帮忙。
答案 0 :(得分:0)
不确定我是否理解你想要的东西,但我会尽力帮助。
尝试为您的外部RelativeLayout提供一个id,例如“parentLayout”,另一个名为newLayout的XML文件将替换您的“common_place_for_xml”布局。
然后在运行时尝试:
RelativeLayout parentLayout = findViewById(R.id.parentLayout);
RelativeLayout childLayout = parentLayout.findViewById(R.id.common_place_for_xml);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) childLayout.getLayoutParams();
int index = parentLayout.indexOfChild(childLayout);
parentLayout.removeView(childLayout);
RelativeLayout newLayout = findViewById(R.id.newLayout);
parentLayout.addView(newLayout, index);
newLayout.setLayoutParams(params);
答案 1 :(得分:0)
您可以在运行时向相对布局添加视图。这是一个示例:
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.common_place_for_xml);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
Button dummy = new Button(this);
dummy.setText("Hello");
dummy.setLayoutParams(params);
relativeLayout.addView(dummy);