Francesco Bordignon
Francesco Bordignon

Reputation: 103

Set the height of a ImageView based on the height of a TextView

I have a ImageView that should have the height of a TextView, this is code I'm using but it always returns 0:

    @Override
public void onBindViewHolder(@NonNull viewHolder holder, final int position) {


    holder.abstractText.setText(events.get(position).abstractTExt);

    Rect bounds = new Rect();
    Paint textPaint = holder.abstractText.getPaint();
    textPaint.getTextBounds((String) holder.abstractText.getText(),0,holder.abstractText.getText().length(),bounds);

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, bounds.height());
    holder.borderImage.setLayoutParams(layoutParams);
    Log.d("-------------borderHe", String.valueOf((holder.abstractText.getLineHeight() * holder.abstractText.getLineCount())));
}

How can I do this? Thanks in advance!

Upvotes: 0

Views: 29

Answers (1)

Kintan Patel
Kintan Patel

Reputation: 1278

It's returning zero because your view is not created yet, so you need to use below code by post method. Firstly you need to calculate the height of TextView and then apply to layout,

holder.abstractText.post(new Runnable() {
            @Override
            public void run() {
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, holder.abstractText.getHeight());
                holder.borderImage.setLayoutParams(layoutParams);     
            }
        });

Upvotes: 2

Related Questions