view.getWidth()问题及解决
发布日期:2021-06-30 21:07:21 浏览次数:3 分类:技术文章

本文共 1083 字,大约阅读时间需要 3 分钟。

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        TextView t = (TextView) findViewById(R.id.ttt);//width == 100dp        L.i("1: " + t.getMeasuredWidth()); //getwidth=0 :等onCreate方法执行完了,我们定义的控件才会被度量(measure),        // 所以我们在onCreate方法里面通过view.getHeight()等其它方法获取控件的高度或者宽度肯定是0,        // 因为它自己还没有被度量,也就是说他自己都不知道自己有多高,而你这时候去获取它的尺寸,肯定是不行的    }    //解决办法 getwidth=0    // 在activity被显示出来时即添加到了DecorView上时获取宽和高如onWindowFocusChanged() 回调方法    @Override    public void onWindowFocusChanged(boolean hasFocus) {        TextView t = (TextView) findViewById(R.id.ttt);        int a = t.getWidth();        int b = t.getMeasuredWidth();        L.i("2:" +a); //300 px        L.i("2:" + b); //300 px        float c = UniteUtils.px2dp(MainActivity.this , a);        L.i("3: " + c); //100 dp        float d = UniteUtils.px2sp(MainActivity.this , a);        L.i("4: " + d); //100 sp        super.onWindowFocusChanged(hasFocus);    }}

转载地址:https://liuyan.blog.csdn.net/article/details/79917791 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:时间和字符串的转化
下一篇:Git简单使用

发表评论

最新留言

不错!
[***.144.177.141]2024年04月30日 00时39分50秒