解决代码动态添加TextView设置Margin不生效问题

把LinearLayout.LayoutParams改成LinearLayoutCompat.LayoutParams即可!

private fun getAddressTextView(text: String): TextView{

        val view = TextView(this)
        view.text = text
        view.textSize = 19f
        view.background = ContextCompat.getDrawable(this, R.drawable.shape_rect_large_corners_green_bg)
        view.setTextColor(ContextCompat.getColor(this, R.color.white))

        val layoutParams = LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT)
        layoutParams.setMargins(ScreenUtils.dip2px(this, 10f),0,ScreenUtils.dip2px(this, 10f),0)
        view.layoutParams = layoutParams

        view.setPadding(
            ScreenUtils.dip2px(this, 20f),
            ScreenUtils.dip2px(this, 10f),
            ScreenUtils.dip2px(this, 20f),
            ScreenUtils.dip2px(this, 10f)
        )
        return view
    }

你可能感兴趣的:(解决代码动态添加TextView设置Margin不生效问题)