Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align drawable image inside a text view to center

I have a textview which holds an image and some text.

programmatically i have added the drawable image to the left side of text view

txtIDFav.setCompoundDrawablesWithIntrinsicBounds(R.drawable.fav_enabled, 0, 0, 0);

i have aligned the text view to center using

txtIDFav.setGravity(Gravity.CENTER);

Now the text in the textview is aligned to center. but the image is on the left side.

eg: [image]_____________________ mytext

used the _ to give space as its not allowed.

I want to align the image to center along with the text.

eg: _____________________[image]mytext

Please advice.

Thanks and appreciate.

like image 242
Mohammad Sherif Avatar asked May 06 '14 10:05

Mohammad Sherif


1 Answers

You can try this, it should work:

    Spannable span = new SpannableString("  " + txtIDFav.getText());  // or set your text manually

    Drawable drawable;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        drawable = getResources().getDrawable(R.drawable.fav_enabled, getContext().getTheme());
    }
    else {
        drawable = getResources().getDrawable(R.drawable.fav_enabled);
    }

    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    ImageSpan imageSpan = new ImageSpan(drawable);
    span.setSpan(imageSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

    txtIDFav.setText(span);
like image 155
Ayaz Alifov Avatar answered Nov 03 '22 23:11

Ayaz Alifov