View Height返回0,我想从onGlobalLayout

时间:2015-06-17 08:34:32

标签: android layout view

这是我的代码返回高度:

int height = 0;
public int getViewHeight(final View v) {
        v.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {

                    @SuppressLint("NewApi")
                    @SuppressWarnings("deprecation")
                    @Override
                    public void onGlobalLayout() {
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                            v.getViewTreeObserver()
                                    .removeGlobalOnLayoutListener(this);
                        } else {
                            v.getViewTreeObserver()
                                    .removeOnGlobalLayoutListener(this);
                        }
                        height = v.getMeasuredHeight();
//
                        Log.v(" height", v.getMeasuredHeight() + "");
                    }
                });

        Log.v(" return height", v.getMeasuredHeight() + "");
        return height;


    }

首先它返回0.然后高度值改变。 任何人都可以让我知道如何在onGlobalLayout中测量时返回视图的高度。返回声明不适用于覆盖方法。

OR

有没有其他方法可以通过传递View实例来创建一个返回视图高度的静态方法。

1 个答案:

答案 0 :(得分:-1)

***try this way* 
i get View Height and Width as per View**

public class Test extends Activity {

private RelativeLayout layout;
private int temp;
ViewTreeObserver vto;
SharedPreferences sharedPreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    sharedPreferences = getSharedPreferences("savePref",
            Context.MODE_PRIVATE);

    layout = (RelativeLayout) findViewById(R.id.layout);
    temp = set(layout);
    Log.e("temp", "" + sharedPreferences.getInt("key", 0));
}
private int set(final RelativeLayout layout) {
    vto = layout.getViewTreeObserver();
    final Editor editor = sharedPreferences.edit();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onGlobalLayout() {
            layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            temp = layout.getMeasuredHeight();
            editor.putInt("key", temp);
            editor.commit();
        }
    });
    if (sharedPreferences.contains("key")) {
        Log.e("contains", "" + sharedPreferences.getInt("key", 0));
    }
    return sharedPreferences.getInt("key", 0);
}}