【发布时间】:2018-06-01 15:59:34
【问题描述】:
我正在尝试在 Android 应用中旋转 Switch。我知道android:rotation 参数,但由于这是应用程序的常见部分,我正在构建一个扩展开关的自定义视图。默认情况下,对视图应用旋转会保持未旋转视图的原始尺寸,因此此实现应切换宽度和高度参数以适应新方向:
public class VerticalSwitch extends Switch {
// Init method called from all constructors
private void init(Context context, …) {
// Rotate the view
setRotation(switchOrientation.ordinal()*90);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
int height = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
int desiredWidth = height + getPaddingLeft() + getPaddingRight();
int desiredHeight = width + getPaddingTop() + getPaddingBottom();
//noinspection SuspiciousNameCombination
setMeasuredDimension(measureDimension(desiredWidth, widthMeasureSpec),
measureDimension(desiredHeight, heightMeasureSpec));
}
private int measureDimension(int desiredSize, int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = desiredSize;
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
if (result < desiredSize){
Log.e(TAG, "The view is too small, the content might get cut");
}
return result;
}
}
这使用了一种修复建议的大小的方法in this article by Lorenzo Quiroli。
这是结果(第一次切换),接着是一个普通的Switch,带有一个-90 的android:rotation 参数,然后是一系列没有旋转的普通Switch 视图(视图边界已打开) :
您可以从绘图视图边界中看到,带有旋转的普通Switch 通常在视觉上被剪裁,因为可绘制对象延伸到边界之外,这保留了水平开关的原始尺寸。然而,自定义VerticalSwitch 具有正确的高度(这允许第二个开关显示完整的可绘制对象),但是可绘制对象偏移到视图的下半部分,并且可绘制对象仍被剪辑在底部的下方视图处于水平配置。
在调试器中检查调整大小的参数表明新的旋转尺寸正在正确应用,但裁剪仍在发生。什么原因导致偏移和削波,如何纠正?
【问题讨论】:
标签: java android rotation android-view clipping