I'm making android app with Kotlin in android studio now, and want to draw on already drawn custom view.
This app is simple app about shows graphical information with received data with serial port. Actually I'm new on Kotlin and rookie on Java/Android. This is code that has problem.
This is XML of custom view, (it is in the contraintlayout)
<!--activity_main.xml-->
<androidx.constraintlayout.widget.ConstraintLayout ... >
<com.(...).DrawUI
android:id="@+id/DrawUI" ...
/>
Trying to call drawing function 'DrawRxData(rxData)' on this thread,
//BluetoothController.kt
class BluetoothClient(private val activity: MainActivity,
private val socket:BluetoothSocket): Thread() {
override fun run() {
...
if(inputStream.available() > 0) {
...
inputStream.read(buffer)
val rxData = BluetoothRxParser(buffer)
DrawRxData(rxData)
...
}
...
}
}
And this is DrawUI that wrote above on XML I want to draw something on this View with calling function in BluetoothController.kt!
//DrawUI.kt
class DrawUI(context: Context, attrs: AttributeSet?) : View(context, attrs) {
init {
// initializing Paint()s
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
// measuring dimension and determine drawing sector
}
override fun onDraw(canvas: Canvas) {
// drawing background
}
}
I tried use Canvas on DrawUI class but it didn't work properly. Also tried making Bitmap but it occurs error that width and height are zero. How can I fix this problem?
EDIT
This way is how I solved this problem, maybe there is another and simple solution..
- Created ImageView that has same size with DrawUI on XML
<ImageView
android:id="@+id/DrawRx" ...
/>
- Get View and cast to ImageView, then create bitmap and canvas.. DrawRxData() is in BluetoothClient class.
private fun DrawRxData (rxData: RxData) {
val v : View = activity.findViewById(R.id.DrawRx)
val iv : ImageView = v as ImageView
val bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.setColor(Color.BLACK)
canvas.drawCircle(50F, 50F, 10F, paint)
- Attach bitmap to ImageView but for thread, it looks like Dispatcher in C#.. Reference
activity.runOnUiThread(java.lang.Runnable {
iv.setImageBitmap(bitmap)
})
Actually just overlapped exist view, please answer if there is efficient way!