Autosizing TextViews in RecyclerView causes text size to decrease

后端 未结 6 853
野趣味
野趣味 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:42

    I packaged Michael Celey's answer into a class. The parameters app:autoSizeMinTextSize, app:autoSizeMaxTextSize, app:autoSizeTextType are taken from xml.

    public class AutosizingTextView extends AppCompatTextView {
    
        private int minTextSize;
        private int maxTextSize;
        private int granularity;
    
        public AutosizingTextView(Context context) {
            super(context);
            init();
        }
    
        public AutosizingTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public AutosizingTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        private void init() {
            minTextSize = TextViewCompat.getAutoSizeMinTextSize(this);
            maxTextSize = TextViewCompat.getAutoSizeMaxTextSize(this);
            granularity = TextViewCompat.getAutoSizeStepGranularity(this);
        }
    
        @Override
        public void setText(CharSequence text, BufferType type) {
            // this method is called on every setText
            disableAutosizing();
            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);
        }
    }```
    

提交回复
热议问题