2015-06-17 69 views
-1

返回查看高度這裏是我的代碼返回視圖高度:圖高度返回0,我想從onGlobalLayout

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中測量時返回視圖的高度。返回語句不適用於overrided方法。

OR

是否有任何其他的方式讓這些通過傳遞查看實例返回視圖高度的靜態方法。

回答

-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); 
}} 
+0

我嘗試這種方式,它的回報率高度和寬度按屏幕大小。你也得到寬度與relativecontainer.getMeasuredWidth()方法 –

+0

我想從onGlobalLayout()方法返回此高度調用方法。就像int height = getViewHeight(view); –

+0

只是使返回int或u的方法可以將其保存在sharedpreferences中並在需要時將其恢復。 –