Let's say I have two buttons in a RelativeLayout
. A button labeled "one" at the top and a button labeled "three" underneath "one". The layout is defined like this.
<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>
So I wrote some code in the onCreate
of MainActivity
to dynamically create a Button
, and insert it in between one and three. But it isn't working. Is there something I'm missing? I created this question as a simplified version of a bigger problem I'm having, so it's not acceptable for me to clear the layout and just insert one two and three dynamically.
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);
}