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>

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值