我有一个开关,可以选择男性和女性。
所以我将textOff和textOn分别设置为'male'和'female',但根据开关位置,只显示男性或女性中的一个。
如何展示男性和女性?
所以,在ascii-art中
我有
[Male / ]
or
[ / Female ]
但我想要
[**Male** / Female]
[Male / **Female**]
答案 0 :(得分:1)
嗯,你可以,但这有点麻烦。
以下是我为此做到的事情:
我使用自定义drawable来跟踪开关。 (轨道是拇指向左和向右滑动的容器。)
mMessengerSwitch.setTrackDrawable(new SwitchTrackTextDrawable(this,
"LEFT", "RIGHT"));
这是SwitchTrackTextDrawable
的实现,它将背景中的文本准确地写在正确的位置(好吧,我只在Nexus 5上测试了它的API 23):
/**
* 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;
}
}
答案 1 :(得分:0)
你可以制作两张同时具有两个图像(一个用于打开和关闭的图像),然后创建一个selector。
只需将textOn和textOff更改为空字符串。
答案 2 :(得分:0)
我找到了最简单的方法来获得我正在寻找的外观是一对相邻的邻接按钮。 Onclick,我交换背景颜色。