Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get height of view inside adapter for creating sized bitmap?

I use custom CursorAdapter with custom items. I need height of view to resize Bitmap from assets folder and set this resized bitmap to ImegeView in list item;

 @Override
public void bindView(View view, final Context context, final Cursor cursor) {
    final ViewHolder holder = (ViewHolder) view.getTag();

    final int imgCol = cursor.getColumnIndex(TableOdelice.COLUMN_URL);
    int titleCol = cursor.getColumnIndex(TableOdelice.COLUMN_TITRE);
    final int themeCol = cursor.getColumnIndex(TableOdelice.COLUMN_THEME);

    String tempPath = getPath(cursor.getString(themeCol), cursor.getString(imgCol));
    final String path = tempPath.replace(".", "c.");
    String[] arr = cursor.getString(titleCol).split("\\*");
    holder.title.setText(arr[0]);
    holder.subTitle.setText(arr[1]);

    if (itemHeight > 0) {
        showThumb(itemHeight, holder.img, path);
    } else {
        final ImageView v = holder.mainImage;
        v.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                itemHeight = v.getHeight();
                showThumb(itemHeight, holder.img, path);
            }
        });
    }
}

  private void showThumb(int height, final ImageView iv, final String path) {
    if (thumbs.containsKey(path)) {
        iv.setImageBitmap(thumbs.get(path));
    } else {
        InputStream is = null;
        try {
            is = context.getAssets().open(path);
        } catch (IOException e) {
            Log.d("no file at path", path);
            e.printStackTrace();
        }
        if (is != null) {
                Bitmap btm = btmHelper.scaleToHeight(BitmapFactory.decodeStream(is);, height);
            thumbs.put(path, btm);
            iv.setImageBitmap(btm);

        }
    }

}

For getting view height I use OnGlobalLayoutListener() of view.

But it's very slow ... Any ideas?

like image 970
Pavel Shysh Avatar asked Dec 15 '22 05:12

Pavel Shysh


1 Answers

I find answer for my question. Using this construction I get a correct width or height of view inside adapter for each view.

final ImageView v = holder.mainImage;
            v.post(new Runnable() {
            @Override
            public void run() {
                itemHeight = v.getHeight();
                Log.d("Height", "" + itemHeight);
            }

        });
    }

Maybe it will help somebody :)

like image 74
Pavel Shysh Avatar answered Jan 13 '23 13:01

Pavel Shysh