Mapbox Fixed Location in Android - android

How do I show a location marker for a fixed location? All am getting from the docs is user location or current location. The task I want to achieve is to get coordinates of a certain location and have a marker appear at that particular location.
Below is the code I tried with but the marker appears somewhere else:
package com.show.show_map
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import com.mapbox.geojson.Point
import com.mapbox.maps.MapView
import com.mapbox.maps.Style
import com.mapbox.maps.plugin.annotation.annotations
import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions
import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager
import okhttp3.logging.HttpLoggingInterceptor
class AbsaLocationActivity : AppCompatActivity() {
private var mapView: MapView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_absa_location)
val BASIC = "mapbox://styles/stunupps/cl2f3q6b1002d14o6wpu3m6bq"
mapView = findViewById(R.id.mapView)
mapView?.getMapboxMap()?.loadStyleUri(
HttpLoggingInterceptor.Level.BASIC,
object : Style.OnStyleLoaded {
override fun onStyleLoaded(style: Style) {
addAnnotationToMap()
}
}
)
}
private fun addAnnotationToMap() {
// Create an instance of the Annotation API and get the PointAnnotationManager.
bitmapFromDrawableRes(
this#AbsaLocationActivity,
R.drawable.red_marker
)?.let {
val annotationApi = mapView?.annotations
val pointAnnotationManager = annotationApi?.createPointAnnotationManager()
// Set options for the resulting symbol layer.
val pointAnnotationOptions: PointAnnotationOptions = PointAnnotationOptions()
// Define a geographic coordinate.
.withPoint(Point.fromLngLat(-15.39, 28.31))
// Specify the bitmap you assigned to the point annotation
// The bitmap will be added to map style automatically.
.withIconImage(it)
// Add the resulting pointAnnotation to the map.
pointAnnotationManager?.create(pointAnnotationOptions)
}
}
private fun bitmapFromDrawableRes(context: Context, #DrawableRes resourceId: Int) =
convertDrawableToBitmap(AppCompatResources.getDrawable(context, resourceId))
private fun convertDrawableToBitmap(sourceDrawable: Drawable?): Bitmap? {
if (sourceDrawable == null) {
return null
}
return if (sourceDrawable is BitmapDrawable) {
sourceDrawable.bitmap
} else {
// copying drawable object to not manipulate on the same reference
val constantState = sourceDrawable.constantState ?: return null
val drawable = constantState.newDrawable().mutate()
val bitmap: Bitmap = Bitmap.createBitmap(
drawable.intrinsicWidth, drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
bitmap
}
}
}

Related

What is wrong with my code. I am unable to draw on the screen

I have checked my code several times and don't know where is it going wrong. i am trying to build a drawing app and after doing all this code I am unable to get any output. Not able to draw on the canvas.
please help me get rid of this issue.
This is my DrawingView.kt
package com.example.drawingapp
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.res.ResourcesCompat
class DrawingView(context : Context, attrs:AttributeSet): View(context, attrs){
private var myDrawPath: CustomPath? = null
private var myCanvasBitmap: Bitmap? = null
private var myDrawPaint: Paint? = null
private var myCanvasPaint: Paint? = null
private var myCanvas: Canvas?= null
private var myBrushSize :Float = 0.toFloat()
private var myColor = Color.BLACK
init{
drawingSetUp()
}
private fun drawingSetUp(){
myDrawPaint = Paint()
myDrawPath = CustomPath(myColor,myBrushSize)
myDrawPaint!!.color= myColor
myDrawPaint!!.style = Paint.Style.STROKE
myDrawPaint!!.strokeJoin =Paint.Join.ROUND
myDrawPaint!!.strokeCap =Paint.Cap.ROUND
myCanvasPaint= Paint(Paint.DITHER_FLAG)
myBrushSize=20.toFloat()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
myCanvasBitmap= Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
myCanvas = Canvas(myCanvasBitmap!!)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
myCanvas!!.drawBitmap(myCanvasBitmap!!, 0f,0f , myCanvasPaint)
if (!myDrawPath!!.isEmpty){
myDrawPaint!!.strokeWidth = myDrawPath!!.brushThickness
myDrawPaint!!.color= myDrawPath!!.color
myCanvas!!.drawPath(myDrawPath!!, myDrawPaint!!)
}
}
#SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
val touchX = event?.x
val touchY = event?.y
when (event?.action) {
MotionEvent.ACTION_DOWN -> {
myDrawPath!!.color = myColor
myDrawPath!!.brushThickness = myBrushSize
myDrawPath!!.reset()
if (touchX != null) {
if (touchY != null) {
myDrawPath!!.moveTo(touchX, touchX)
}
}
}
MotionEvent.ACTION_MOVE -> {
if (touchX != null) {
if (touchY != null) {
myDrawPath!!.lineTo(touchX, touchY)
}
}
}
MotionEvent.ACTION_UP->{
myDrawPath = CustomPath(myColor, myBrushSize)
}
else->return false
}
invalidate()
return true
}
internal inner class CustomPath(var color:Int, var brushThickness:Float): Path(){
}
}
This is my activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.drawingapp.DrawingView
android:id="#+id/drawing_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
And this is my MainActivity.kt file
package com.example.drawingapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
You're drawing to the wrong Canvas. You need to draw to the one passed in to onDraw, that's the one linked to what your View will actually display.
When you do this:
myCanvasBitmap= Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
myCanvas = Canvas(myCanvasBitmap!!)
you're creating your own, personal Bitmap, and creating your own personal Canvas to draw stuff on that bitmap. You can do that - but unless you draw that bitmap to the canvas onDraw gives you at some point, you'll never see it.
I'm assuming you wanted to do this:
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// draw your stored bitmap to the view's canvas
canvas.drawBitmap(myCanvasBitmap!!, 0f,0f , myCanvasPaint)
if (!myDrawPath!!.isEmpty){
myDrawPaint!!.strokeWidth = myDrawPath!!.brushThickness
myDrawPaint!!.color= myDrawPath!!.color
// draw this stored path to the view's canvas, on top of
// the stored bitmap you just drew
canvas.drawPath(myDrawPath!!, myDrawPaint!!)
}
}
i.e. drawing to canvas and not myCanvas. I don't know where you're actually drawing stuff to myCanvas though (to build up your stored image), you still need to do that so you have something to paint on the view's canvas. I'm assuming that happens elsewhere and the path you're drawing in onDraw is like a temporary overlay that isn't part of the stored image yet
Also just as a piece of advice, you need to avoid that !! stuff everywhere - that's a big sign you've made something nullable that shouldn't be nullable, and now you have to fight with the null-checking system because you're sure it can't be null but the system thinks it could be.
If you just move all your drawingSetup code into init, it'll see that you're assigning everything a value and you won't need to make them null. It's because you're assigning them through another function called from init that it can't be sure you're doing that - it's a limitation of the language unfortunately. Or you could just assign them directly:
private var myDrawPath = CustomPath(myColor,myBrushSize)
private lateinit var myCanvasBitmap: Bitmap
private var myDrawPaint = Paint().apply {
color= myColor
style = Paint.Style.STROKE
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
}
// etc
If you do want to keep that initialisation function (e.g. because you want to reset everything to normal) at least make your vars lateinit non-nullable types - if they're never going to be null when they're accessed, don't make them nullable! You just have to make sure lateinit stuff is assigned a value before something tries to read it - but the same is true for making something null and doing !! every time you access it, aka "trust me bro it's not null"

I Have Several Problems In Gson Library in (Jetpack Compose)

Hello Stackoverflow community
I Would like to fetch data from this Rest Api:
https://adeega.xisaabso.online/Api/android_today_dashboard.php
but unfortunately i have several problems in my application
so how can i solved, i am new in jetpack compose
here are my problems:
No value passed for parameter 'Amaahda'
No value passed for parameter 'Expenses'
No value passed for parameter 'Lacagta_La_dirayo'
No value passed for parameter 'Total'
No value passed for parameter 'Amaahda'
None of the following functions can be called with the arguments supplied
build gradle
implementation("com.android.volley:volley:1.2.1")
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
DashBoardItems Class
package com.example.eee.Classes
data class DashBoardItems(
val Amaahda: Float,
val Expenses: Float,
val Lacagta_La_dirayo: Float,
val Total: Float
)
DashBoardScreen.kt
package com.example.eee.Screens
import android.widget.Toast
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.eee.Cards.DashBoardText
import com.example.eee.Classes.DashBoardItems
import com.google.gson.GsonBuilder
#Composable
fun DashBoard_Screen(navController: NavController){
val context = LocalContext.current
val baseUrl = "https://adeega.xisaabso.online/Api/android_last_vouchers.php"
val dashBoardItems_data = DashBoardItems()
val data = remember {
mutableStateOf<DashBoardItems>(DashBoardItems())
}
val stringRequest = StringRequest(baseUrl, { it ->
val gsonBuilder = GsonBuilder()
val gson = gsonBuilder.create()
gson.fromJson(it, DashBoardItems::class.java)
data.value = dashBoardItems_data
}, {
Toast.makeText(context, it.toString(), Toast.LENGTH_SHORT).show()
}).apply {
DashBoardText(data = data.value)
}
val volleyRequest = Volley.newRequestQueue(context)
volleyRequest.add(stringRequest)
}
DashBoardText Composable
package com.example.eee.Cards
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import com.example.eee.Classes.DashBoardItems
#Composable
fun DashBoardText(data: DashBoardItems){
Text(text = data.Total.toString())
Text(text = data.Amaahda.toString())
}
In those two places, you are calling DashBoardItems constructor without any argument, but it requires 4 of them:
val dashBoardItems_data = DashBoardItems()
val data = remember {
mutableStateOf<DashBoardItems>(DashBoardItems())
}
You can call it like DashBoardItems(0F, 0F, 0F, 0F) or specify default values in your constructor:
data class DashBoardItems(
val Amaahda: Float = 0F,
val Expenses: Float = 0F,
val Lacagta_La_dirayo: Float = 0F,
val Total: Float = 0F,
)
Another problem you will soon encounter is that you can't just call api requests from your composables like that, you will need a LaunchedEffect or better a ViewModel.

How to Parcelize a MutableList in kotlin?

I have an App that lets users drag and draw boxes on a custom view. I want to persist the state of these boxes(list of boxes) across orientation change using onSavedInstanceState(): Parcelable and onRestoreInstanceState(state: Parcelable). However, I don't know how to store a MutableList because the only available function is putParcelableArrayList. Please how do I parcelize a Mutable List to persist the boxes across rotation? I know the docs said its possible but I don't know how to. Here is the code.
#Parcelize
class Box(private val start: PointF) : Parcelable {
// When a user touches BoxDrawingView, a new box will be created and added to the list of existing boxes.
var end: PointF = start
val left: Float
get() = start.x.coerceAtMost(end.x)
val right: Float
get() = start.x.coerceAtLeast(end.x)
val top: Float
get() = start.y.coerceAtMost(end.y)
val bottom: Float
get() = start.y.coerceAtLeast(end.y)
}
My custom View
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PointF
import android.os.Bundle
import android.os.Parcelable
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
/** This Class is where we setup our custom View and write the Implementation for listening to touch events from the USER and draw boxes on the Screen.**/
private const val TAG = "BoxDrawingView"
private const val BOX_STATE = "box"
private const val VIEW_STATE = "view"
class BoxDrawingView(context: Context, attrs: AttributeSet? = null) :
View(context, attrs) {
private var currentBox: Box? = null
private var boxen = mutableListOf<Box>() // list of boxes to be drawn out on the screen
private val boxPaint = Paint().apply {
color = 0x22ff0000
}
private val backGroundPaint = Paint().apply {
color = 0xfff8efe0.toInt()
}
init {
isSaveEnabled = true
}
override fun onSaveInstanceState(): Parcelable {
val bundle = Bundle()
bundle.putParcelableArrayList(BOX_STATE, boxen) // type mismatch error because of mutableList passed to ArrayList
bundle.putParcelable(VIEW_STATE, super.onSaveInstanceState())
return bundle
}
override fun onRestoreInstanceState(state: Parcelable?) {
var viewState = state
if (viewState is Bundle) {
boxen = viewState.getParcelableArrayList<Box>(BOX_STATE)?.toMutableList() ?: mutableListOf()
viewState = viewState.getParcelable(VIEW_STATE)
}
super.onRestoreInstanceState(state)
}
override fun onDraw(canvas: Canvas) {
// Fill in the background
canvas.drawPaint(backGroundPaint)
boxen.forEach { box ->
canvas.drawRect(box.left, box.top, box.right, box.bottom, boxPaint)
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val current = PointF(event.x, event.y)
var action = ""
when(event.action) {
MotionEvent.ACTION_DOWN -> {
action = "ACTION_DOWN"
// Reset drawing state
currentBox = Box(current).also {
boxen.add(it)
}
}
MotionEvent.ACTION_MOVE -> {
action = "ACTION_MOVE"
// update the currentBox.end as the user moves his/her finger around the screen
updateCurrentBox(current)
}
MotionEvent.ACTION_UP -> {
action = "ACTION_UP"
// tells the last report of the currentBox as the user's finger leaves the screen
updateCurrentBox(current)
currentBox = null
}
MotionEvent.ACTION_CANCEL -> {
action = "ACTION_CANCEL"
currentBox = null
}
}
// this is a log message for each of the 4 Event actions
Log.i(TAG, "$action at x=${current.x}, y=${current.y}")
return true
}
Changing the boxen type to arrayList() worked. Turns out arrayList works as a mutable list under the hood. Also David wasser's answer in the comments also worked.

Comparing two VectorDrawables fails in Kaspresso - Android

I'm trying to use Kaspresso for tests and I'm checking whether a view has a certain drawable with the method:
withId<KImageView>(R.id.criticalErrorImage) {
hasDrawable(R.drawable.error_graphic)
}
With PNG works really well, while comparing the image stored in the imageView and restored and the VectorDrawable fails.
The file where the check is made is this one.
In particular this part of code:
var expectedDrawable: Drawable? = drawable ?: getResourceDrawable(resId)?.mutate()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && expectedDrawable != null) {
expectedDrawable = DrawableCompat.wrap(expectedDrawable).mutate()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tintColorId?.let { tintColorId ->
val tintColor = getResourceColor(tintColorId)
expectedDrawable?.apply {
setTintList(ColorStateList.valueOf(tintColor))
setTintMode(PorterDuff.Mode.SRC_IN)
}
}
}
if (expectedDrawable == null) {
return false
}
val convertDrawable = (imageView as ImageView).drawable.mutate()
val bitmap = toBitmap?.invoke(convertDrawable) ?: convertDrawable.toBitmap()
val otherBitmap = toBitmap?.invoke(expectedDrawable) ?: expectedDrawable.toBitmap()
The funny part is that it works if I'm setting the image through databinding, while it doesn't work if I set it in all other ways. Cannot understand why.
I've created a POC here: https://github.com/filnik/proof_of_concept
In particular, here is the test: https://github.com/filnik/proof_of_concept/blob/master/app/src/androidTest/java/com/neato/test/POCInstrumentationTest.kt
While here I dynamically set the image:
https://github.com/filnik/proof_of_concept/blob/master/app/src/main/java/com/neato/test/FirstFragment.kt
The issue was because actually the image is scaled. So the scaled image is different from the original one.
To avoid this issue I've used this "altered" KImageView:
package your_package
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.PorterDuff
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.graphics.drawable.DrawableCompat
import androidx.test.espresso.DataInteraction
import androidx.test.espresso.assertion.ViewAssertions
import com.agoda.kakao.common.assertions.BaseAssertions
import com.agoda.kakao.common.builders.ViewBuilder
import com.agoda.kakao.common.utilities.getResourceColor
import com.agoda.kakao.common.utilities.getResourceDrawable
import com.agoda.kakao.common.views.KBaseView
import com.agoda.kakao.image.KImageView
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
class KImageView2 : KBaseView<KImageView>, ImageViewAssertions2 {
constructor(function: ViewBuilder.() -> Unit) : super(function)
constructor(parent: Matcher<View>, function: ViewBuilder.() -> Unit) : super(parent, function)
constructor(parent: DataInteraction, function: ViewBuilder.() -> Unit) : super(parent, function)
}
interface ImageViewAssertions2 : BaseAssertions {
/**
* Checks if the view displays given drawable
*
* #param resId Drawable resource to be matched
* #param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null)
*/
fun hasDrawable(#DrawableRes resId: Int, toBitmap: ((drawable: Drawable) -> Bitmap)? = null) {
view.check(ViewAssertions.matches(DrawableMatcher2(resId = resId, toBitmap = toBitmap)))
}
}
class DrawableMatcher2(
#DrawableRes private val resId: Int = -1,
#ColorRes private val tintColorId: Int? = null,
private val toBitmap: ((drawable: Drawable) -> Bitmap)? = null
) : TypeSafeMatcher<View>(View::class.java) {
override fun describeTo(desc: Description) {
desc.appendText("with drawable id $resId or provided instance")
}
override fun matchesSafely(view: View?): Boolean {
if (view !is ImageView) {
return false
}
if (resId < 0) {
return view.drawable == null
}
val bitmap = extractFromImageView(view)
view.setImageResource(resId)
val otherBitmap = extractFromImageView(view)
return bitmap?.sameAs(otherBitmap) ?: false
}
private fun extractFromImageView(view: View?): Bitmap? {
return view?.let { imageView ->
var expectedDrawable: Drawable? = getResourceDrawable(resId)?.mutate()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && expectedDrawable != null) {
expectedDrawable = DrawableCompat.wrap(expectedDrawable).mutate()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tintColorId?.let { tintColorId ->
val tintColor = getResourceColor(tintColorId)
expectedDrawable?.apply {
setTintList(ColorStateList.valueOf(tintColor))
setTintMode(PorterDuff.Mode.SRC_IN)
}
}
}
if (expectedDrawable == null) {
return null
}
val convertDrawable = (imageView as ImageView).drawable.mutate()
toBitmap?.invoke(convertDrawable) ?: convertDrawable.toBitmap()
}
}
}
internal fun Drawable.toBitmap(): Bitmap {
if (this is BitmapDrawable && this.bitmap != null) {
return this.bitmap
}
if (this is StateListDrawable && this.getCurrent() is BitmapDrawable) {
val bitmapDrawable = this.getCurrent() as BitmapDrawable
if (bitmapDrawable.bitmap != null) {
return bitmapDrawable.bitmap
}
}
val bitmap = if (this.intrinsicWidth <= 0 || this.intrinsicHeight <= 0) {
Bitmap.createBitmap(
1,
1,
Bitmap.Config.ARGB_8888
) // Single color bitmap will be created of 1x1 pixel
} else {
Bitmap.createBitmap(this.intrinsicWidth, this.intrinsicHeight, Bitmap.Config.ARGB_8888)
}
val canvas = Canvas(bitmap)
this.setBounds(0, 0, canvas.width, canvas.height)
this.draw(canvas)
return bitmap
}
Not the cleanest solution possible, but it works. If anyone can provide a better solution would be great :-)

Android how to add a ronuded border ImageView on AppWidget?

I am here not for looking how add border to imageView I know 10000 methods.
I am here for how add rounded border ImageView specific on HOME WIDGET.
Since currently I found no way to do this. I have tried:
Using xml shape as ImageView background, it works for TextView, but not ImageView;
I tried using Glide programatically add rounded border, but that things need a bounch of thing, and I can not make it work.
Here is current code that doesn't work:
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.SharedPreferences
import android.net.Uri
import android.widget.RemoteViews
import cn.manaai.daybreak.R
import es.antonborri.home_widget.HomeWidgetBackgroundIntent
import es.antonborri.home_widget.HomeWidgetLaunchIntent
import es.antonborri.home_widget.HomeWidgetProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.TransformationUtils
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
class HomeWidgetGlanceProvider : HomeWidgetProvider(), AppCompatActivity {
// this load a todo widget, showing todos here
// so the layout here is different.
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray, widgetData: SharedPreferences) {
appWidgetIds.forEach { widgetId ->
val views = RemoteViews(context.packageName, R.layout.glance_app_widget).apply {
// Open App on Widget Click
val pendingIntent = HomeWidgetLaunchIntent.getActivity(
context,
MainActivity::class.java)
setOnClickPendingIntent(R.id.widget_container, pendingIntent)
// Swap Title Text by calling Dart Code in the Background
setTextViewText(R.id.nickname, widgetData.getString("title", null)
?: "No Title Set")
val backgroundIntent = HomeWidgetBackgroundIntent.getBroadcast(
context,
Uri.parse("homeWidgetExample://titleClicked2")
)
setOnClickPendingIntent(R.id.nickname, backgroundIntent)
val message = widgetData.getString("message", null)
setTextViewText(R.id.todonum, message
?: "12")
// Detect App opened via Click inside Flutter
val pendingIntentWithData = HomeWidgetLaunchIntent.getActivity(
context,
MainActivity::class.java,
Uri.parse("homeWidgetExample://message?message=$message"))
setOnClickPendingIntent(R.id.todonum, pendingIntentWithData)
var avatar = findViewById(R.id.avatar) as ImageView;
// avatar
Glide.with(this).load("http://p15.qhimg.com/bdm/720_444_0/t01b12dfd7f42342197.jpg")
.apply(RequestOptions.bitmapTransform(RoundedCorners(20)))
// .circleCrop()
.into(avatar)
}
appWidgetManager.updateAppWidget(widgetId, views)
}
}
}
I simplfy want my avatar to be rounded, any idea??
PS: DO NOT SEND ME ANY JAVA CODE.
I am using kotlin only.
You need to make a bitmap from the URL. And pass that bitmap to the function that I made.
fun createRoundedImage(bitmap: Bitmap): Bitmap {
val imageRounded =
Bitmap.createBitmap(bitmap.width, bitmap.height, bitmap.config)
val canvas = Canvas(imageRounded)
val paint = Paint()
paint.isAntiAlias = true
paint.shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
canvas.drawRoundRect(
RectF(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat()),
(bitmap.width / 2).toFloat(),
(bitmap.height / 2).toFloat(),
paint
)
return imageRounded
}
Now just set the round bitmap returned by the function to your image view.

Categories

Resources