简体   繁体   English

如何制作自定义textView?

[英]How to make custom textView?

My TextViews xml file 我的TextViews xml文件

<com.example.blabla.HateTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/hate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text" />

Next code 下一个代码

public class HateTextView extends android.support.v7.widget.AppCompatTextView {

    Paint mTxtPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private String str = " ";

    HateTextView(Context context, AttributeSet attrs){
        super(context, attrs);
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.HateTextView);
        a.recycle();
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint.FontMetrics fm = new Paint.FontMetrics();
        mTxtPaint.setColor(Color.parseColor("#d00000"));
        mTxtPaint.setTextSize(20 * getResources().getDisplayMetrics().density);
        mTxtPaint.getFontMetrics(fm);
        mTxtPaint.isAntiAlias();

        int margin = 5;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            canvas.drawRoundRect(90 - margin, 100 + fm.top - margin,
                    115 + mTxtPaint.measureText(str) + margin, 100 + fm.bottom + margin,35,35, mTxtPaint);
        }

        mTxtPaint.setColor(Color.WHITE);
        canvas.drawText(str, 100, 100, mTxtPaint);
    }

    public void setTextHate(String hate) {
        str = hate;
    }
}

I create something like this: 我创建这样的东西:

HateTextView h = itemView.findViewById(R.id.hate);
h.setTextHate("some text..");
h.setRotation(number);

just because of the rotation so many problems. 只是因为轮换这么多问题。 Or rather because of antialias. 还是因为抗锯齿。 Simply from xml getPaint.AntiAlia .. does not work. 简单地从xml getPaint.AntiAlia ..不起作用。

the problem looks like this 问题看起来像这样

Here I put "match_parent", and if I put "content" of the text that I'm drawing is not visible at all. 在这里,我放置了“ match_parent”,如果我放置的是“内容”,则我绘制的文本根本不可见。 How do I insert "Text" into my text instead, which I draw. 如何在我绘制的文本中插入“文本”。

 public void setTextHate(String hate) {
    str = hate;
}

after set str = hate, you have to call invalidate(); 设置str = hate之后,您必须调用invalidate(); to call onDraw(Canvas canvas) again. 再次调用onDraw(Canvas canvas)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM