Как установить рамку вокруг текста текстового представления - PullRequest
1 голос
/ 06 октября 2019

Я начну с объяснения, что то, что я хочу получить, - это не граница вокруг самого представления, а на самом деле это граница вокруг текста внутри textview.

Я уже пытался установить тень внутри textviewи на style.xml, и ни одно из этих решений не сработало. Я пытался заставить приведенный ниже код работать, но я далеко не хороший разработчик, поэтому я даже не знаю, как его использовать. Все, что я знаю, - это то, что это подразумевает рефлексию (но не то, что я знаю, что это значит).

Мой класс Java (OutlineTextView)

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatTextView;

import com.example.detetiveinvestigativo.R;

import java.lang.reflect.Field;

public class OutlineTextView extends AppCompatTextView {
    private Field colorField;
    private int textColor;
    private int outlineColor;

    public OutlineTextView(Context context) {
        this(context, null);
    }

    public OutlineTextView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public OutlineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        try {
            colorField = TextView.class.getDeclaredField("mCurTextColor");
            colorField.setAccessible(true);

            // If the reflection fails (which really shouldn't happen), we
            // won't need the rest of this stuff, so we keep it in the try-catch

            textColor = getTextColors().getDefaultColor();

            // These can be changed to hard-coded default
            // values if you don't need to use XML attributes

            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OutlineTextView);
            outlineColor = a.getColor(R.styleable.OutlineTextView_outlineColor, Color.TRANSPARENT);
            setOutlineStrokeWidth(a.getDimensionPixelSize(R.styleable.OutlineTextView_outlineWidth, 0));
            a.recycle();
        }
        catch (NoSuchFieldException e) {
            // Optionally catch Exception and remove print after testing
            e.printStackTrace();
            colorField = null;
        }
    }

    @Override
    public void setTextColor(int color) {
        // We want to track this ourselves
        // The super call will invalidate()

        textColor = color;
        super.setTextColor(color);
    }

    public void setOutlineColor(int color) {
        outlineColor = color;
        invalidate();
    }

    public void setOutlineWidth(float width) {
        setOutlineStrokeWidth(width);
        invalidate();
    }

    private void setOutlineStrokeWidth(float width) {
        getPaint().setStrokeWidth(2 * width + 1);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // If we couldn't get the Field, then we
        // need to skip this, and just draw as usual

        if (colorField != null) {
            // Outline
            setColorField(outlineColor);
            getPaint().setStyle(Paint.Style.STROKE);
            super.onDraw(canvas);

            // Reset for text
            setColorField(textColor);
            getPaint().setStyle(Paint.Style.FILL);
        }

        super.onDraw(canvas);
    }

    private void setColorField(int color) {
        // We did the null check in onDraw()
        try {
            colorField.setInt(this, color);
        }
        catch (IllegalAccessException | IllegalArgumentException e) {
            // Optionally catch Exception and remove print after testing
            e.printStackTrace();
        }
    }

    // Optional saved state stuff

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);
        ss.textColor = textColor;
        ss.outlineColor = outlineColor;
        ss.outlineWidth = getPaint().getStrokeWidth();
        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        textColor = ss.textColor;
        outlineColor = ss.outlineColor;
        getPaint().setStrokeWidth(ss.outlineWidth);
    }

    private static class SavedState extends BaseSavedState {
        int textColor;
        int outlineColor;
        float outlineWidth;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            textColor = in.readInt();
            outlineColor = in.readInt();
            outlineWidth = in.readFloat();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(textColor);
            out.writeInt(outlineColor);
            out.writeFloat(outlineWidth);
        }

        public static final Parcelable.Creator<SavedState>
                CREATOR = new Parcelable.Creator<SavedState>() {

            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="OutlineTextView" >
        <attr name="outlineColor" format="color" />
        <attr name="outlineWidth" format="dimension" />
    </declare-styleable>
</resources>

my_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context=".Interface.CharacterSelection.CharacterSelectionFragment"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="7dp"
    android:paddingBottom="7dp"
    android:background="@drawable/wood_texture"
    android:clickable="true"
    android:focusable="false"
    android:id="@+id/cs_parent_layout">

<androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/cs_textview_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/select_characters"
        android:textSize="25sp"
        android:textColor="@color/white"
        android:fontFamily="@font/joystix_monospace"
        app:outlineColor="@color/black"
        app:outlineWidth="4dp"
        android:gravity="center"
        android:layout_marginBottom="7dp"
        android:clickable="false"/>
</androidx.appcompat.widget.LinearLayoutCompat>

Как мне использовать этот класс? Как мне преобразовать AppCompatTextView в OutlineTextView и что мне нужно, чтобы он работал?

РЕДАКТИРОВАТЬ:

Это то, что я хочу сделать, это буквально положить черныйрамка вокруг текста: нажмите здесь, чтобы увидеть изображение

1 Ответ

0 голосов
/ 06 октября 2019

Вы можете использовать тени. Код ниже создает черную тень вокруг текста. Чтобы изменить цвет, измените поле shadowColor. ShadowDy - это вертикальное смещение тени и смещение shadowDx по горизонтали.

android:shadowColor="#000000"
android:shadowRadius="5"
android:shadowDy="2"
android:shadowDx="2"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...