Oval shape clipped when created programmatically

后端 未结 5 1972
逝去的感伤
逝去的感伤 2020-12-31 21:16

I\'ve got a clipping problem.

First, I tried to display an oval shape with Xml only. I had the following code:

res/drawable/circle.xml



        
5条回答
  •  感情败类
    2020-12-31 22:09

    I experienced the same exact issue. This probably happens because of a bug in Android. The solution is to set the parent View's padding to some value, then set it back to the desired value at some point in the future.

    // set stroke properties programmatically
    viewWithStroke.background
            .let {it as GradientDrawable}
            .setStroke(newBorderThickness,newBorderColor)
    
    // set padding to some value now, then to the desired value later as a
    // work-around for the weird android bug where strokes get clipped because
    // android is not refreshing the view layouts properly
    val parentOfViewWithStroke = viewWithStroke.parent.let {it as ViewGroup}
    parentOfViewWithStroke.setPadding(
            newBorderPadding+1,newBorderPadding+1,
            newBorderPadding+1,newBorderPadding+1)
    viewWithStroke.post()
    {
        parentOfViewWithStroke.setPadding(
                newBorderPadding,newBorderPadding,
                newBorderPadding,newBorderPadding)
    }
    

    P.S.: I tried using View.invalidate() and View.requestLayout() but could not get it to work.

提交回复
热议问题