Android - 以编程方式定位视图

jep*_*nkz 6 android textview

我想弄清楚如何在android中以编程方式定位视图.让我们说例如我们有这个XML代码.

<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>
Run Code Online (Sandbox Code Playgroud)

如何在android中以编程方式实现此布局?因为我希望我的textview有一个随机的位置.

x4r*_*f41 7

RelativeLayout.LayoutParams与TextBox的setLayoutParams方法一起使用

RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams)textView1.getLayoutParams();
p.leftMargin = xxx; // in PX
p.topMargin = xxx; // in PX
textView1.setLayoutParams(p)
Run Code Online (Sandbox Code Playgroud)

如果你想使用dp值,请查找dp到px转换


小智 5

检查一下..

    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);
Run Code Online (Sandbox Code Playgroud)