Issue
I have a custom view named FloorView. I want this Floor view to be occupying the whole screen, and I need this dynamically (maybe match_parent). I don't want to hard code the size of the view.
I've tried doing this in FloorView.kt
private val rectangle = RectF(
ViewGroup.LayoutParams.MATCH_PARENT.toFloat(),
ViewGroup.LayoutParams.MATCH_PARENT.toFloat(), 0f, 0f)
I was thinking I could use the match_parent attribute, and match the ConstraintLayout of my MainActivity, but that didn't work, nothing was drawn, possibly because the ConstraintLayout doesn't exist yet
My code for the FloorView.kt is this
class FloorView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL_AND_STROKE
color = Color.BLACK
}
private val rectangle = RectF(
ViewGroup.LayoutParams.MATCH_PARENT.toFloat(),
ViewGroup.LayoutParams.MATCH_PARENT.toFloat(), 0f, 0f)
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas!!.drawRect(rectangle, paint)
}
}
Ladies and gentlemen, how can I make a custom view occupy all available screen space? (like match_parent)
Solution
You can do something like:
class FloorView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val displayMetrics by lazy { Resources.getSystem().displayMetrics }
private val deviceWidth by lazy { (displayMetrics.widthPixels).toFloat() }
private val deviceHeight by lazy { (displayMetrics.heightPixels).toFloat() }
// you can also use this.width & this.Height if this view already
// added in a ViewGroup via XML
private val rectangle by lazy { RectF(0f, 0f, deviceWidth, deviceHeight) }
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL_AND_STROKE
color = Color.BLACK
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas!!.drawRect(rectangle, paint)
}
}
Answered By - DarShan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.