Android TextView字体大小自适应

当文字非常长,在屏幕小的手机上无法全部文字;

Android 让 TextView 自适应大小,加入以下代码:

app:autoSizeTextType="uniform"

就可以实现以下效果,无论 TextView 大小是多少,都可以让里面的文字充满整个 TextView:

告别以前自己写递归算法,非常方便。

MainActivity 完整代码如下:

public class MainActivity extends AppCompatActivity {
    TextView tv_cat;
    SeekBar seekBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_cat = findViewById(R.id.tv_cat);
        seekBar = findViewById(R.id.seekBar);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //dp转化为px
                float dp = progress * 3;
                final float scale = getResources().getDisplayMetrics().density;
                int px = (int) (dp * scale + 0.5f);

                //设置TextView高度
                ViewGroup.LayoutParams params = tv_cat.getLayoutParams();
                params.height = px;
                params.width = px;
                tv_cat.setLayoutParams(params);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }
}

activity_main 完整代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:gravity="center">

        <TextView
            android:id="@+id/tv_cat"
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:background="#FFFFFF"
            android:text="你还记得那只猫吗?"
            app:autoSizeTextType="uniform" />
    </LinearLayout>

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:layout_marginTop="20dp"
        android:max="100"
        android:min="50"
        android:progress="100"
        android:scrollbarStyle="outsideOverlay" />
</LinearLayout>
发布了322 篇原创文章 · 获赞 450 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/wuqingsen1/article/details/103713425