gpt4 book ai didi

java - 旋转开关 View 的剪辑

转载 作者:行者123 更新时间:2023-12-02 11:50:51 24 4
gpt4 key购买 nike

我正在尝试在 Android 应用中旋转 Switch。我知道 android:rotation 参数,但由于这是应用程序的常见部分,因此我正在构建一个扩展 switch 的自定义 View 。默认情况下,对 View 应用旋转会保留未旋转 View 的原始尺寸,因此此实现应切换宽度和高度参数以适应新的方向:

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 .

这是结果(第一个开关),后面是一个 Switchandroid:rotation 参数为 -90,然后是一系列没有旋转的正常 Switch View ( View 边界已打开):

A row of switches with view bounds shown. The first is vertical, but placed lower than the others with the bottom half cut off, the second is correctly vertical, and the remainder are normal horizontal switches.

您可以从绘图 View 边界中看到,带有旋转的普通 Switch 通常会在视觉上被剪切,因为可绘制对象会延伸到边界之外,从而保留水平开关的原始尺寸。然而,自定义 VerticalSwitch 具有正确的高度(这允许第二个开关显示完整的可绘制对象),但是可绘制对象偏移到 View 的下半部分,并且可绘制对象仍被剪裁在下方 View 底部处于水平配置。

检查调试器中的大小调整参数表明,新的旋转尺寸已正确应用,但裁剪仍在发生。是什么导致了偏移和削波?如何纠正?

最佳答案

无需创建垂直自定义Switch,您可以使用android:rotation="90"作为垂直Switch

您只需为您的Switch 提供静态高度试试这个

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp">

<Switch
android:layout_width="wrap_content"
android:layout_height="60dp"
android:rotation="90" />

<Switch
android:layout_width="wrap_content"
android:layout_height="60dp"
android:rotation="90" />


<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


</LinearLayout>

输出

enter image description here

关于java - 旋转开关 View 的剪辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47883209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com