旋转屏幕后ImageView的宽度和高度返回0 [重复]

Posted

技术标签:

【中文标题】旋转屏幕后ImageView的宽度和高度返回0 [重复]【英文标题】:ImageView width and height returns 0 after rotating the screen [duplicate] 【发布时间】:2012-11-04 18:49:55 【问题描述】:

我,我开始探索 android,但我有点卡在我的第一个问题上。 旋转屏幕后,我的 ImageView 在宽度和高度上返回 0。我第一次上传照片时它工作正常,但是一旦我翻转屏幕它就会返回 0。我试图在 onResume 和 onRestoresavedInstance 方法中获取它,但我失败了。有谁知道如何解决这个问题?

提前谢谢你。 :)

布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical" >

<EditText
    android:id="@+id/text_email"
    android:layout_
    android:layout_
    android:hint="@string/email" />

<EditText
    android:id="@+id/text_nickname"
    android:layout_
    android:layout_
    android:hint="@string/nickname" />

<Button
    android:id="@+id/button_take_photo"
    android:layout_
    android:layout_
    android:onClick="takePhoto"
    android:text="@string/photo_button" />

<ImageView
    android:id="@+id/image_viewer"
    android:layout_
    android:contentDescription="@string/photo_taken" 
    android:background="@android:color/black" 
    android:layout_
    android:layout_weight="1"
    android:gravity="top"
    android:adjustViewBounds="true" />

</LinearLayout> 

代码

public class MainActivity extends Activity 

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private String fileUri;
private ImageView mImageView;
private EditText nickTextView;
private EditText mailTextView;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initUI();


@Override
public void onResume() 
    super.onResume();
    try 
        if (this.fileUri != null) 
            setPic();
        
     catch (Exception e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;


@Override
public void onSaveInstanceState(Bundle savedInstanceState) 

    // Save UI state changes to the savedInstanceState.
    // This bundle will be passed to onCreate if the process is
    // killed and restarted.

    savedInstanceState.putString("fileUri", this.fileUri);
    savedInstanceState.putString("nick", this.nickTextView.getText()
            .toString());
    savedInstanceState.putString("email", this.mailTextView.getText()
            .toString());
    super.onSaveInstanceState(savedInstanceState);


// onRestoreInstanceState
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) 
    super.onRestoreInstanceState(savedInstanceState);
    this.fileUri = savedInstanceState.getString("fileUri");
    this.nickTextView.setText(savedInstanceState.getString("nick"));
    this.mailTextView.setText(savedInstanceState.getString("email"));


public void takePhoto(View view) 
    if (checkCameraHardware(this)) 
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        this.fileUri = getOutputMediaFilePath();
        File temp = new File(fileUri);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp));
        startActivityForResult(intent,
                MainActivity.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
     else 
        System.out
                .println("This hardware does not support camera features!!!");
    


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) 
        if (resultCode == RESULT_OK) 
            // galleryAddPic();
            try 
                setPic();
             catch (Exception e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
            
         else if (resultCode == RESULT_CANCELED) 
            System.out.println("User cancelled the image capture");
         else 
            System.out.println("Image capture failed, advise user");
        
    


private void initUI() 
    // Get the image view
    mImageView = (ImageView) findViewById(R.id.image_viewer);

    // Get the text views
    nickTextView = (EditText) findViewById(R.id.text_nickname);
    mailTextView = (EditText) findViewById(R.id.text_email);


private String getOutputMediaFilePath() 
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
            .format(new Date());
    String imageFileName = "liftoff_" + timeStamp + ".jpg";
    File image = new File(storageDir, imageFileName);
    return image.getAbsolutePath();


private boolean checkCameraHardware(Context context) 
    if (context.getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) 
        // this device has a camera
        return true;
     else 
        // no camera on this device
        return false;
    


private void galleryAddPic() 
    Intent mediaScanIntent = new Intent(
            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(fileUri);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);


private void setPic() throws Exception 

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(fileUri, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Get the dimensions of the View
    int targetH = mImageView.getHeight();
    int targetW = mImageView.getWidth();

    // Put correct orientation
    Matrix matrix = new Matrix();
    ExifInterface exif = new ExifInterface(this.fileUri);
    String orientation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
    if (orientation.equals(ExifInterface.ORIENTATION_NORMAL)) 
        // Do nothing. The original image is fine.
     else if (orientation.equals(ExifInterface.ORIENTATION_ROTATE_90 + "")) 
        photoW = bmOptions.outHeight;
        photoH = bmOptions.outWidth;
        matrix.postRotate(90);
     else if (orientation
            .equals(ExifInterface.ORIENTATION_ROTATE_180 + "")) 
        matrix.postRotate(180);
     else if (orientation
            .equals(ExifInterface.ORIENTATION_ROTATE_270 + "")) 
        matrix.postRotate(270);
        photoW = bmOptions.outHeight;
        photoH = bmOptions.outWidth;
    

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(fileUri, bmOptions);

    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
            bitmap.getWidth(), bitmap.getHeight(), matrix, true);

    mImageView.setImageBitmap(resizedBitmap);

【问题讨论】:

嗨,欢迎来到安卓 :)。我们将需要一些代码或布局来帮助您。只是为了开始,你的布局文件在哪里?你有两个方向的布局(纵向和横向) 【参考方案1】:

确保视图已完成其布局过程。试试this。

【讨论】:

您好,谢谢!基本上上面的代码只是一个实验,所以它可能没有意义。这是为了试验相机的功能。结果我只有一个布局,事情是我希望我的图片在旋转屏幕时缩放到正确的大小。我已经用代码编辑了问题。

以上是关于旋转屏幕后ImageView的宽度和高度返回0 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何根据视频的高度和宽度设置屏幕方向

如何获取屏幕的宽度

如何获取ImageView的高度和宽度?

如何在快速屏幕旋转后获得视图的高度?

根据视频宽度和高度旋转屏幕

我如何同时传递 x 和 y 轴以及屏幕的高度和宽度以快速以编程方式截取屏幕截图