当前位置:网站首页>获取一个控件宽度
获取一个控件宽度
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哟。
效果图:

边栏推荐
猜你喜欢

Redis 持久化操作 (RDB, AOF)

阿里云国际版忘记会员名或登录密码,怎么办?

C language function (1)

如何用C语言实现简单职工信息管理系统

buu web

The cubic root of a number

Live broadcast preview | live broadcast Seminar on open source security governance models and tools

技术干货 | 数据处理好难?来看MindSpore提供的解决思路!

Restclient operation index library - initialize restclient

Fault tolerant processing with hystrix
随机推荐
数的三次方根
怎么使用selenium.chrome实现扩展拦截或转发请求功能
Typora设置标题自动添加序号
uni-app进阶之内嵌应用【day14】
互联网流量编排方案
Celebrity interview | various strange current situations in the open source community -- night sky Book Chen Zili tison
php可不可以拆分数组
关于常见排序的稳定性
网站图标的实现
1.10 API and string
TensorRT的插件实战(1)
c语言扫雷
方正中期是什么级别的期货公司?开户安全可靠吗?
How to use selenium.chrome to realize the extended function of intercepting or forwarding requests
论文阅读:The Perfect Match: 3D Point Cloud Matching with Smoothed Densities
笔者认为,元宇宙与互联网的发展逻辑在某种成都上是截然不同的
oh-my-zsh
目标检测之锚点与锚框
阿里云国际版注册成功后添加支付方式
为什么有的人把代码写的如此复杂?