我正在尝试将 BoD ( https://github.com/BoD/android-switch-backport ) 的反向移植开关旋转 90°。我玩过 Switch 类,最后我设法让它看起来不错(http://img706.imageshack.us/img706/8662/oslz.jpg)。但是,它不能正常工作。如果我尝试切换按钮,它会被绘制在视图下方的某个位置,所以我只看到它的一部分。
我在 BoD 的原始 Switch 中编辑了 onMeasure() 和 onDraw() 方法:
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (mOnLayout == null) {
mOnLayout = makeLayout(mTextOn);
}
if (mOffLayout == null) {
mOffLayout = makeLayout(mTextOff);
}
mTrackDrawable.getPadding(mTempRect);
final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth());
final int switchWidth = Math.max(mSwitchMinWidth, maxTextWidth * 2 + mThumbTextPadding * 4 +
mTempRect.left+ mTempRect.right);
final int switchHeight = mTrackDrawable.getIntrinsicHeight();
mThumbWidth = maxTextWidth + mThumbTextPadding * 2;
switch (widthMode) {
case MeasureSpec.AT_MOST:
widthSize = Math.min(widthSize, switchWidth);
break;
case MeasureSpec.UNSPECIFIED:
widthSize = switchWidth;
break;
case MeasureSpec.EXACTLY:
// Just use what we were given
break;
}
switch (heightMode) {
case MeasureSpec.AT_MOST:
heightSize = Math.min(heightSize, switchHeight);
break;
case MeasureSpec.UNSPECIFIED:
heightSize = switchHeight;
break;
case MeasureSpec.EXACTLY:
// Just use what we were given
break;
}
这是编辑后的代码 - 我替换了这个块:
mSwitchWidth = switchWidth;
mSwitchHeight = switchHeight
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int measuredHeight = getMeasuredHeight();
if (measuredHeight < switchHeight) {
setMeasuredDimension(getMeasuredWidth(), switchHeight);
}
}
有了这个:
mSwitchWidth = switchHeight;
mSwitchHeight = switchWidth;
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
final int measuredWidth = getMeasuredWidth();
if (measuredWidth < switchWidth) {
//setMeasuredDimension(getMeasuredWidthAndState(), switchHeight);
setMeasuredDimension(switchHeight, switchWidth);
}
}
我将这两行添加到 onDraw() 方法中:
canvas.translate(getWidth(), 0);
canvas.rotate(90);
我在这里通过 BoD 上传了 Switch 的原始代码:http://pastebin.com/8CU9ybET 我也想知道,在 onLayout() 方法中使用了 mSwitchWidth 和 mSwitchHeight,所以也许我也应该以某种方式调整它......谢谢你有任何想法ppl ;)