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.
Change the view position with ObjectAnimatorObjectAnimator animation = ObjectAnimator. ofFloat(view, "translationX", 100f); animation. setDuration(2000);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With