Finding import and dependency with Android Studio - android

I am trying to use imageResource in an Android Jetpack Compose app but I cannot find the depndency to add to my grade file.
imageResource is in the docs here:
androidx.compose.ui.res
Image(
bitmap = imageResource(id = R.drawable.background),
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
When I add androidx.compose.ui.res to my grade file it fails to resolve.
How do I find the dependency to add to my grade file for immageresouzrce?

No dependency, the link you posted clearly states the method is accessible though ImageBitmap.Companion.imageResource(...), so that is what it is.
Type the exact phrase and you'll be good.
Explicitly using the Companion property is not necessary, you could directly use ImageBitmap.imageResource(...) here as well.

Related

PainterResource throws IllegalArgumentException: Only VectorDrawables and rasterized asset types are supported

I am working on a Jetpack Project which downloads an image from API using Coil Library.
I have confirmed that valid image URLs and related data are being returned from the API call successfully. I am able to view the image on my browser using the returned URL.
This is my Image Composable:
#Composable
fun AstroPhoto(picture: AstroPicture) {
val imgUrl = picture.url.toUri()
.buildUpon()
.scheme("https")
.build()
AsyncImage(model = ImageRequest.Builder(LocalContext.current)
.data(imgUrl)
.size(Size.ORIGINAL)
.crossfade(true).build(),
placeholder = painterResource(R.drawable.loading_animation),
contentDescription = picture.title,
contentScale = ContentScale.Crop,
)
}
I call the above image composable in a Lazy Column:
....
Box( ... ) {
LazyColumn(content = {
items(state.astroPictures) {
AstroPhoto(picture = it)
} })
}
This is the exception at I am getting:
FATAL EXCEPTION: main Process: com.uxstate, PID: 31790
java.lang.IllegalArgumentException: Only VectorDrawables and
rasterized asset types are supported ex. PNG, JPG
at androidx.compose.ui.res.PainterResources_androidKt.loadVectorResource(PainterResources.android.kt:93)
I am on compose_version = '1.1.1' working with kotlin_version = '1.6.10'. My coil version is "io.coil-kt:coil-compose:2.1.0" and compileSdk 32 and AS Chipmunk. Source code can be found here.
I have checked the docs and searched online but cannot resolve the error. Please help me to go about the error, Thanks.
if you are using png and jpg with painterResource but still face this issue. Change your image, It happened when there is something wrong with the image.
painterResource converts png, and jpg in the bitmap. Its throws that error if it fails to convert any Resource
My project worked correctly before, but after I changed some code (just add a fucntion, it is not about png or jpg or other things about image), my app crash when render a png. But after i reinstall the project in the emulator, it is fixed.
It seems like a bug in Compose? I dont know, may be a bug in gradle?
Just try to reinstall your app, i think it will be fixed.
in my previous projects, there is no problem passing drawable resources to painterResource function. But when I create a new jetpack-compose project, the problem you describe occurs.
In my new project, this problem only happens in preview phase. When I firstly build and run my app in emulator, the problem suddenly disappears.
so this is my solution: if you haven't run you app in emulator, build and run it in emulator.
Just encountered this error and see if anyone had the same error as me.
I just re-opened the Android Studio, and after that, I use Clean Project and Rebuild Project. Now the project and the compose preview are working fine.
Tried to use shape drawable as a placeholder and it caused this error.
If I set the same placeholder to ImageRequest.Builder instead, the code works fine.
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(imageUrl)
.placeholder(R.drawable.placeholder_rect)
.error(R.drawable.placeholder_rect)
.build(),
contentDescription = "",
)

Android jetpack compose - Drawable colors

I am having the following issue. I am adding some vector drawable images in my project which is built using Jetpack compose. I am overriding the colors of the drawable by setting
android:fillColor="?colorPrimary"
But, the previous solution, even though it works on a usual Android project, when working on Jetpack compose it is not.
Of course, I have initialized a Material Theme with my colors/typo/shapes.
Any suggetions?
Best regards!
I've run into similar issues where compose doesn't play well with attributes. It prefers to access via colorResource(R.color.colorName).
What you might be looking for is either of the below implementations:
Icon(
Icons.Filled,
"contentDescription",
tint = MaterialTheme.colors.secondary
)
Image(
painter = painterResource(R.drawable.resourceName),
contentDescription = "contentDescription",
colorFilter = ColorFilter.tint(Color.myColor)
)
UPDATE:
I actually found something similar with font attributes. You might want to try something like this:
fun getFontFromAttribute(resId: Int, context: Context): Typeface? =
context.obtainStyledAttributes(R.style.MYSTYLE, intArrayOf(resId))
.use { array ->
val resource = array.getResourceId(array.getIndex(0), 0)
if (resource == 0) {
null
} else {
ResourcesCompat.getFont(context, resource) ?: Typeface.SANS_SERIF
}
}

Unresolved reference for Modifier.preferredSize and Modifier.prefferredHeight [closed]

I am following this YouTube Tutorial where they are using Modifier.preferredSize() on a box and Modifier.preferredHeight() on a Spacer Composable - all other chained Modifiers are fine.
However Android Studio is not recognizing these 2 options.
Here is the code that I am working with:
Column() {
var isBlue by remember { mutableStateOf(false) }
val color = if(isBlue) Color.Blue else Color.Green
Button(onClick = { isBlue = !isBlue }) {}
Spacer(modifier = Modifier.preferredHeight(128.dp))
Box(modifier = Modifier.preferredHeight(128.dp).background(color = color)){}
}
The Editor is high-lighting preferredHeight as unresolved.
This is the image from the IDE for perspective.
I am using compose_version = '1.0.1' and I'm on AS Arctic Fox
preferredSize was renamed to size and preferredHeight to height
If I face some old video/article with invalid api, I'm searching through compose-samples(official samples from the maintainers) commits to find place where this method was deprecated/renamed, it's the easiest way to know if it just was renamed or I need to change more logic. In this case change was on this commit
Modifier.preferredWidth/preferredHeight/preferredSize were renamed to width/height/size starting from 1.0.0-beta01
I resolved it by following the mouse over suggestion, pressing the alt+Enter to import automatically the required referenced packages
I am following the lessons for andoid and kotlin and had stacked with this error.

Set Drawable instance to Image in Jetpack Compose

In Jetpack Compose, who can tell me is there a way to assign a Drawable Object to the Image compose view?
I took the apps installed on an Android device. I get an icon with the type that is Drawable and I want to use it in Image
val icon: Drawable = packageInfor.applicationInfo.loadIcon(packageManager)
I found there are 3 functions that can assign images
From Painter (IdRes)
From ImageBitmap
From ImageVector
From all that I don't know how to assign a Drawable instance.
After all, I found a simple solution with Accompanist. Thanks to #Sinner of the System for suggesting to me.
Adding this dependency to the app gradle.
implementation "com.google.accompanist:accompanist-drawablepainter:<version>" //0.28.0
Using:
Image(
painter = rememberDrawablePainter(drawable = drawable),
contentDescription = "content description",
)
Check out: Drawable Painter¶
Edit: You should definitely use the accompanist library as recommended in the Wilson Tran answer. Since it provides support for several kinds of drawables.
If you're not using the accompanist library, you can do the following...
ContextCompat.getDrawable(LocalContext.current, R.mipmap.ic_launcher)?.let {
Image(bitmap = it.toBitmap().asImageBitmap(), contentDescription = null)
}
You can set the drawable size in toBitmap function if you want...
If you're using the Coil library, rememberImagePainter will accept an Any? as its data argument, which includes support for Drawable instances. I'm using this as an all-in-one solution for my images rather than importing Accompanist.
Image(
painter = rememberImagePainter(data = myDrawableInstance)
)
You can do like that
val backgroundImage = painterResource(R.drawable.your_image)
and then pass this to your image like that
Image(painter = backgroundImage, contentDescription = null)
That will work.

Android Jetpack Compose Icons doesn't contain some of the material icons

There're many oft-used material icons in androidx.compose.material.icons.Icons but some are missing. Just as an example there is no print icon.
...
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu // ok
import androidx.compose.material.icons.filled.Print // error, unresolved reference
#Composable
fun IconsExample() {
Icon(Icons.Filled.Menu, "menu") // ok
Icon(Icons.Filled.Print, "print") // error, unresolved reference
}
What is the simplest way to use those missing icons in an app?
There's a separate dependency material-icons-extended which contains the full list of material icons, just add it into your app's build.gradle
dependencies {
...
implementation "androidx.compose.material:material-icons-extended:$compose_version"
}
Now you can use any material icon, for example:
...
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu // ok
import androidx.compose.material.icons.filled.Print // ok
#Composable
fun IconsExample() {
Icon(Icons.Filled.Menu, "menu") // ok
Icon(Icons.Filled.Print, "print") // ok
}
A note about the artifact size: Since the artifact contains all material icons for multiple themes, it's a pretty big dependency, 18MB aar as of 1.0.0-alpha10. There's a note on maven repository that recommends not to use it directly:
This module contains all Material icons. It is a very large dependency and should not be included directly.
Сonsidering that most Android projects enable code shrinking for release builds, such a large dependency won't affect the release build size but it can affect your debug build and device upload time, though I'm not sure that the influence would be significant. Actually many of compose samples use this dependency.
If only a few additional icons are required and you decided not to use material-icons-extended artifact, the icons can be easily added into your project resources using Android Studio. You can use such resource-icons like this:
...
import com.mycompany.myproject.R
import androidx.compose.ui.res.painterResource
#Composable
fun ResourceIconExample() {
Icon(
painter = painterResource(R.drawable.ic_baseline_print_24),
contentDescription = "print"
)
}
I will add to previous comment that you can use not only painterResource but ImageVector. That way you can use the same type parameter in composable functions.
ImageBitmap vs ImageVector
val imageVector = ImageVector.vectorResource(id = R.drawable.baseline_shopping_cart_24)

Categories

Resources