Method of realizing text and picture centered display by Android custom textview

Recently, there is a demand that the symbol "¥" of RMB is not exactly the same because of the inconsistency of Android mobile phone system, so it is replaced by the picture given by art. Considering that there are many places to use, I wanted to write a composite control inherited from the linear layout. Later, I thought, isn't there a textview in Android, a control with its own picture, Later, I wrote a demo because I used matchparent, which led to problems. The RMB symbol is not centered like the text. Therefore, this blog post is available. Let's define textview. This scene is used more.

Analyze the source code of textview

Let's first analyze the source code of textview. Because textview has pictures in the up, down, left, right directions, we won't consider the up and down first, because generally speaking, there is no problem with the vertical center of the picture. We only deal with the pictures in the left and right directions. We directly look at the OnDraw method of textview, because textview also inherits from view, All drawing will be done here

As can be seen from the above, there is a canvas.translate method, which roughly means that after saving, the canvas is translated to the X axis and Y axis respectively, scrollx.. and scrolly. After translation, the picture in the left direction is drawn, and finally restore to the previous canvas. The same is true for right.

In this way, we basically understand the principle. The four directions of textview are drawn to the top, bottom, left and right of the text through canvas translate. Then we can only change this scrollx and scrolly to meet our needs.

Concrete implementation

1. There are comments below. It's not particularly troublesome. It's suitable for drawableleft and drawableright pictures. Don't set gravity in PS and XML, so it can be centered. The code is as follows:

Update the effect picture (because I saw the reply from netizens before, and I used it recently. Update this blog again)

The title is emailcentertextview, and the arrow above and below is drawableright. The unread and garbage bin emailcentertextview of the presentation has no pictures

The above method of realizing text and picture centered display by Android custom textview is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>