xing_star

Time:2020-11-4

Nowadays, chat is a standard configuration for social apps. In addition, many functions are derived from chat, such as expression pack, background, bubble, etc.

One day, the test gave me a bug, saying that when the soft keyboard pops up and collapses, the chat background image will shake. We need to solve it. I’m very puzzled. This is not implemented by ImageView. What is the effect of Android. How can I know how to change it?

To make complaints about the test, my sister used my WeChat chat background to hit my face. It looks like WeChat is right. I took a closer look at the effect of the chat interface of Netease cloud letter and found that, um, Netease cloud letter has dealt with this problem. The soft keyboard pops up and collapses, and the background image will not shake. After studying for a few minutes, we found the key code. So today, write down the code and write it down. In the future will not encounter this problem (⊙ o ⊙)

Netease cloud letter inherits and rewrites some methods of ImageView:

MsgBkImageView.java

public class MsgBkImageView extends AppCompatImageView {
    public MsgBkImageView(Context context) {
        super(context);

        init();
    }

    public MsgBkImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    public MsgBkImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init();
    }

    private final void init() {
        super.setScaleType(ScaleType.CENTER_CROP);
    }

    @Override
    public final void setScaleType(ScaleType scaleType) {
        // REJECT
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable dr = getDrawable();

        if (dr == null) {
            super.onDraw(canvas);

            return;
        }

        int dwidth = dr.getBounds().width();
        int dheight = dr.getBounds().height();

        int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
        int vheight = getHeight() - getPaddingTop() - getPaddingBottom();

        float scale;
        float dx = 0, dy = 0;

        if (dwidth * vheight > vwidth * dheight) {
            scale = (float) vheight / (float) dheight;
            dx = (vwidth - dwidth * scale) * 0.5f;
        } else {
            scale = (float) vwidth / (float) dwidth;
            dy = (vheight - dheight * scale) * 0.5f;
        }

        canvas.save();

        canvas.translate(0, -(int) (dy + 0.5f));

        super.onDraw(canvas);

        canvas.restore();
    }
}

It seems that the OnDraw method has been rewritten with the canvas.translate Methods have been dealt with. This method has not been studied in depth