Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position a Button in a RelativeLayout through code?

Tags:

android

layout

< RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
        < Button android:text="Previous" 
            android:layout_height="wrap_content" 
            android:id="@+id/MeasurePrev"           
            android:layout_alignParentBottom="true"
            android:layout_width="wrap_content">
        < / Button>
< / RelativeLayout >

Can anyone tell me how can i do this using Java code or in activity class? I do not know how to set android:layout_alignParentBottom="true". I want to implement whole view via java code.

like image 497
Nishant Shah Avatar asked Jul 27 '10 06:07

Nishant Shah


People also ask

How do I center a button in RelativeLayout?

If you have a single Button in your Activity and you want to center it the simplest way is to use a RelativeLayout and set the android:layout_centerInParent=”true” property on the Button.

What is the default placement of objects in a RelativeLayout?

By default, all child views are drawn at the top-left of the layout, so you must define the position of each view using the various layout properties available from RelativeLayout.

How do I use RelativeLayout code in android?

Navigate to the app > res > layout > activity_main. xml and add the below code to that file. Below is the code for the activity_main. xml file.


1 Answers

Here is a dynamic equivalent of your code :

    RelativeLayout rl = new RelativeLayout(this);
    LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    rl.setLayoutParams(params);
    Button button = new Button(this);
    button.setText("Previous");
    LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    button.setLayoutParams(params1);
    rl.addView(button);
like image 89
Sephy Avatar answered Sep 28 '22 14:09

Sephy