May*_*val 13 android switch-statement custom-component
I using custom switch for support of API 8. I am using THIS Libarary for Custom Switch. But I want to make something Like show in figure.I have tried to change the color ,though changing the color in the style but doesn't effect as i want.

Please help me , Thanks in advance.
esp*_*chi 10
这是一个完整的,有效的解决方案,在实施了这个有趣的一天之后.
使用以下命令设置交换机轨道的drawable.轨道是拇指左右滑动的容器.
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)
尝试使用
android:textOn="On"
android:textOff="Off"
Run Code Online (Sandbox Code Playgroud)
代替
android:text="On"
Run Code Online (Sandbox Code Playgroud)
在开关中。
如果有帮助,您也可以完成此操作。
| 归档时间: |
|
| 查看次数: |
17119 次 |
| 最近记录: |