如何设置marginTop?

时间:2019-05-02 02:43:40

标签: android kotlin android-constraintlayout

我已经将Textview添加到constraint-layout2.0.0-alpha4。我已将marginTop设置为约800dp,但未应用。 但是当我使用constraint-layout1.1.3时,它可以工作。

val textView = TextView(this)         textView.id = View.generateViewId()

    val set = ConstraintSet()
    mConstraintLayout.addView(textView)
    set.clone(mConstraintLayout)
    set.connect(textView.id, ConstraintSet.TOP, mConstraintLayout.id, ConstraintSet.TOP, 0)
    set.connect(textView.id, ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 0)
    set.applyTo(mConstraintLayout)

    val params = textView.layoutParams as ConstraintLayout.LayoutParams
    params.height = resources.getDimensionPixelSize(R.dimen.defaulHeight)
    params.width = resources.getDimensionPixelSize(R.dimen.defaulWidth)

    when (shapeType) {
        type_Square -> {
            textView.background = resources.getDrawable(R.drawable.image_square)
            textView.text = "Add description"
        }
        type_Circle -> {
            textView.background = resources.getDrawable(R.drawable.imagecircle)
            textView.text = "Add description"
        }
        type_LineH -> {
            textView.background = resources.getDrawable(R.drawable.image_line_h)
            params.height = resources.getDimensionPixelSize(R.dimen.defaulSelectionLine)
        }
        type_LineV -> {
            textView.background = resources.getDrawable(R.drawable.image_line_v)
            params.width = resources.getDimensionPixelSize(R.dimen.defaulSelectionLine)
        }
        else -> {
        }
    }

    val displayMetrics = resources.displayMetrics
    val width = displayMetrics.widthPixels
    val height = displayMetrics.heightPixels

    params.setMargins(
        (width - params.width) / 2,
        height - resources.getDimensionPixelSize(R.dimen.defaulBottomMargin),
        0,
        0
    )


    textView.layoutParams = params
    textView.gravity = Gravity.CENTER

    textView.setOnTouchListener(MyTouchListener())
    mConstraintLayout.setOnDragListener(MyDragListener())

    setCurrentView(textView)

0 个答案:

没有答案