Android - positional representations programmatically

I want to figure out how to position views programmatically in android. 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 implement this layout programmatically in Android? because I want to have a random position in my text view.

+4
source share
2 answers

check this.

  RelativeLayout main = new RelativeLayout(this); main.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); TextView textV = new TextView(this); textV.setGravity(Gravity.LEFT); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(121, 140, 0, 0); textV.setLayoutParams(layoutParams); text.setText("Result "); main .addView(text); 
+4
source

use RelativeLayout.LayoutParams using the setLayoutParams method in the text box

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

Look at converting dp to px if you want to use dp values

+6
source

Source: https://habr.com/ru/post/1439983/


All Articles