设置图像按钮 - uri,android

时间:2014-08-12 01:48:48

标签: java android button uri drawable

我的程序会生成多个显示键,我想分配每个图标。资产保持图标。但是android没有加载图标

        button.setText(shop.getName());
        Drawable icon;
        int s = shop.getId();
        String sk = Integer.toString(s);
        String imageUri = "file:///android_asset/shop"+sk+".png";
        Log.w("imageURI", imageUri);
        Uri uri=Uri.parse(imageUri);


        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            icon = Drawable.createFromStream(inputStream, uri.toString() );
        } catch (FileNotFoundException e) {
            icon = getResources().getDrawable(R.drawable.shopping1);
        }
        Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
        Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 100, 100, true));

        button.setCompoundDrawablesWithIntrinsicBounds( null, d, null, null );

记录:... file:///android_asset/shop1.png

1 个答案:

答案 0 :(得分:0)

试试这个:

    button.setText(shop.getName());
    Drawable icon;
    int s = shop.getId();
    String sk = Integer.toString(s);
    String imageUri = "file:///android_asset/shop"+sk+".png";
    Log.w("imageURI", imageUri);
    Uri uri=Uri.parse(imageUri);

    InputStream is;
    try {
        is = this.getContentResolver().openInputStream( uri );
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inSampleSize = 10;
        Bitmap preview_bitmap=BitmapFactory.decodeStream(is,null,options);

        Drawable icon = new BitmapDrawable(getResources(),preview_bitmap);

    } catch (FileNotFoundException e) {
        //set default image from the button
        icon = getResources().getDrawable(R.drawable.shopping1);
    }    

    button.setBackground(icon);