Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android-以编程方式定位视图_Android_Textview - Fatal编程技术网

Android-以编程方式定位视图

Android-以编程方式定位视图,android,textview,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

我想弄清楚如何在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>

如何在android中以编程方式实现此布局?因为我想有一个我的文本视图的随机位置

与文本框的setLayoutParams方法一起使用

RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams)textView1.getLayoutParams();
p.leftMargin = xxx; // in PX
p.topMargin = xxx; // in PX
textView1.setLayoutParams(p)
如果要使用dp值,请查找dp到px的转换,请选中此项

    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);

给你,我希望这有帮助