Objective
TextView's Drawableleft, Drawableright, and drawabletop are a common, easy-to-use attribute that can be placed around the top and bottom of the text without using a more complex layout. I also often like to use the RadioButton of these several properties to achieve a lot of results, but do not support to let drawbleleft with the text center, set gravity for center also useless, finally have the time to study, here with you to share.
Body
One, the effect chart
Second, the implementation of the Code
Custom controls
/** * Drawableleft centered with text * */public class Drawablecentertextview extends-TextView {
Public Drawablecentertextview (context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);
Public Drawablecentertextview (context, AttributeSet attrs) {Super (context, attrs);
Public Drawablecentertextview {Super (context);
} @Override protected void OnDraw (Canvas Canvas) {drawable[] drawables = Getcompounddrawables ();
if (drawables!= null) {drawable drawableleft = drawables[0];
if (drawableleft!= null) {Float textWidth = Getpaint (). Measuretext (GetText (). toString ());
int drawablepadding = getcompounddrawablepadding ();
int drawablewidth = 0;
Drawablewidth = Drawableleft.getintrinsicwidth ();
Float bodywidth = textWidth + drawablewidth + drawablepadding;
Canvas.translate ((GetWidth ()-bodywidth)/2, 0);
} super.ondraw (canvas); }
}
Summary: consistent with common textview usage, no additional attributes are required, Drawableright is not available.
The above is to the custom control let TextView of the drawableleft with the text of the center to show the problem solved, need friends can refer to.