Skip to content

Instantly share code, notes, and snippets.

@rajeefmk
Last active July 30, 2020 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeefmk/87f91ef19c378f256354061cb38c9651 to your computer and use it in GitHub Desktop.
Save rajeefmk/87f91ef19c378f256354061cb38c9651 to your computer and use it in GitHub Desktop.
Custom Textview with helper methods of setting style, font and html support.
public class AppTextView extends TextView {
public Paint paint;
public boolean addStrike = false;
public AppTextView(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) init(attrs);
}
public AppTextView(Context context) {
super(context);
}
private void init(AttributeSet attrs) {
TypedArray attrsArray = getContext().obtainStyledAttributes(attrs, R.styleable.apptext);
try {
int style = attrsArray.getInteger(R.styleable.apptext_textStyle, 5);
String fontFamily;
switch (style) {
case 0:
fontFamily = "Thin";
break;
case 1:
fontFamily = "Light";
break;
case 2:
fontFamily = "Regular";
break;
case 3:
fontFamily = "Bold";
break;
case 4:
fontFamily = "Semibold";
break;
default:
fontFamily = "Regular";
break;
}
String fontName = getContext().getString(R.string.font_name) + "-" + fontFamily;
setTypeface(TypefaceProvider.getTypeFace(getContext(), fontName));
setPaintFlags(getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
paint = new Paint();
paint.setColor(Color.GRAY);
paint.setStrokeWidth(getResources().getDisplayMetrics().density * 1);
} finally {
attrsArray.recycle();
}
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (addStrike) {
canvas.drawLine(0, getHeight() / 2, getWidth(),
getHeight() / 2, paint);
}
}
@Override
public void setText(CharSequence text, BufferType type) {
if (text != null) {
super.setText(text, type);
}
}
public void setHTMLText(String value) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
setText(value != null ? Html.fromHtml(value, Html.FROM_HTML_MODE_LEGACY) : "");
} else {
setText(value != null ? Html.fromHtml(value) : "");
}
}
}
@walioul
Copy link

walioul commented Jun 25, 2018

Hello ,

Thank you for making this. I found you on https://medium.com . Could you please share value of R.styleable.apptext_textStyle and R.styleable.apptext

@xubmuajkub
Copy link

Can you provide the value of apptext_textStyle and apptext?

@gagan50
Copy link

gagan50 commented Jan 24, 2019

Can you provide the value of apptext_textStyle and apptext?

@MustafaAndroid
Copy link

did anyone get the answer of Could you please share value of R.styleable.apptext_textStyle and R.styleable.apptext..????

@ranjeetchouhan
Copy link

did anyone get the answer of Could you please share value of R.styleable.apptext_textStyle and R.styleable.apptext..????

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment