我可以在开关中同时显示 textOn 和 textOff 吗?

pin*_*yid 4 android android-layout

我有一个可以在男性和女性之间进行选择的开关。

因此,我将 textOff 和 textOn 分别设置为“男性”和“女性”,但仅显示男性或女性之一,具体取决于开关位置。

我怎样才能让它同时显示男性和女性?

所以,在 ascii-art 中

我有

[Male /        ]
or 
[     / Female ]
Run Code Online (Sandbox Code Playgroud)

但我想要

[**Male** / Female]
[Male / **Female**]
Run Code Online (Sandbox Code Playgroud)

esp*_*chi 5

可以啊,不过有点麻烦。

这是我为得到这个所做的事情:

自定义开关示例

我使用自定义绘图作为开关的轨道。(轨道是拇指在其中左右滑动的容器。)

mMessengerSwitch.setTrackDrawable(new SwitchTrackTextDrawable(this,
        "LEFT", "RIGHT"));
Run Code Online (Sandbox Code Playgroud)

下面是 的实现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;
    }
}
Run Code Online (Sandbox Code Playgroud)