Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

textview - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...