简体   繁体   English

如何增加 TextView 的大小并在 for 循环中获取它的宽度,Android

[英]How to increase TextView size and get width of it in for loop, Android

When button click a for loop starts and in for loop I am increasing text size and log the width of TextView.当按钮单击 for 循环开始并进入 for 循环时,我正在增加文本大小并记录 TextView 的宽度。 but it is not increasing size and always getting the same width(check the log added below).但它并没有增加大小并且总是获得相同的宽度(检查下面添加的日志)。 I added my full code.我添加了我的完整代码。 How to fix this?如何解决这个问题?

activity_main.xml activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:background="@color/colorPrimary"
        android:fontFamily="@font/roboto"
        android:text="00:00" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="ocBtnIncrease"
        android:text="Increase" />

</RelativeLayout>

MainActivity.java MainActivity.java

package com.example.test;

import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = MainActivity.class.getSimpleName();
    TextView tv;

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

        tv = findViewById(R.id.tv);
    }

    public void ocBtnIncrease(View view) {
        for (int i = 1; i < 500; i++) {
            tv.setTextSize(i);
            Log.i(TAG, "i: " + i);
            Log.i(TAG, "WIDTH: " + tv.getWidth());
            SystemClock.sleep(500);
        }
    }
}

Log日志

I/MainActivity: i: 1
I/MainActivity: WIDTH: 71
I/MainActivity: i: 2
I/MainActivity: WIDTH: 71
I/MainActivity: i: 3
I/MainActivity: WIDTH: 71
I/MainActivity: i: 4
.
.

Use setTextSize() like this:像这样使用 setTextSize():

tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f);

Original answer is here原始答案在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM