In my project I'm trying to display several image files by manipulating the filename of one of the images programatically.
ie, I may have:
filename.jpg, filename_top.jpg, filename_middle.jpg
I receive input of an drawable int and am trying to find the filename of the displayed image before manipulating this filename and trying to display the programatically generated filenames.. problem is that the manipulated filename does not display.
ie. there is something wrong with this:
imageView2.setImageResource(getImageId(this, namebottom));
Any ideas how getImageId can be modified to make setImageResource work properly?
The code would look something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bun = getIntent().getExtras();
int imagenumber = bun.getInt("imagenumber");
String extension = bun.getString("extension");
// int become a val from 0 to 20 (array size)
setContentView(R.layout.clickeditem);
final int[] imgIds = new int[{
R.drawable.image0,R.drawable.image1,R.drawable.image2,,,R.drawable.image20};
//The first image with id top in the layout is set ok:
ImageView imageView1 = (ImageView)findViewById(R.id.top);
imageView1.setImageResource(imgIds [ imagenumber ] );
// problem here:
//try to get the name of this file: ie: filename.jpg
// and then manipulate the filename:
String name = imageView1.getResources().getString(R.id.image0);
//try to convert this to the filename_middle.jpg
String namemiddle = name.replace(".jpg", "_middle.jpg");
imageViewt.setImageResource(getImageId(this, namemiddle));
//try to convert this to filename_bottom.jpg
String namebottom = name.replace(".jpg", "_bottom.jpg");
imageView2.setImageResource(getImageId(this, namebottom));
}
//where getImageId is defines as follows:
public static int getImageId(Context context, String imageName)
{
return context.getResources().getIdentifier("drawable/" + imageName,
null, context.getPackageName());
}
return context.getResources().getIdentifier("drawable/" + imageName,
null, context.getPackageName());
replace this by
return context.getResources().getIdentifier(imageName,
"drawable", context.getPackageName());
Related
I want to convert Drawable into int and then vice versa.Basically I want to save Arraylist object into sharedPrefrence. For that purpose I have Implement Gson to Srtring convertion Method. If I use here Drawable instead of int then Gson String convertion take alot of time. so I want to use int instead of Drawable.
private List<AppInfo> apps = null;
public void setIcon(int icon) {
this.icon = icon;
}
apps.get(position).setIcon(mContext.getResources().getDrawable(apps.get(position).getIcon()));
Where AppInfo here is
public AppInfo(String appname, String pname, String versionName, int versionCode, int icon, int color) {
this.appname = appname;
this.pname = pname;
this.versionName = versionName;
this.versionCode = versionCode;
this.icon = icon;
this.color = color;
}
Here is source of Converting ArrayList of Custom object into String so that i can save it to SharedPrefrence.
Gson gson = new Gson();
apps.get(number).setColor(picker.getColor());
String JsonAppsdata = gson.toJson(apps);
System.out.println("Storing="+JsonAppsdata);
utility.StoreData(getApplicationContext(), JsonAppsdata);
Int -> Drawable:
Drawable icon = getResources().getDrawable(42, getTheme());
Drawable -> Int:
(I assume, that you're populating List<AppInfo> apps with app's whose icons are already in res/drawable folder of your app)
Once you set your R.drawable.app1 to ImageView, you can also give it a tag to identify the resource in the ImageView later:
ImageView appIcon1ImageView = (ImageView)findViewById(R.id.app_icon_1);
appIcon1ImageView.setImageDrawable(getDrawable(R.drawable.app1));
appIcon1ImageView.setTag(R.drawable.app1);
......
// Once you need to identify which resource is in ImageView
int drawableId = Integer.parseInt(appIcon1ImageView.getTag().toString());
If your icons are coming from server - the only way is to store them to disk and then re-load them. (or, better, rely on the already existing image-caching solutions like picasso)
UPD:
There's no direct way of converting Drawable into int, but in this particular case, it's possible to get the int, instead of Drawable from PackageManager:
ApplicationInfo applicationInfo = mContext.getPackageManager().getApplicationInfo(apps.get(position).getPname(),1);
int icon= applicationInfo.icon;
This is how we can fetch app icon and set it for an imageview.
applicationInfo=mContext.getPackageManager().getApplicationInfo(apps.get(position).getPname(),PackageManager.GET_META_DATA);
int icon= applicationInfo.icon;
Rsources resources=mContext.getPackageManager().getResourcesForApplication(applicationInfo);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.itemIcon.setImageDrawable(resources.getDrawable(icon,null));
}else
{
holder.itemIcon.setImageDrawable(resources.getDrawable(icon));
}
The only solution that worked for me was in the chat by #KonstantinLoginov, but instead of using:
val drawable = context.getPackageManager().getApplicationIcon(applicationInfo),
I passed in the packageName:
val drawable = context.getPackageManager().getApplicationIcon(packageName) which is String and can easily be passed around.
I would like to change the imageview src based on my string, I have something like this:
ImageView imageView1 = (ImageView)findViewById(R.id.imageView1);
String correctAnswer = "poland";
String whatEver = R.drawable+correctAnswer;
imageView1.setImageResource(whatEver);
Of course it doesnt work. How can I change the image programmatically?
public static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
use:
imageView1.setImageResource(getImageId(this, correctAnswer);
Note: leave off the extension (eg, ".jpg").
Example: image is "abcd_36.jpg"
Context c = getApplicationContext();
int id = c.getResources().getIdentifier("drawable/"+"abcd_36", null, c.getPackageName());
((ImageView)v.findViewById(R.id.your_image_on_your_layout)).setImageResource(id);
I don't know if this is what you had in mind at all, but you could set up a HashMap of image id's (which are ints) and Strings of correct answers.
HashMap<String, Integer> images = new HashMap<String, Integer>();
images.put( "poland", Integer.valueOf( R.drawable.poland ) );
images.put( "germany", Integer.valueOf( R.drawable.germany ) );
String correctAnswer = "poland";
imageView1.setImageResource( images.get( correctAnswer ).intValue() );
I want to display images randomly when my activity starts. I am using the following code to execute it.
final ImageView img = (ImageView) findViewById(R.id.imgRandom);
final String str = "img_" + rnd.nextInt(2);
img.setImageDrawable(getResources().getDrawable(
getResourceID(str, "drawable", getApplicationContext())));
}
protected final static int getResourceID(final String resName,
final String resType, final Context ctx) {
final int ResourceID = ctx.getResources().getIdentifier(resName,
resType, ctx.getApplicationInfo().packageName);
if (ResourceID == 0) {
throw new IllegalArgumentException(
"No resource string found with name " + resName);
} else {
return ResourceID;
}
}
PROBLEM: This code only randomly generates first two images present in my drawable, whereas i have a total of 8 images.
Thanks in advance.
P.S the name of my images are img_0 , img_1, img_2, img_3, img_4, img_5, img_6, img_7
Use HashMap to store your image names associated with a key ,
HashMap<Integer, String> meMap=new HashMap<Integer, String>();
meMap.put(0,"img_0"); // add other images as 1, 2, 3
Use Random class to generate number including 0 and less than 8
Random rnd = new Random();
int value = rnd.nextInt(8);
Get the relevant map object according to the generated key(random integer) and get the respective image name and load it.
I parse image name by json, and now for displaying I would have to get the drawable id by the image name so I can do this:
background.setBackgroundResource(R.drawable.eventimage1);
When I get the image name the format is like this:
image_ev1.png
Use this function to get a drawable when you have the image name. Note that the image name does not include the file extension.
public static Drawable GetImage(Context c, String ImageName) {
return c.getResources().getDrawable(c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName()));
}
then just use setBackgroundDrawable method.
If you only want the ID, leave out the getDrawable part
i.e.
return c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName());
this gets you your image id
int resId = getResources().
getIdentifier(your_image_name.split("\\.")[0], "drawable", getApplicationInfo().packageName);
if you need a drawable after that :
getResources().getDrawable(resId)
Add this method to your code:
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
Then retrieve your image so:
Context ctx = getApplicationContext();
background.setBackgroundResource(getResourceID("image_ev1", "drawable", ctx)));
For Kotlin programmer (ContextCompat from API 22):
var res = context?.let { ContextCompat.getDrawable(it,resources.getIdentifier("your_resource_name_string", "drawable", context?.getPackageName())) }
Your can also use e.g. "mipmap" instead of "drawable" if resource is place in other location.
Here is how to do in Kotlin :
// FilePath : ../drawable/app_my_bg_drawable.xml
// Call function as: val fileIntId = getDrawableIntByFileName(context, "app_my_bg_drawable")
fun getDrawableIntByFileName(context: Context, fileName: String): Int {
return context.resources.getIdentifier(fileName, "drawable", context.packageName)
}
// FilePath : ../drawable/app_my_bg_drawable.xml
// Call function as: val fileDrawable = getDrawableByFileName(context, "app_my_bg_drawable")
fun getDrawableByFileName(context: Context, fileName: String): Drawable? {
return ContextCompat.getDrawable(context, context.resources.getIdentifier(fileName, "drawable", context.packageName))
}
I'm looking for a way to convert the first letter of a string to a lower case letter. The code I'm using pulls a random String from an array, displays the string in a text view, and then uses it to display an image. All of the strings in the array have their first letter capitalized but image files stored in the app cannot have capital letters, of course.
String source = "drawable/"
//monb is randomly selected from an array, not hardcoded as it is here
String monb = "Picture";
//I need code here that will take monb and convert it from "Picture" to "picture"
String uri = source + monb;
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
ImageView imageView = (ImageView) findViewById(R.id.monpic);
Drawable image = getResources().getDrawable(imageResource);
imageView.setImageDrawable(image);
Thanks!
if (monb.length() <= 1) {
monb = monb.toLowerCase();
} else {
monb = monb.substring(0, 1).toLowerCase() + monb.substring(1);
}
public static String uncapitalize(String s) {
if (s!=null && s.length() > 0) {
return s.substring(0, 1).toLowerCase() + s.substring(1);
}
else
return s;
}
Google Guava is a java library with lot of utilities and reusable components. This requires the library guava-10.0.jar to be in classpath. The following example shows using various CaseFormat conversions.
import com.google.common.base.CaseFormat;
public class CaseFormatTest {
/**
* #param args
*/
public static void main(String[] args) {
String str = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "studentName");
System.out.println(str); //STUDENT_NAME
str = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "STUDENT_NAME");
System.out.println(str); //studentName
str = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, "student-name");
System.out.println(str); //StudentName
str = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "StudentName");
System.out.println(str); //student-name
}
}
Output Like:
STUDENT_NAME
studentName
StudentName
student-name