Android 在片段中获取布局高度和宽度 [英] Android get layout height and width in a fragment
问题描述
我正在处理一个片段,我想获取 xml
fragment layout
中包含的 layout
的维度.当我尝试代码时
I am working on a fragment and I want to get the dimension of a layout
contained in the xml
fragment layout
.
When I try the code
RelativeLayout myLayout = view.findViewById(R.id.myLayout);
myLayout.getHeight();
它返回0.我需要这些尺寸才能将其他对象放入 myLayout 中.
it returns 0. I need these dimensions to put inside myLayout other objects.
我尝试使用:
myLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener(){
@Override
public void onGlobalLayout() {
mHeight = myLayout.getHeight();
mWidth= myLayout.getWidth();
System.out.println("width: "+mWidth+" height: "+mHeight);
}
});
但是这段代码调用了很多时间,我不知道它什么时候执行.我需要将这些维度放入 public void onActivityCreated()
方法中.是否可以?
but this code is invoke a lot of time and I don't know exactly when it is execute.
I need these dimensions into public void onActivityCreated ()
method. Is it possible?
推荐答案
对此有一个更简洁的解决方案,只需在片段的根视图上使用 View.post()
方法,您就可以调用getMeasuredHeight()/getMeasuredWidth()
并获取实际值.
There's a cleaner solution to this, just use the View.post()
method on your fragment's root view, and you can call getMeasuredHeight()/getMeasuredWidth()
and get the actual values.
例如
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.myfragment, container, false);
root.post(new Runnable() {
@Override
public void run() {
// for instance
int height = root.getMeasuredHeight();
}
});
return root;
}
使用 ViewTreeObserver
非常整洁,没有杂乱无章.
Very neat and tidy and no messy mucking about with the ViewTreeObserver
.
我只在 android-23 设备上测试过这个,但是 API 从 1 级开始就有这个方法了.
I've only tested this with android-23 devices, but the API has had this method since level 1.
无论如何,WFM.
这篇关于Android 在片段中获取布局高度和宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!