什么时候应该在片段中获得宽度视图 [英] When should I get Width View in Fragment

查看:70
本文介绍了什么时候应该在片段中获得宽度视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linearlayout中以编程方式添加View(按钮).LinearLayout由Fragment中的XML布局.

I adding View (button) programally in Linearlayout.LinearLayout is layouted by XML in Fragment.

我想获取按钮的宽度,但总是返回0.

I want to get button width, but always return 0.

我搜索了这个问题

getWidth仅在WindowFocusChanged上起作用.

getWidth work only onWindowFocusChanged.

 public void onWindowFocusChanged(boolean hasFocus) { }

但是Fragment没有这种方法.

but Fragment do not have this method.

如何获取片段中的视图宽度?

How to get View width in Fragment?

推荐答案

查看帖子

Check out post GlobalLayoutListener. You can use the listener on your Button in onCreateView() as you have used onWindowFocusChanged. It also is more reliable than onWindowFocusChanged().

尝试如下:

  final View myView = profileContainer.findViewById(R.id.sub_page_padding);
  ViewTreeObserver vto = profilePadding.getViewTreeObserver();
  vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
      Log.d("TEST", "Height = " + myView.getHeight() + " Width = " + myView.getWidth());
      ViewTreeObserver obs = profilePadding.getViewTreeObserver();
      obs.removeGlobalOnLayoutListener(this);
    }
  });

这篇关于什么时候应该在片段中获得宽度视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆