如何获得线性布局的宽度和高度,该布局在xml中定义为fill_parent的高度和宽度?我试过onmeasure方法,但我不知道为什么它没有给出确切的价值.在oncreate方法完成之前,我需要在Activity中使用这些值.
MGD*_*oid 35
假设我必须得到LinearLayoutXML定义的宽度.我必须通过XML来引用它.定义LinearLayout l为实例.
l = (LinearLayout)findviewbyid(R.id.l1);
ViewTreeObserver observer = l.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
init();
l.getViewTreeObserver().removeGlobalOnLayoutListener(
this);
}
});
protected void init() {
int a= l.getHeight();
int b = l.getWidth();
Toast.makeText(getActivity,""+a+" "+b,3000).show();
}
callfragment();
}
Run Code Online (Sandbox Code Playgroud)
在创建布局之后设置宽度和高度值,放置元素然后测量它们.在第一次调用onSizeChanged时,parms将为0,因此如果您使用该检查.
这里有更多细节 https://groups.google.com/forum/?fromgroups=#!topic/android-developers/nNEp6xBnPiw
在这里http://developer.android.com/reference/android/view/View.html#Layout
以下是如何使用onLayout:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = someView.getWidth();
int height = someView.getHeight();
}
Run Code Online (Sandbox Code Playgroud)
小智 5
要使其工作,您需要检查所需的高度值是否大于 0 - 然后首先删除 onGlobalLayout 侦听器并对该高度执行任何您想要的操作。侦听器连续调用其方法,并且不能保证在第一次调用时正确测量视图。
final LinearLayout parent = (LinearLayout) findViewById(R.id.parentView);
parent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int availableHeight = parent.getMeasuredHeight();
if(availableHeight>0) {
parent.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//save height here and do whatever you want with it
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53043 次 |
| 最近记录: |