【问题标题】:Android - positioning views programmaticallyAndroid - 以编程方式定位视图
【发布时间】:2018-04-01 22:53:26
【问题描述】:

我想弄清楚如何在 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 中以编程方式实现此布局?因为我想要我的文本视图的随机位置。

【问题讨论】:

    标签: android textview


    【解决方案1】:

    使用 RelativeLayout.LayoutParams 和 TextBox 的 setLayoutParams 方法

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

    如果您想使用 dp 值,请查看 dp 到 px 的转换

    【讨论】:

    • 给你,希望对你有帮助
    【解决方案2】:

    检查一下..

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2015-09-11
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      相关资源
      最近更新 更多