Reputation: 3807
Hi I have my layout like so:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/BlanchedAlmond" >
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout >
I programmatically add a button like so:
ImageButton startButton = new ImageButton(this);
startButton.setBackground(getResources().getDrawable(R.drawable.startbutton));
addContentView(startButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Can anyone guide me as to how I could get the button placed at the bottom and centered. I have seen other questions that are similar but I have not been able to achieve what I am looking.
Upvotes: 2
Views: 638
Reputation: 9700
Give an id
to your RelativeLayout
as below to add new view to this layout later...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/BlanchedAlmond" >
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout >
Now, create ImageButton
and add to the activity layout as follows...
RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.layout);
ImageButton startButton = new ImageButton(this);
startButton.setImageResource(R.drawable.ic_launcher);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
rootLayout.addView(startButton, lp);
Upvotes: 2
Reputation: 6714
You can simply add rules
encapsulated with verbs
to your LayoutParams
For Example :
ImageButton startButton = new ImageButton(this);
startButton.setBackground(getResources().getDrawable(R.drawable.startbutton));
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
addContentView(startButton, lp);
I hope this helps.
Upvotes: 1