开发者

Android ImageView problem

开发者 https://www.devze.com 2023-02-03 10:55 出处:网络
I have and image (img1.png) in my drawable-hdpi folder, but im getting NullPointerException(?) when i use the following code. Did i miss something?

I have and image (img1.png) in my drawable-hdpi folder, but im getting NullPointerException(?) when i use the following code. Did i miss something?

int id = getResources().getIdentifier("img1", "drawable", 开发者_如何学CgetPackageName());  
    imgView.setImageResource(id); 

Thanks


Try this code:

imageView.setImageResource(R.drawable.img1);

Taken from http://developer.android.com/guide/topics/resources/accessing-resources.html


Did you initialize imgView?

imgView = new ImageView(this);

Even if you have done so, that's not the way to do it... it should be something like:

imgView = (ImageView)findViewById(R.drawable.img1);


If you haven't found a fix already, this may be to do with the support-screens tag. In later versions of Android, if this is set to true, it will rescale your bitmaps for you and things change. I found that having:

<supports-screens android:anyDensity="true" />

made getting a drawable image work as expected. (The image is returned in its native resolution).

See: http://developer.android.com/guide/topics/manifest/supports-screens-element.html


Try this

 Bitmap img1 = BitmapFactory.decodeResource(getResources(), R.drawable.img1);

This will make your image into a bitmap. Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号