Как установить изображение из динамически динамически в андроид?
Я сохраняю свои связанные с проектом изображения в папке с возможностью выбора. Также я сохраняю имена изображений в строковой переменной и динамически пытаюсь установить эти изображения в образ. Но изображение не отображается. Пожалуйста, помогите мне в этом.
Мой код:
int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);
В приведенном выше коде "imagename" - это строковая переменная, которая содержит имя изображения.
Заранее спасибо
Ответы
Ответ 1
Попробуйте следующее:
String uri = "@drawable/myresource"; // where myresource (without the extension) is the file
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
Ответ 2
Здесь я устанавливаю изображение frnd_inactive
из drawable
на изображение
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageDrawable(getResources().getDrawable(R.drawable.frnd_inactive));
Ответ 3
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(R.drawable.mydrawable);
Ответ 4
Попробуйте этот Динамический код
String fnm = "cat"; // this is image file name
String PACKAGE_NAME = getApplicationContext().getPackageName();
int imgId = getResources().getIdentifier(PACKAGE_NAME+":drawable/"+fnm , null, null);
System.out.println("IMG ID :: "+imgId);
System.out.println("PACKAGE_NAME :: "+PACKAGE_NAME);
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),imgId);
your_image_view.setImageBitmap(BitmapFactory.decodeResource(getResources(),imgId));
В приведенном выше коде вам понадобится объект Image-file-Name и Image-View , который у вас есть.
Ответ 5
Смотрите ниже код, который работает для меня
iv.setImageResource(getResources().getIdentifier(
"imagename", "drawable", "com.package.application"));
Ответ 6
Это работает для меня (не используйте расширение изображения, просто имя):
String imagename = "myImage";
int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);
Ответ 7
Вот лучший способ, с помощью которого работает в каждом телефоне сегодня. Большинство из этих ответов устарели или нуждаются в API >= 19 или 22.
Вы можете использовать код фрагмента или код действия, который зависит от того, что вам нужно.
Фрагмент
//setting the bitmap from the drawable folder
Bitmap bitmap= BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.my_image);
//set the image to the imageView
imageView.setImageBitmap(bitmap);
активность
//setting the bitmap from the drawable folder
Bitmap bitmap= BitmapFactory.decodeResource(MyActivity.this.getResources(), R.drawable.my_image);
//set the image to the imageView
imageView.setImageBitmap(bitmap);
Ура!
Ответ 8
imageView.setImageResource(R.drawable.picname);
Ответ 9
getDrawable()
устарел, поэтому попробуйте
imageView.setImageResource(R.drawable.fileName)
Ответ 10
Сначала имя вашего изображения myimage. Итак, что вам нужно сделать, это перейти к Drawable и сохранить имя изображения myimage.
Теперь предположим, что вы знаете только имя изображения, и вам нужно получить к нему доступ. Используйте ниже фрагмент, чтобы получить к нему доступ,
что вы сделали правильно, убедитесь, что вы сохранили имя изображения, которое вы собираетесь использовать внутри кодирования.
public static int getResourceId(Context context, String name, String resourceType) {
return context.getResources().getIdentifier(toResourceString(name), resourceType, context.getPackageName());
}
private static String toResourceString(String name) {
return name.replace("(", "")
.replace(")", "")
.replace(" ", "_")
.replace("-", "_")
.replace("'", "")
.replace("&", "")
.toLowerCase();
}
В дополнение к этому вы должны убедиться, что нет пустых мест и чувствительности к случаю
Ответ 11
Начиная с API 22, getResources().getDrawable()
устарел (см. также Android getResources(). getDrawable() устарел API 22). Вот новый способ динамического задания ресурса изображения:
String resourceId = "@drawable/myResourceName"; // where myResourceName is the name of your resource file, minus the file extension
int imageResource = getResources().getIdentifier(resourceId, null, getPackageName());
Drawable drawable = ContextCompat.getDrawable(this, imageResource); // For API 21+, gets a drawable styled for theme of passed Context
imageview = (ImageView) findViewById(R.id.imageView);
imageview.setImageDrawable(drawable);
Ответ 12
Это отлично работает для меня.
final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();
for (int i=0; i < fields.length;i++)
{
resourceId[i] = fields[i].getInt(drawableResources);
/* till here you get all the images into the int array resourceId.*/
}
imageview= (ImageView)findViewById(R.id.imageView);
if(your condition)
{
imageview.setImageResource(resourceId[any]);
}
Ответ 13
getDrawable() устарел.
теперь вы можете использовать
imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.msg_status_client_read))
Ответ 14
int[] phptr=new int[5];
добавление указателя изображения в массив
for(int lv=0;lv<3;lv++)
{
String id="a"+String.valueOf(lv+1);
phptr[lv]= getResources().getIdentifier(id, "drawable", getPackageName());
}
for(int loopvariable=0;loopvariable<3;loopvariable++)
{
et[loopvariable] = findViewById(p[loopvariable]);
}
for(int lv=0;lv<3;lv++)
{
et[k].setImageResource(phptr[k]);
}