2013-05-05 26 views
0

我有這樣的XML代碼的寬度和喚起注意:如何獲得ImageView的

<LinearLayout 
android:id="@+id/linearLayoutInner" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="@layout/gallery_image_background" 
/> 

那麼這個代碼:

LinearLayout linearLayoutInner = (LinearLayout) findViewById(R.id.linearLayoutInner); 
ImageView imageView = new ImageView(thisActivityContext); 
imageView.setImageResource(R.drawable.example); 
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 
imageView.setLayoutParams(lp); 
linearLayoutInner.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL); 
linearLayoutInner.addView(imageView); 

我再調用自身的功能,是爲了擴大位圖直到其中一個邊緣到達邊緣(即,如果原始bitmat是高度的兩倍,則它將保持imageview內部的比例,這顯然不受任何scaletype設置支持):

SharedCode.sharedUtilScaleImage(imageView); 

問題來了。該函數需要知道包含可繪製位圖的視圖的大小。如果imageView行爲正確,則應使用MATCH_PARENT,並因此給出linearLayoutInner的寬度/高度。但是,下面的代碼返回零:

int heightParent = max(imageView.getLayoutParams().height, imageView.getHeight());  
int widthParent = max(imageView.getLayoutParams().width, imageView.getWidth()); 

如何解決此問題?爲什麼我返回0而不是正確的高度/寬度?

回答

3

在調用View的onMeasure()之前,您可能過早調用代碼。在此之前,它的大小是未知的。

final ImageView iv.... 
ViewTreeObserver vto = iv.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
     //Measure 
     iv.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
    } 
}); 
+0

(Upvoted)在什麼時候叫這個onMeasure? (如果它只被調用一次,我想我可以創建一些等待的代碼。)我需要能夠根據需要傳遞ImageView引用。在初始創建後,imageview/linearlayout的高度/寬度應該不會改變**。 (當然,bimaps的改變對應於另一個控件上的點擊事件) – Tom 2013-05-05 13:04:30

+1

@Tom onMeasure()在第一次繪製視圖之前調用一次,並且每當大小改變時再次調用它。 – 2013-05-05 13:05:33

+0

只是爲了確認,這個解決方案的工作:) – Tom 2013-05-09 11:55:49

3
final ImageView imageView = (ImageView)findViewById(R.id.image_test); 
    ViewTreeObserver vto = imageView.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      imageView .getViewTreeObserver().removeGlobalOnLayoutListener(this); 
      imageView.getHeight(); // This will return actual height. 
      imageView.getWidth(); // This will return actual width. 
     } 
    });  
+0

(Upvoted)謝謝你的答案。我仍然覺得很奇怪,在** onWindowFocusChanged()**上甚至無法訪問height/width,但是我會嘗試使用這個方法,並嘗試將它與我現有的代碼結合起來。 – Tom 2013-05-05 13:07:15

1

看起來像你可能從onCreate()被調用。你需要等待活動窗口附加,然後致電getWidth()getHeight()imageView。您可以嘗試撥打getWidth()getHeight()onWindowFocusChanged()您的活動的方法。

編輯

@Override 
public void onWindowFocusChanged(boolean hasFocus){ 
    int width=imageView.getWidth(); 
    int height=imageView.getHeight(); 
} 
+0

(Upvoted)從onWindowFocusChanged調用沒有區別:( – Tom 2013-05-05 13:01:53

相關問題