Autosizing TextViews in RecyclerView causes text size to decrease

后端 未结 6 852
野趣味
野趣味 2021-02-13 17:24

I am trying to use Autosizing TextViews in a RecyclerView, but when I scroll a few times the text gets so small that it\'s obviously not working properly.

Example of my

6条回答
  •  面向向阳花
    2021-02-13 17:35

    Pavel Haluza's answer's approach was great. However, it didn't work, probably because he missed a line setTextSize(TypedValue.COMPLEX_UNIT_PX, maxTextSize);.

    Here is my updated version:

    public class MyTextView extends AppCompatTextView {
    
    private int minTextSize;
    private int maxTextSize;
    private int granularity;
    
    public MyTextView(Context context) {
        super(context);
        init();
    }
    
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    
    private void init() {
        minTextSize = TextViewCompat.getAutoSizeMinTextSize(this);
        maxTextSize = TextViewCompat.getAutoSizeMaxTextSize(this);
        granularity = Math.max(1, TextViewCompat.getAutoSizeStepGranularity(this));
    }
    
    @Override
    public void setText(CharSequence text, BufferType type) {
        // this method is called on every setText
        disableAutoSizing();
        setTextSize(TypedValue.COMPLEX_UNIT_PX, maxTextSize);
        super.setText(text, type);
        post(this::enableAutoSizing); // enable after the view is laid out and measured at max text size
    }
    
    private void disableAutoSizing() {
        TextViewCompat.setAutoSizeTextTypeWithDefaults(this, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
    }
    
    private void enableAutoSizing() {
        TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(this,
                minTextSize, maxTextSize, granularity, TypedValue.COMPLEX_UNIT_PX);
    }}
    

提交回复
热议问题