2014-03-24 44 views
0

我試圖讓機器人的ImageView的高度&寬度它返回0如何獲取ImageView的高度和寬度?

public class FullScreenImage extends FragmentActivity { 
    ImageView full_view; 
    int width; 
    int height; 
    @Override 
    protected void onCreate(Bundle arg0) { 
     super.onCreate(arg0); 

     setContentView(R.layout.full_screen); 

     full_view = (ImageView)findViewById(R.id.full_view); 

     Bundle bundle=getIntent().getExtras(); 
     byte[] image= bundle.getByteArray("image"); 

     width  =  full_view.getWidth(); 
     height  =  full_view.getHeight(); 

     Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length); 
     Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true); 

     full_view.setImageBitmap(resized); 
    } 


} 

請大家幫幫我,我該怎麼做呢?

回答

3

新Android開發人員犯的常見錯誤是在其構造函數中使用視圖的寬度和高度。當視圖的構造函數被調用時,Android不知道視圖有多大,所以尺寸設置爲零。實際尺寸是在佈局階段計算的,佈局階段是在施工之後但在繪製任何東西之前進行的。您可以使用onSizeChanged()方法獲知這些值的已知時間,也可以稍後使用getWidth()getHeight()方法,例如在onDraw()方法中。

+0

除到Farhan已經提到的你也可以看一下'http:// developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html' – Anuj

0

如果你第一次得到的高度和寬度當時沒有可用的圖像,結果爲0。

請使用此代碼:

setContentView(R.layout.full_screen); 

    full_view = (ImageView)findViewById(R.id.full_view); 

    Bundle bundle=getIntent().getExtras(); 
    byte[] image= bundle.getByteArray("image"); 


    Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length); 
    Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true); 

    full_view.setImageBitmap(resized); 

    width  =  full_view.getWidth(); 
    height  =  full_view.getHeight(); 
1

看到this

int finalHeight, finalWidth; 
final ImageView iv = (ImageView)findViewById(R.id.scaled_image); 
final TextView tv = (TextView)findViewById(R.id.size_label); 
ViewTreeObserver vto = iv.getViewTreeObserver(); 
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { 
public boolean onPreDraw() { 
    finalHeight = iv.getMeasuredHeight(); 
    finalWidth = iv.getMeasuredWidth(); 
    tv.setText("Height: " + finalHeight + " Width: " + finalWidth); 
    return true; 
    } 
});