5

I have a text view with icon rendered in the TextView. It has an image. I have set on the left of the text. But I need to set the icon as a circular shape.

How can I design this in java?

enter image description here

My code which set on the left side.

textview.setCompoundDrawablesWithIntrinsicBounds(
                    image, 0, 0, 0);

How can I design the circular image for the above textview drawableleft image.

 <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="fill_vertical"
        android:ellipsize="end"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="-10dp"
        android:gravity="center"
        android:layout_marginLeft="15dp"
        android:minHeight="24dp"
        android:paddingLeft="@dimen/spacing_d2"
        android:paddingRight="@dimen/spacing_d2"
        android:tag="@string/tag_font_h_regular"
        android:fontFamily="@font/cachetbook"
        android:textColor="@color/white_new"
        android:textSize="12dp"
        tools:text="Universal Orlando Resort"/>
sejn
  • 911
  • 3
  • 11
  • 38

1 Answers1

3

Load your image

You need to load your image as a bitmap. If you are taking if from your drawable, you can see How to convert a Drawable to a Bitmap?.

Resize it

You can resize your bitmap to scale it to fit your textview as you wish. See How to Resize a Bitmap in Android?.

Make the corner rounded

According to this post you can found the code to make corner rounded

Code example

// Load your drawable
Drawable drawable = ContextCompat.getDrawable(this,R.drawable.ic_launcher_background);
// Convert it to a bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(drawableToBitmap((drawable)),50,50,false);
// Make the corner rounded
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
final float roundPx = (float) bitmap.getWidth() * 90f;
roundedBitmapDrawable.setCornerRadius(roundPx);
// Apply it to the TextView
((TextView) findViewById(R.id.test)).setCompoundDrawablesWithIntrinsicBounds(
                roundedBitmapDrawable, null, null, null);

Output

enter image description here

Note

I do not know why you decided to choose to do it programmatically, but I would not recommand it, it is harder to control the view and how things are positionned.

axel7083
  • 540
  • 3
  • 12