Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从文件中动态设置imageView?_Android_Imageview - Fatal编程技术网

Android 如何从文件中动态设置imageView?

Android 如何从文件中动态设置imageView?,android,imageview,Android,Imageview,我需要动态设置imageView。该图像是可绘制的。此代码正常: Bitmap bm2 = BitmapFactory.decodeResource(getResources(), R.drawable.image1); img_pergunta.setImageBitmap(bm2); 问题是我需要从字符串开始,但这段代码不起作用: File imgFile = new File("/drawable/image1.png"); Bitmap bm2 = BitmapFactory.de

我需要动态设置imageView。该图像是可绘制的。此代码正常:

Bitmap bm2 = BitmapFactory.decodeResource(getResources(), R.drawable.image1); 
img_pergunta.setImageBitmap(bm2);
问题是我需要从字符串开始,但这段代码不起作用:

File imgFile = new  File("/drawable/image1.png");
Bitmap bm2 = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
img_pergunta.setImageBitmap(bm2);

如何解决此问题?

您可能给出了错误的文件路径,请重试

File imgFile=新文件(“android。resource://COM.EXAMPLE.PACKAGE/drawable/image1.png");


但是用正确的包名替换包名-您的

您可以通过提供如下所述的路径来创建新文件

File File=new文件(“android.resource://”+R.class.getPackage().getName()+“/”+resourceId);

resourceId可以替换为
R.drawable.resourceName

您可以使用context.getResources().getIdentifier()和类似image4的名称获取id(在decodeResource()中使用)

BitmapFactory.decodeFile(…文件路径…);可以。但是使用的路径是不可能的。另外,两个答案中使用的路径都是无意义的;和恢复的str2=com.cursorandroid.autenticacaousuario.autenticacaousuario?????????????路径仍然不正确,我尝试了此方法。getClass().getPackage().getName()只是为了确保包的正确名称为什么包名是路径?E/BitmapFactory:无法解码流:java.io.FileNotFoundException:/android.resource:/com.cursoandroid.autenticacaousuario.autenticacaousuario/21301099768:打开失败:enoint(没有这样的文件或目录)我测试了字符串str2=this.getClass().getPackage().getName(); 和恢复的str2=com.cursoroandroid.autenticacaousuario.autenticacaousuarioE/BitmapFactory:无法解码流:java.io.FileNotFoundException:/android.resource:/com.cursoroandroid.autenticacaousuario.autenticacaousuario/drawable/q8circ1.png:打开失败:enoint(没有这样的文件或目录)int resId=getResources().getIdentifier(“q8circ1”); // 不正确。我知道您没有在谷歌上搜索声明或示例。我尝试了:int resId=getResources().getIdentifier(“image1”,“image”,getPackageName());位图bm2=BitmapFactory.decodeResource(getResources(),resId);设置图像位图(bm2);int resId=getResources().getIdentifier(“image1”,“drawable”,getPackageName());