在Android Swtich中更改textOn和textOff的位置

时间:2015-11-12 19:41:51

标签: android android-xml

我已经用这种方式实现了Switch Widget:

<android.support.v7.widget.SwitchCompat xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textOff="@string/switch_on"
            android:textOn="@string/switch_on"
            app:showText="true"
            android:gravity="right"
            android:thumb="@drawable/slider_thumb"
            app:switchMinWidth="200dp"
            app:track="@drawable/slider_tracker">

除了将文字写在拇指顶部之外,一切正常。我想要实现的是让文本显示在轨道上。因此,假设选中了开关,文本将显示在左侧,未选中时,textOff将显示在右侧。

Something like the image

我怎样才能做到这一点。感谢

1 个答案:

答案 0 :(得分:0)

我想通过在位图上绘制文本,生成可从中绘制的位图并将开关的轨道可绘制更改为bitmapdrawable来实现此目的。

基本上,我使用下面的代码段来实现这一点。

BitmapDrawable bitmapDrawable = new BitmapDrawable(drawTextToBitmap(this, R.drawable.test_, "Slide to Sign In"));
        switchCompat.setTrackDrawable(bitmapDrawable);

 public Bitmap drawTextToBitmap(Context gContext,
                                   int gResId,
                                   String gText) {
        Resources resources = gContext.getResources();
        float scale = resources.getDisplayMetrics().density;
        Bitmap bitmap =
                BitmapFactory.decodeResource(resources, gResId);

        android.graphics.Bitmap.Config bitmapConfig =
                bitmap.getConfig();
        // set default bitmap config if none
        if (bitmapConfig == null) {
            bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
        }
        // resource bitmaps are imutable,
        // so we need to convert it to mutable one
        bitmap = bitmap.copy(bitmapConfig, true);

        Canvas canvas = new Canvas(bitmap);
        // new antialised Paint
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // text color - #3D3D3D
        paint.setColor(Color.rgb(61, 61, 61));
        // text size in pixels
        paint.setTextSize((int) (10 * scale));
        // text shadow
        paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);

        // draw text to the Canvas center
        Rect bounds = new Rect();
        paint.getTextBounds(gText, 0, gText.length(), bounds);
        int x = (bitmap.getWidth() - (170));
        int y = (bitmap.getHeight() + bounds.height()) / 2;

        canvas.drawText(gText, x, y, paint);

        return bitmap;
    }

至于开关打开和关闭时更换drawable,可以使用

进行播放
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            }
        });