Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - positioning views programmatically

I want to figure out how to position views programmatically in android. Lets say for example we have this XML code.

<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:id="@+id/mainLayout">
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="121dp"
    android:layout_marginTop="140dp"
    android:text="Results" /></RelativeLayout>

How can I achieve this layout programmatically in android? because I want to have a random position of my textview.

like image 550
xknozi Avatar asked Oct 16 '12 07:10

xknozi


People also ask

How to change position of view programmatically in android?

Change the view position with ObjectAnimatorObjectAnimator animation = ObjectAnimator. ofFloat(view, "translationX", 100f); animation. setDuration(2000);

How to set view position in android studio?

This example demonstrates how do I set the absolute position of a view in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

use the RelativeLayout.LayoutParams with the setLayoutParams Method of the TextBox

RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams)textView1.getLayoutParams();
p.leftMargin = xxx; // in PX
p.topMargin = xxx; // in PX
textView1.setLayoutParams(p)

look up dp to px conversion if u want to use dp values

like image 140
x4rf41 Avatar answered Oct 17 '22 12:10

x4rf41