How can I get drawable resource by string? - drawable

I have their name as String which is in drawable folder. How can I access to drawable folder and pass drawable resource to change the Icon View.
val iconList = ["ic_apple","ic_banana","ic_melon"]
and ic_apple.png, ic_banana.png, ic_melon.png in my drawable folder.
Like,
there was this with java's code.
String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
view.setBackground(drawable)

You can use LocalContext to get current context, and then use same methods as you used in view based Android:
val context = LocalContext.current
val drawableId = remember(name) {
context.resources.getIdentifier(
name,
"drawable",
context.packageName
)
}
Image(
painterResource(id = drawableId),
contentDescription = "..."
)

it will also work with the ressourceString
val context = LocalContext.current
val text = stringResource(id =
LocalContext.current.resources.getIdentifier(
"Error_verification_code",
"string",
context.packageName
))

Related

Is it possible to display animated gif in jetpack?

I'm trying to implement a gif in my splash screen using jetpack.Tried this one as suggested but no output .What am I missing?
val context = LocalContext.current
val imageLoader = ImageLoader.Builder(context)
.componentRegistry {
if (SDK_INT >= 28) {
add(ImageDecoderDecoder(context))
} else {
add(GifDecoder())
}
}
.build()
Image(
painter = rememberImagePainter(
imageLoader = imageLoader,
data = R.id.mygif,
builder = {
size(OriginalSize)
}
),
contentDescription = null,
modifier = Modifier
.padding(top = 100.dp)
)
Apparently Compose is not supporting gif out of the box, I could not find any reference to gif files in the docs. However, one of the popular library out there to deal with gifs is Coil.
-> Here is coil for Compose:
https://coil-kt.github.io/coil/compose/
-> Make sure to add the gif extension:
https://coil-kt.github.io/coil/gifs/
-> You will have to override the ImageLoader and add the gif extension:
https://coil-kt.github.io/coil/compose/#localimageloader
For those, who is still looking for answer, here is updated version (since LocalImageLoader is deprecated) in Coil.
Same steps for installation:
Add implementation for coil-compose
Add implementation for coil-gif
Usage:
#Composable
fun Content() {
val imageLoader = ImageLoader.Builder(LocalContext.current)
.components {
if (SDK_INT >= 28) {
add(ImageDecoderDecoder.Factory())
} else {
add(GifDecoder.Factory())
}
}
.build()
Image(
painter = rememberAsyncImagePainter(
ImageRequest.Builder(LocalContext.current)
.data(data = R.drawable.mettaton_battle_box)
.apply(block = fun ImageRequest.Builder.() {
size(Size.ORIGINAL)
}).build(),
imageLoader = imageLoader
),
contentDescription = null,
)
}

Layout inflater with DialogFragment

I'm trying to inflate my custom layout (a dialog fragment).
I have this in my function showDialog()
val inflatedView = layoutInflater.inflate(R.layout.alerts_dialog_remi, null)
mydialog = Dialog(this, R.style.DialogCustomTheme)
mydialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
mydialog.setContentView(R.layout.alerts_dialog_remi)
mydialog.setOnShowListener {
val text = inflatedView.findViewById<TextView>(R.id.alerte_title)
val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
text.setText("Text")}
mydialog.create()
txt = mydialog.findViewById(R.id.close_modal_alerte)
txt.isEnabled = true
txt.setOnClickListener{
mydialog.cancel()
}
mydialog.show()
}
But I don't see the "Text" string in my dialog fragment. I tried the put the inflatedView inside setOnShowListener, but it doesn't do anything either.
You don't need to inflate your view, because dialog.setContentView does just that for you.
What you need is to get the inflated view from inside your lambda.
Like this:
mydialog.setOnShowListener {
val text = it.view.findViewById<TextView>(R.id.alerte_title)

how to convert beloved android code into nativescript

i try to convert beloved code same into nativescript but i am new i have no idea for this please tell me how to convert android code to nativescript ...
private void createWebPrintJob() {
// Get a PrintManager instance
PrintManager printManager = (PrintManager)
getSystemService(Context.PRINT_SERVICE);
// Get a print adapter instance
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
// Create a print job with name and adapter instance
String jobName = getString(R.string.app_name) + " Document";
PrintJob printJob = printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
// Save the job object for later status checking
// mPrintJobs.add(printJob);
}
May be something like this,
var application = require('application');
var utils = require('utils/utils');
function createWebPrintJob() {
var printManager = application.android.context
.getSystemService(android.content.Context.PRINT_SERVICE);
var printAdapter = webView.createPrintDocumentAdapter();
var jobName = getString(utils.ad.getStringId("app_name")) + " Document";
var printJob = printManager.print(jobName, printAdapter, new namespace.to.PrintAttributes.Builder().build());
mPrintJobs.add(printJob);
}
The above is just puedo code, end of the day it's JavaScript nothing super special.

Fallback for TYPO3 FAL references fieldname

This should be a simple TypoScript question:
I d like to define a fallback field for a FAL image. The default image should be received from a custom field added to the pages table called ogimage. If there`s no image in this field, the image should be received from the media field instead. This is how I tried to make it work - I commented out the different non-working approaches:
page.meta.og:image {
cObject = FILES
cObject {
references {
table = pages
uid.field = uid
fieldName = media
#fieldName.field = ogimage // media
#fieldName.override = ogimage
#fieldname.override.required = 1
#fieldName.override.if.isTrue.field = ogimage
#fieldName.override.if.isTrue.data = page:ogimage
}
renderObj = IMG_RESOURCE
renderObj {
stdWrap.prepend = TEXT
stdWrap.prepend {
data = getIndpEnv: TYPO3_REQUEST_HOST
wrap = |/
}
file.import.data = file:current:publicUrl
file.maxW = 1500
}
}
}
Any ideas how to solve this?
Yesterday, we had the same problem and your question inspired me. You've been quite close to the solution. This should work:
page.meta.og:image {
cObject = FILES
cObject {
references {
table = pages
uid.field = uid
fieldName = ogimage
fieldName.override = media
fieldName.override.if.isFalse.field = ogimage
}
...
}
}
Since fieldName only contains the field's name there is no image reference or something like that. It is just a string but - as you have tried - the property is stdWrap-able. So the override provides an alternative field name. This is only applied your custom field is empty ("0" which means it has no reference to sys_file_references).

Lift image upload, resize, store in database, display

Is there a succinct example of how to upload an image, resize it, store it in a database and then serve the image up using Lift?
I'm sure I could piece it together from the file upload, Java 2D API, Lift Mapper and Response APIs. But is there any example code I can follow to do it the 'correct' or recommended way?
I did this for a Mapper field linked to s3 by creating a new MappedField. I also have a some code to resize, but haven't tested or deployed (so use with caution).
class MappedS3Image[T<:Mapper[T]](owner: T, val path:String, maxWidth: String, maxHeight:String) extends MappedString[T](owner, 36) {
def url:String = MappedS3Image.fullImgPath(path, is)
def setFromUpload(fileHolder: Box[FileParamHolder]) = {
S3Sender.uploadImageToS3(path, fileHolder).map(this.set(_))
}
override def asHtml:Node = <img src={url} style={"max-width:" + maxWidth + ";max-height:"+maxHeight} />
override def _toForm: Box[Elem] = Full(SHtml.fileUpload(fu=>setFromUpload(Full(fu))))
}
import java.awt.Image
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import java.awt.Graphics2D
import java.awt.AlphaComposite
object ImageResizer {
def resize(is:java.io.InputStream, maxWidth:Int, maxHeight:Int):BufferedImage = {
val originalImage:BufferedImage = ImageIO.read(is)
val height = originalImage.getHeight
val width = originalImage.getWidth
if (width <= maxWidth && height <= maxHeight)
originalImage
else {
var scaledWidth:Int = width
var scaledHeight:Int = height
val ratio:Double = width/height
if (scaledWidth > maxWidth){
scaledWidth = maxWidth
scaledHeight = (scaledWidth.doubleValue/ratio).intValue
}
if (scaledHeight > maxHeight){
scaledHeight = maxHeight
scaledWidth = (scaledHeight.doubleValue*ratio).intValue
}
val scaledBI = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB)
val g = scaledBI.createGraphics
g.setComposite(AlphaComposite.Src)
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose
scaledBI
}
}
}
The other answer nicely describes how to resize the image and store a reference to the file on the file system.
If you want to use the lift mapper to store the actual file contents, you have to create your custom model object, and define a binary field on it. Try something like this:
package code {
package model {
import _root_.net.liftweb.mapper._
import _root_.net.liftweb.util._
import _root_.net.liftweb.common._
// singleton object which manipulates storing of Document instances
object Document extends Document with KeyedMetaMapper[Long, Document] {
}
class Document extends KeyedMapper[Long, Document] {
def getSingleton = Document
def primaryKeyField = id
object id extends MappedLongIndex(this)
object name extends MappedString(this, 20) {
override def displayName = "Name"
override def writePermission_? = true
}
object content extends MappedBinary(this) {
override def displayName = "Content"
override def writePermission_? = true
}
}
}
}
Then, in bootstrap class, add this Document at the end:
Schemifier.schemify(true, Schemifier.infoF _, User, Document)
Voila. Using Document save (new Document) stores it into database. A new Document's fields can be set using the set method. Try playing with delete_!, find, findAll methods of the Document singleton to delete or find it in the database. It should be straightforward from this point on.
Finally, to display the image, you can override Lift's dispatching rules (in bootstrap class, Boot.scala). Try playing around with this example which overrides the rules for pdf requests:
def getFile(filename: String): Option[Document] = {
val alldocs = Document.findAll()
alldocs.find(_.name.get == filename)
}
LiftRules.statelessDispatchTable.append {
case Req("file" :: name :: Nil, "pdf", GetRequest) =>
() =>
println("Got request for: " + name + ".pdf")
for {
stream <- tryo(
getFile(name + ".pdf") map {
doc => new java.io.ByteArrayInputStream(doc.content.get)
} getOrElse null
)
if null ne stream
} yield StreamingResponse(stream,
() => stream.close,
stream.available,
List("Content-Type" -> "application/pdf"),
Nil,
200)
}
Based on the accepted answer by Jon Hoffman, I fixed the bugs. His version messes up the aspect ratio (it always becomes 1:1), because the math was off in a few spots. This version resizes big pictures until they fit, and respects the aspect ratio.
def resize(is:java.io.InputStream, maxWidth:Int, maxHeight:Int):BufferedImage = {
require (maxWidth > 0)
require (maxHeight > 0)
val originalImage:BufferedImage = ImageIO.read(is)
var height = originalImage.getHeight
var width = originalImage.getWidth
// Shortcut to save a pointless reprocessing in case the image is small enough already
if (width <= maxWidth && height <= maxHeight)
originalImage
else {
// If the picture was too big, it will either fit by width or height.
// This essentially resizes the dimensions twice, until it fits
if (width > maxWidth){
height = (height.doubleValue() * (maxWidth.doubleValue() / width.doubleValue())).intValue
width = maxWidth
}
if (height > maxHeight){
width = (width.doubleValue() * (maxHeight.doubleValue() / height.doubleValue())).intValue
height = maxHeight
}
val scaledBI = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
val g = scaledBI.createGraphics
g.setComposite(AlphaComposite.Src)
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose
scaledBI
}
}

Resources