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)
CodePudding user response:
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)
}
}
CodePudding user response:
Hi guys meniman98 doesn't want a view of "screen size", just want the view to match parent view's size. Actually "screen size" is impossible -- a view can not exceed its parent ViewGroup's size.
The question is in
private val rectangle = RectF(
ViewGroup.LayoutParams.MATCH_PARENT.toFloat(),
ViewGroup.LayoutParams.MATCH_PARENT.toFloat(), 0f, 0f)
this will not get expected size because MTACH_PARENT is just a const int to instruct the layout planner, not size.
View's size is first decided in view's onSizeChanged call, so you should override this function and create the rectangle there.
private var rectangle:RectF? = null
override fun onSizeChanged(int w, int h, int oldW, int oldH) {
rectangle = RectF(0f, 0f, w.toFloat(), h.toFloat())
}