在OnCreate()中,我按如下方式初始化mRelLayout:
mRelLayout = (RelativeLayout) findViewById(R.id.relative_layout);
稍后,我尝试在屏幕底部放置一个动态创建的按钮:
RelativeLayout.LayoutParams layoutParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
mRelLayout.addView(dynamicallyCreateButton);
我正在使用以下布局XML文件:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:id="@+id/tv_intro1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="@string/intro1" />
<Button android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_intro1"
android:layout_centerHorizontal="true"
android:text="@string/button_label" />
<TextView android:id="@+id/tv_label1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_1"
android:text="" />
<TextView
android:id="@+id/tv_content1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_label1"
android:text="" />
<TextView android:id="@+id/tv_label2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_content1"
android:text="" />
<TextView android:id="@+id/tv_content2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_label2"
android:text="" />
</RelativeLayout>
</ScrollView>
问题是dynamicallyCreateButton
始终显示在屏幕顶部,而不是我想要的底部。
我做错了什么?
答案 0 :(得分:5)
你遗失了一些东西:
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(/*...*/);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
dynamicallyCreateButton.setLayoutParams(layoutParams); // <== missing line
mRelLayout.addView(dynamicallyCreateButton);