自定义TextView将数据传递给onDraw

时间:2015-01-01 19:20:29

标签: android textview android-custom-view

我需要自定义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个值传递给自定义textview?因为我上面的代码不起作用。

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

1 个答案:

答案 0 :(得分:3)

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

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