繁体   English   中英

如何在android中的imageview中设置图像?

[英]How to set image in imageview in android?

我想在 imageview 中显示一个图像,所以我创建了一个文件夹 - 在res drawable并将我的图像放在那里。 类似apple.png东西。 然后我使用这个代码:

ImageView iv= (ImageView)findViewById(R.id.img_selected_image);
String path = getApplication().getFilesDir().getAbsolutePath();
InputStream is = new FileInputStream(path + "/apple.png");
Drawable icon = new BitmapDrawable(is);
Log.i("Fnord", "width="+icon.getIntrinsicWidth()+
     " height="+icon.getIntrinsicHeight());
iv.setImageDrawable(icon);

但是当我运行它时,它说data/data/package-name/files没有apple.png名称的任何图像。 我想我把我的形象放在了不合适的地方。 我应该把我的形象放在哪里?

你可以直接在你的setimage中给出图像名称iv.setImageResource(R.drawable.apple); 那应该是它。

使用以下代码,

    iv.setImageResource(getResources().getIdentifier("apple", "drawable", getPackageName()));

您可以在XML布局中设置:而不是通过活动类中的代码设置可绘制资源:

代码如下:

<ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/apple" />
// take variable of imageview

private ImageView mImageView;

//bind imageview with your xml's id

mImageView = (ImageView)findViewById(R.id.mImageView);

//set resource for imageview

mImageView.setImageResource(R.drawable.your_image_name);

放入res / drawable的图像由Android处理。 您无需按照自己的方式获取图像。 在你的情况下你可以简单地调用iv.setImageRessource(R.drawable.apple)

要获取图像(而不是直接将其添加到ImageView),可以调用Context.getRessources().getDrawable(R.drawable.apple)来获取图像

        ImageView iv= (ImageView)findViewById(R.id.img_selected_image);
        public static int getDrawable(Context context, String name)//method to get id
        {
         Assert.assertNotNull(context);
         Assert.assertNotNull(name);
        return context.getResources().getIdentifier(name,    //return id
            "your drawable", context.getPackageName());
        }
        image.setImageResource(int Id);//set id using this method

如果您从Java类创建了ImageView

ImageView img = new ImageView(this);

//Here we are setting the image in image view
img.setImageResource(R.drawable.my_image);

如果你想设置一个位图对象到图像视图这里是简单的两行`

Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.sample_drawable_image);
image.setImageBitmap(bitmap);

1>您可以从布局本身添加图像:

<ImageView
                android:id="@+id/iv_your_image"
                android:layout_width="wrap_content"
                android:layout_height="25dp"
                android:background="@mipmap/your_image"
                android:padding="2dp" />

要么

2>在java类中以编程方式:

ImageView ivYouImage= (ImageView)findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

片段

View rowView= inflater.inflate(R.layout.your_layout, null, true);

ImageView ivYouImage= (ImageView) rowView.findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

在imageview中设置图像

imageView.setImageResource(R.drawable.myImage);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM