Align drawable image inside a text view to center

前端 未结 6 1385
挽巷
挽巷 2021-02-19 11:58

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.setCompound         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 12:24

    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);
    

提交回复
热议问题