布局 getHeight() 和 getWidth() return 从相机获取图像时为 0

layout getHeight() and getWidth() return 0 when getting image from camera

我正在创建一个相框应用程序,当我从画廊获取图像时它工作正常但是当我尝试从相机获取图像时我的 framelayout.getwidth()framelayout.getHeight() 方法 returns 0.

我的代码如下:

btnGetImage.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
            imagePickerDialog();
    }
});

public void imagePickerDialog() {
    AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
    myAlertDialog.setTitle("Pictures Option");
    myAlertDialog.setIcon(R.drawable.getimage_icon);
    myAlertDialog.setMessage("Select Picture From...");
    myAlertDialog.setPositiveButton("Gallery",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                Intent fileIntent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(fileIntent,
                        Constant.FILE_REQUEST);
            }
        });
    myAlertDialog.setNegativeButton("Camera",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                Intent cameraIntent = new Intent(
                        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent,
                        Constant.CAMERA_REQUEST);
            }
        });
    myAlertDialog.show();
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == Constant.CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap camera_image = (Bitmap) data.getExtras().get("data");
        addViewInFrame(camera_image);               
    } else if (requestCode == Constant.FILE_REQUEST
            && resultCode == RESULT_OK) {

        Uri selectedImage = data.getData();
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor c = getContentResolver().query(selectedImage, filePath,
                null, null, null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePath[0]);
        String picturePath = c.getString(columnIndex);
        c.close();
        addViewInFrame(getScaledBitmap(picturePath, 300, 300));
    }
}

public void addViewInFrame(Bitmap viewBit) {
    if (android.os.Build.VERSION.SDK_INT <= 10) {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenWidth = metrics.widthPixels;
        int screenHeight = metrics.heightPixels;

        imageBitmap = Bitmap.createScaledBitmap(viewBit, screenWidth,
            screenHeight / 2, true);
        image1 = new TouchImageView(getApplicationContext());
        image1.setScaleType(ScaleType.MATRIX);
        image1.setImageBitmap(imageBitmap);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
            screenWidth, screenHeight / 2);
        params.leftMargin = 0;
        params.topMargin = 0;
        frame.addView(image1, params);
    else {
        imageBitmap = Bitmap.createScaledBitmap(viewBit,
            frame.getWidth(), frame.getHeight() / 2, true);
        image1 = new TouchImageView(getApplicationContext());
        image1.setScaleType(ScaleType.MATRIX);
        image1.setImageBitmap(imageBitmap);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                frame.getWidth(), frame.getHeight() / 2);
        params.leftMargin = 0;
        params.topMargin = 0;
        frame.addView(image1, params);
}

这里 frame 是我的框架布局。

错误日志为:

Process: com.example.imageoverotherimage, PID: 3065
java.lang.RuntimeException: Unable to resume activity 
{com.example.imageoverotherimage/com.example.imageoverotherimage.MainActivity}: 
java.lang.RuntimeException: Failure delivering result 
ResultInfo{who=null, request=1888, result=-1, data=Intent { 
act=inline-data dat=content://media/external/images/media/6658 (has extras) }} 
to activity {com.example.imageoverotherimage/com.example.imageoverotherimage.MainActivity}: 
java.lang.IllegalArgumentException: width and height must be > 0

    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2996)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3025)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3974)
    at android.app.ActivityThread.access00(ActivityThread.java:166)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5511)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at dalvik.system.NativeStart.main(Native Method)

Caused by: java.lang.RuntimeException: Failure delivering result 
ResultInfo{who=null, request=1888, result=-1, data=Intent { 
act=inline-data dat=content://media/external/images/media/6658 (has extras) }} 
to activity {com.example.imageoverotherimage/com.example.imageoverotherimage.MainActivity}: 
java.lang.IllegalArgumentException: width and height must be > 0

    at android.app.ActivityThread.deliverResults(ActivityThread.java:3601)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2983)
    ... 13 more

Caused by: java.lang.IllegalArgumentException: width and height must be > 0
    at android.graphics.Bitmap.createBitmap(Bitmap.java:922)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:901)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:833)
    at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:709)
    at com.example.imageoverotherimage.MainActivity.addViewInFrame(MainActivity.java:232)
    at com.example.imageoverotherimage.MainActivity.onActivityResult(MainActivity.java:187)
    at android.app.Activity.dispatchActivityResult(Activity.java:5514)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3597)
    ... 14 more

谢谢。

您应该在 onLayout() 事件之后或内部调用 getWidth()getHeight() 方法。这是该过程的更详细描述 How Android Draws Views.

尝试在这个方法中调用frame.getWidth(),你会发现它的结果不同于0

frame.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, 
                               int right, int bottom, 
                               int oldLeft, int oldTop, 
                               int oldRight, int oldBottom) {
        int w = frame.getWidth();
    }
});