假设我在RelativeLayout
中有两个按钮。顶部标有“one”的按钮和“one”下面标有“三”的按钮。布局是这样定义的。 RelativeLayout在两个人之间插入视图
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/mainContainer"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvOne"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:text="One" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvThree"
android:layout_centerHorizontal="true"
android:layout_below="@id/tvOne"
android:text="Three" />
</RelativeLayout>
所以我写了一些代码的MainActivity
的onCreate
动态创建Button
,以及一个和三个之间插入进去。但它不起作用。有什么我失踪?我将这个问题作为我遇到的更大问题的简化版本创建,因此我无法清除布局,只需动态插入一个二和三个。
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button one = (Button)findViewById(R.id.tvOne);
Button three = (Button)findViewById(R.id.tvThree);
//Dynamically create a button, set it underneath one and above two.
Button two = new Button(this);
two.setText("TWO TWO TWO TWO TWO TWO TWO");
//Create some layout params so that this button is horizontally centered,
//above button number three and below button number one
final int WC = RelativeLayout.LayoutParams.WRAP_CONTENT;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WC, WC);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, one.getId());
params.addRule(RelativeLayout.ABOVE, three.getId());
two.setLayoutParams(params);
//Add button number two to the activity.
RelativeLayout rl = (RelativeLayout)findViewById(R.id.mainContainer);
rl.addView(two);
}
其中第三个按钮让现在加入.. –
你不改变三个按钮的LayoutParams ..所以它总是有效的“机器人:layout_below =” @ ID/tvOne“” 。 – fasteque
可能这可以对你有所帮助: http://stackoverflow.com/questions/12524589/how-can-we-add-buttons-at-dynamic-positions-in-layout –