自定义TextView传数据给onDraw

Custom TextView pass data to onDraw

我需要自定义 TextView(带边框效果的文本)。我有如下代码。

public class BorderTextView extends TextView {

    private int textSize;
    private String strokeColor;
    private String textColor;
    private String text;
    private Canvas canvas;

    public BorderTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public String getMyStrokeColor() {
        return strokeColor;
    }

    public String getMyTextColor() {
        return textColor;
    }

    public String getMyText() {
        return text;
    }

    public int getMyTextSize() {
        return textSize;
    }

    public void setParameters(String strokeColor, String textColor, String text, int textSize) {
        this.textSize = textSize;
        this.strokeColor = strokeColor;
        this.textColor = textColor;
        this.text = text;
    }


    @Override
    protected void onDraw(Canvas canvas) {

         if (getMyStrokeColor() != null) {
           Paint paint = new Paint();
           paint.setColor(Color.parseColor(getMyStrokeColor()));
           paint.setTextSize(getMyTextSize());
           paint.setStyle(Paint.Style.STROKE);
           paint.setStrokeWidth(getTextSize() / 5);
           paint.setAntiAlias(true);
           paint.setTextAlign(Paint.Align.CENTER);

           int xPos = (canvas.getWidth() / 2);
           int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() +
           paint.ascent()) / 2));

           canvas.drawText(getMyText(), xPos, yPos, paint);

           paint.setStrokeWidth(0f);
           paint.setColor(Color.parseColor(getMyTextColor()));
           paint.setTextSize(getMyTextSize());

           canvas.drawText(getMyText(), xPos, yPos, paint);
         }
    }

}

在 XML 中:

                <com.app.widget.BorderTextView
                    android:id="@+id/category"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:layout_centerInParent="true"
                    android:gravity="center" />

并且在活动中:

private BorderTextView category;
category = (BorderTextView) rootView.findViewById(R.id.category);

category = new BorderTextView(getActivity(), null);
category.setParameters("#000000", firstColor, secondColor, 60);

如何将这 4 个值传递到我的自定义文本视图?因为我上面的代码不起作用。

它不起作用,因为我的值是空的。

您正在将 category 初始化为布局中定义的 BorderTextView,但随后您正在实例化 BorderTextView 的新实例并将其分配给 category .您调用 setParameters() 的实例不是屏幕上的实例,因此不是正在绘制的实例。删除行:

category = new BorderTextView(getActivity(), null);