【问题标题】:How to add a view programmatically to RelativeLayout?如何以编程方式将视图添加到 RelativeLayout?
【发布时间】:2019-01-22 16:39:53
【问题描述】:

你能给我一个非常简单的例子,以编程方式将子视图添加到给定位置的RelativeLayout

例如,要反映以下 XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="107dp"
    android:layout_marginTop="103dp"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />

我不明白如何创建合适的RelativeLayout.LayoutParams 实例。

【问题讨论】:

    标签: android android-layout android-relativelayout


    【解决方案1】:

    这是一个让您入门的示例,请根据需要填写其余部分:

    TextView tv = new TextView(mContext);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    params.leftMargin = 107
    ...
    mRelativeLayout.addView(tv, params);
    

    RelativeLayout.LayoutParams 的文档和构造函数是here

    【讨论】:

    • 抱歉,同样的问题:您从哪里了解到RelativeLayout.LayoutParams 没有Context 作为第一个参数的构造函数?
    • 啊,抱歉,我认为宽度和高度应该是精确值。
    • 我在找这个!即使我的观点似乎不适用参数...
    【解决方案2】:

    首先,你应该给你的 RelativeLayout 一个 id,比如说 relativeLayout1。

    RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relativeLayout1);
    TextView mTextView = new TextView(context);
    mTextView.setText("Dynamic TextView");
    mTextView.setId(111);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    mainLayout.addView(mTextView, params);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 2017-01-04
    相关资源
    最近更新 更多