2015-10-16 39 views
0

我的ImageView在XML:ImageView的回報爲零的getWidth

<ImageView 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:id="@+id/ivManagePhoto" 
        android:layout_marginTop="10dp" 
        android:layout_marginLeft="10dp" 
        android:layout_marginRight="10dp" /> 

我的代碼:

ImageView ivManagePhoto; 
    ivManagePhoto = (ImageView)findViewById(R.id.ivManagePhoto); 
    double ivw = ivManagePhoto.getWidth(); 

當我試圖讓ivManagePhoto.getWidth();返回0,但我需要得到mathparent大小。

+0

想要屏幕寬度尺寸? – Manishika

+0

@ Manishika,屏幕寬度尺寸= 480,寬度imageView =〜400。我需要得到這個400 – user3712384

回答

1

你可以試試這個:

imageView.post(new Runnable() { 
      @Override 
      public void run() { 
       imageView.getWidth(); 
      } 
     }); 

,或者試試這個:

ViewTreeObserver viewTreeObserver = rootLayout.getViewTreeObserver(); 
if (viewTreeObserver.isAlive()) { 
    viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
     rootLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
     viewWidth = view.getWidth(); 
    } 
    }); 
} 

希望這個代碼將幫助你。

+0

不工作,並獲得簡單的寬度代碼:/ – user3712384

+0

imageView!的大小=屏幕大小。 – user3712384

+0

行..試試看這個問題的答案:http://stackoverflow.com/questions/3591784/getwidth-and-getheight-of-view-returns-0 –

0

您可以等待onwindowfocuschanged事件。此時UI項目已加載

@Override 
public void onWindowFocusChanged(boolean hasFocus) { 

    super.onWindowFocusChanged(hasFocus); 
    if (hasFocus) { 
     //get sizes you want 
     Point screen_size=new Point(); 
     getWindowManager().getDefaultDisplay().getSize(screen_size); 
     int width = screen_size.x; 
     int height = screen_size.y; 
     //... 
    } 
    //... 
}