2016-10-04 61 views
1

在我的Activity中,我有SurfaceView用于显示摄像头预览和几个控制按钮。这Activity应该有两个工作案例:第一个,当方向是风景,相机预览比率设置为4:3时,第二个,当方向是肖像,并且相机预览应该是尖锐的。 我真正想要做的只是根据方向调整视图。 我已经尝试通过将android:configChanges="orientation|screenSize"添加到我在manifest中的活动描述中来处理方向更改,但是这里的问题甚至被认为是onCreate()方法未调用,活动组件已重新排列。我想这发生在我拨打super.onConfigurationChanged(null);(我无法避免,因为我会得到例外)。 所以我的问题是,如果有可能实现我试图达到的效果?或者我别无选择,只能针对不同的方向有两个单独的布局,并允许重新创建活动? This is how my acitivyt look like in portrait mode And this is what I get when rotate my device在不触及布局的情况下捕捉Android活动的方向变化

回答

0

如果要做到这一点没有每个方向单独的布局,可以只是调整纵横比的方法的子类SurfaceView(或TextureView)。这实际上是在Camera sample applications Android团队使用方法:

public class AutoFitTextureView extends TextureView { 

    private int mRatioWidth = 0; 
    private int mRatioHeight = 0; 

    public AutoFitTextureView(Context context) { 
     this(context, null); 
    } 

    public AutoFitTextureView(Context context, AttributeSet attrs) { 
     this(context, attrs, 0); 
    } 

    public AutoFitTextureView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 

    public void setAspectRatio(int width, int height) { 
     if (width < 0 || height < 0) { 
      throw new IllegalArgumentException("Size cannot be negative."); 
     } 
     mRatioWidth = width; 
     mRatioHeight = height; 
     requestLayout(); 
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
     int width = MeasureSpec.getSize(widthMeasureSpec); 
     int height = MeasureSpec.getSize(heightMeasureSpec); 
     if (0 == mRatioWidth || 0 == mRatioHeight) { 
      setMeasuredDimension(width, height); 
     } else { 
      if (width < height * mRatioWidth/mRatioHeight) { 
       setMeasuredDimension(width, width * mRatioHeight/mRatioWidth); 
      } else { 
       setMeasuredDimension(height * mRatioWidth/mRatioHeight, height); 
      } 
     } 
    } 

} 

那你还不需要重写onConfigurationChanged,所有你需要做的是检查设备的方向onResume之后的某个时间:

int orientation = getResources().getConfiguration().orientation; 
if(orientation == Configuration.ORIENTATION_LANDSCAPE) { 
    mAutoFitTextureView.setAspectRatio(width, height); 
} else { 
    mAutoFitTextureView.setAspectRatio(width, width); 
} 
+0

谢谢您的建议,Bryan。但是这种方法假设活动应该暂停然后重新开始。也许从我的信息来看,这并不清楚,但是当我的活动正在运行时,我需要处理方向的变化,并且想要达到效果,当除了表面变化之外没有可见的变化,在工作期间改变它的尺寸并且没有停顿(但我仍然不确定Android SDK是否有工具)。 – Yurii

相关问题