Autosizing TextViews in RecyclerView causes text size to decrease

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

    The issue I've seen with this is that setting your view height to be wrap_content allows the text size to get smaller, but the text will never get bigger again. This is why the documentation recommends to not use wrap_content for the view size. However, I've found that if you turn off the auto-resizing, set the text size to whatever the max is, then re-enable auto-resizing, the text size resets to the largest size and scales down as necessary.

    So my view in XML would look like:

    
    

    Then in my ViewHolder when I bind my text to the view:

    TextView title = view.findViewById(R.id.text_title);
    String titleValue = "Some Title Value";
    
    // Turn off auto-sizing text.
    TextViewCompat.setAutoSizeTextTypeWithDefaults(title, 
        TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
    
    // Bump text size back up to the max value.
    title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 42);
    
    // Set your text as normal.
    title.setText(titleValue);
    
    // Post a runnable to re-enable auto-sizing text so that it occurs
    // after the view is laid out and measured at max text size.
    title.post(new Runnable() {
        @Override
        public void run() {     
            TextViewCompat
                .setAutoSizeTextTypeUniformWithConfiguration(title,
                        26, 42, 1, TypedValue.COMPLEX_UNIT_DIP);
        }
    });
    

提交回复
热议问题