我有一个可以在男性和女性之间选择的开关。
因此,我将textOff和textOn分别设置为“男性”和“女性”,但根据开关位置的不同,只显示男性或女性中的一个。
怎样才能同时显示男性和女性?
所以,在ascii-art中
我有过
[Male / ]
or
[ / Female ]但我想
[**Male** / Female]
[Male / **Female**]发布于 2015-10-07 05:47:52
你可以,但这有点麻烦。
下面是我为实现这一点所做的工作:

我使用一个自定义的可绘制开关的轨迹。(轨迹是拇指在其中左右滑动的容器。)
mMessengerSwitch.setTrackDrawable(new SwitchTrackTextDrawable(this,
"LEFT", "RIGHT"));下面是SwitchTrackTextDrawable的实现,它在后台准确地将文本写入正确的位置(好吧,我只在Nexus5上测试了API23):
/**
* Drawable that generates the two pieces of text in the track of the switch, one of each
* side of the positions of the thumb.
*/
public class SwitchTrackTextDrawable extends Drawable {
private final Context mContext;
private final String mLeftText;
private final String mRightText;
private final Paint mTextPaint;
public SwitchTrackTextDrawable(@NonNull Context context,
@StringRes int leftTextId,
@StringRes int rightTextId) {
mContext = context;
// Left text
mLeftText = context.getString(leftTextId);
mTextPaint = createTextPaint();
// Right text
mRightText = context.getString(rightTextId);
}
private Paint createTextPaint() {
Paint textPaint = new Paint();
//noinspection deprecation
textPaint.setColor(mContext.getResources().getColor(android.R.color.white));
textPaint.setAntiAlias(true);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setTextAlign(Paint.Align.CENTER);
// Set textSize, typeface, etc, as you wish
return textPaint;
}
@Override
public void draw(Canvas canvas) {
final Rect textBounds = new Rect();
mTextPaint.getTextBounds(mRightText, 0, mRightText.length(), textBounds);
// The baseline for the text: centered, including the height of the text itself
final int heightBaseline = canvas.getClipBounds().height() / 2 + textBounds.height() / 2;
// This is one quarter of the full width, to measure the centers of the texts
final int widthQuarter = canvas.getClipBounds().width() / 4;
canvas.drawText(mLeftText, 0, mLeftText.length(),
widthQuarter, heightBaseline,
mTextPaint);
canvas.drawText(mRightText, 0, mRightText.length(),
widthQuarter * 3, heightBaseline,
mTextPaint);
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}发布于 2013-12-12 06:55:44
您可以制作两个同时具有这两个功能的图像(一个图像用于打开切换,一个用于关闭切换),然后创建一个selector。
只需将textOn和textOff更改为空字符串。
发布于 2013-12-13 15:52:05
我发现获得我想要的外观的最简单的方法是一对相邻的、相邻的按钮。Onclick,我交换了背景颜色。
https://stackoverflow.com/questions/20531538
复制相似问题