本文介绍了什么时候应该在片段中获得宽度视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在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?
推荐答案
查看帖子.您可以像使用onWindowFocusChanged
一样在onCreateView()
中的Button
上使用侦听器.它也比onWindowFocusChanged()
更可靠.
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);
}
});
这篇关于什么时候应该在片段中获得宽度视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!