当前位置:网站首页>获取一个控件宽度

获取一个控件宽度

2022-07-22 22:39:00 Rannki

在开发中,我们经常会遇到获取某个控件的宽度,但用

view.getWidth()

获取到的宽度总是为0,这是因为view视图还没有绘制完成,所以是0,我们需要等它绘制完成后再获取就可以了。所以,上代码:

mainactivity.xml:

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="aaaaaaaaaaaaaaaaa"
        android:background="@color/black"
        android:textColor="@color/white"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:layout_marginTop="30dp"
        android:layout_gravity="center"
        android:textColor="@color/black" />
</LinearLayout>

MainActivity.java:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.text);
        // 当textview视图绘制完成后,执行run方法
        textView.post(new Runnable() {
            @Override
            public void run() {
                // 获得textview的宽度,单位px
                int width = textView.getWidth();
                // 显示获取到的width
                TextView show = findViewById(R.id.show);
                show.setText(width + "px");
            }
        });
    }
}

这样,通过用

view.post()

来告诉app,让它等这个view绘制完成后,再执行post里面的方法,这个原理呢,是基于【Handler】多线程来完成的。需要注意的是,【view.getWidth()】获取到的宽度,单位是px哟。

效果图:

 

原网站

版权声明
本文为[Rannki]所创,转载请带上原文链接,感谢
https://blog.csdn.net/oAiYinSiTan12/article/details/125782402