以编程方式设置按钮和textView的权重

时间:2020-04-25 21:02:29

标签: android kotlin

我正在创建一个基本的待办事项应用程序,当调用事件addRow时,我想以编程方式在下面添加XML布局(包含文本和按钮的新行) 如何以编程方式创建以下布局?

    <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/main_table"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintHorizontal_bias="0.466"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/ll_component_container">

        <TableRow
                android:layout_width="match_parent"
                android:layout_marginTop="30dp"
                android:id="@+id/tab1"
                android:weightSum="5"
                android:layout_height="84dp">
            <TextView
                    android:id="@+id/textView1"
                    android:layout_width="fill_parent"
                    android:layout_weight="4"
                    android:paddingLeft="20dp"
                    android:textColor="#FFFFFF"
                    android:layout_height="wrap_content"
                    android:text="Value1"
                    android:textAppearance="?android:attr/textAppearanceSmall"/>
            <Button
                    android:text="Remove"
                    android:background="#fc032c"
                    android:layout_marginRight="20dp"
                    android:layout_weight="1"
                    android:layout_height="40dp" android:id="@+id/button1"/>
        </TableRow>
    </TableLayout>

我已经尝试过了,但是我既找不到如何更改粗细也不能更改按钮marginRight。

   private fun addRow(content: Editable) {
        val tl = findViewById<TableLayout>(R.id.main_table)
        val _id = View.generateViewId()
        val tr_head = TableRow(this)
        tr_head.id = _id
        tr_head.layoutParams = TableRow.LayoutParams(
            TableRow.LayoutParams.MATCH_PARENT,
            84,
            5f
        )

        val label = TextView(this)
        label.id = View.generateViewId()
        label.text = content
        label.setTextColor(Color.WHITE)
        label.setPadding(20, 0,0,0)
        tr_head.addView(label)

        val btn = Button(this)
        btn.id = _id + 1
        btn.setBackgroundColor(Color.RED)
        btn.setText("Remove")

        tr_head.addView(label)
        tr_head.addView(btn)

        tl.addView(
            tr_head, TableLayout.LayoutParams(
                TableRow.LayoutParams.MATCH_PARENT,
                TableRow.LayoutParams.WRAP_CONTENT
            )
        )
    }

1 个答案:

答案 0 :(得分:0)

我找到了另一种方法来完成我想要的事情,所以我没有使用重量,而是使用屏幕宽度来获得相对宽度。为了增加边距,我只是在包含按钮和文本的行之前添加了一个空行。这是有兴趣的完整代码。

QWidget
相关问题