代码之家  ›  专栏  ›  技术社区  ›  Ibanez1408

如何在Kotlin中以编程方式设置TextInputItemText中的边距

  •  0
  • Ibanez1408  · 技术社区  · 4 年前

    val input = TextInputEditText(context!!)
                input.gravity = Gravity.CENTER
                CommonHelper.capitalizeTextbox(input)
                input.inputType =
                    InputType.TYPE_CLASS_TEXT
                input.setSingleLine()
                input.gravity = Gravity.CENTER
    
                val lp: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
    
                input.layoutParams = lp
                setMargins(input, 50,10,50,10)
                alertDialog.setView(input)
                alertDialog.setIcon(R.drawable.ic_plate)
    
    
    private fun setMargins(view: View, left: Int, top: Int, right: Int, bottom: Int) {
        if (view.layoutParams is MarginLayoutParams) {
            val p = view.layoutParams as MarginLayoutParams
            p.setMargins(left, top, right, bottom)
            view.layoutParams = p
            view.invalidate()
        }
    }
    

    我试过了 lp.setMargins(50, 10, 50, 10) 但它也不起作用

    0 回复  |  直到 4 年前
        1
  •  1
  •   Mohit Ajwani    4 年前

    通过在屏幕上设置边距,您的做法是正确的 layoutParams . 这里缺少的是您必须将布局参数应用回 view invalidate() .

    那么你的 setMargins

    private fun setMargins(view: View, left: Int, top: Int, right: Int, bottom: Int) {
        if (view.layoutParams is ViewGroup.LayoutParams) {
            val p = view.layoutParams
            p.setMargins(left, top, right, bottom)
            // Set the layout params back to the view
            view.layoutParams = p
            // Call invalidate to redraw the view
            view.invalidate()
        }
    }
    

    如果检查 MarginLayoutParams 实例检查将不满足,因为您的参数为 LinearLayoutParams 类型

    enter image description here