什么时候应该在片段中获得宽度视图
问题描述:
我在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);
}
});