-
반응형
안녕하세요, 하루플입니다.
이전 포스팅에서 ProgressBar를 커스텀해서 예쁜 UI로 만들었습니다.
여기서 단순히 TextView를 ProgressBar 안에 적용해도 되긴 하지만 가독성이 떨어져서 쉽게 읽히지 않았습니다.
그래서 테두리가 있는 TextView를 개발해서 위 사진처럼 테두리를 적용하는 방법을 알려드리겠습니다.
먼저 일반적인 TextView를 커스텀하는 것 처럼 AppCompatTextView를 상속받는 OutLineTextView 클래스를 만들었습니다.
class OutlineTextView : AppCompatTextView {}그리고 선의 두께와 컬러를 지정할 전역변수를 선언합니다.
만약 Activity나 Fragment에서 직접 이 두께와 컬러를 지정하려면 private를 해제하고 사용하면 됩니다.
private var stroke = falseprivate var strokeWidth = 0.0fprivate var strokeColor = 0저는 XML에서 OutLine 옵션을 지정할 수 있도록 styleable에 각 옵션을 등록해두었습니다.
private fun initView(context: Context, attrs: AttributeSet?) {val type = context.obtainStyledAttributes(attrs, R.styleable.OutlineTextView)stroke = type.getBoolean(R.styleable.OutlineTextView_out_line_text_view_has_stroke, false) // 아웃라인 유무strokeWidth = type.getFloat(R.styleable.OutlineTextView_out_line_text_view_stroke_width, 0.0f) // 아웃라인 두께strokeColor = type.getColor(R.styleable.OutlineTextView_out_line_text_view_stroke_color, -0x1) // 아웃라인 컬러}attrs.xml
<declare-styleable name="OutlineTextView"><attr name="out_line_text_view_has_stroke" format="boolean" /><attr name="out_line_text_view_stroke_width" format="float" /><attr name="out_line_text_view_stroke_color" format="integer"/></declare-styleable>그리고 onDraw 함수를 통해 Stroke를 만들어주면 됩니다.
캔버스를 이용해서 텍스트뷰에 stroke를 그려줄 수 있습니다.
override fun onDraw(canvas: Canvas) {if (stroke) {val states = textColorspaint.style = Paint.Style.STROKEpaint.strokeWidth = strokeWidthsetTextColor(strokeColor)super.onDraw(canvas)paint.style = Paint.Style.FILLsetTextColor(states)}super.onDraw(canvas)}아래는 OutLineTextView 클래스 전체 코드입니다.
class OutlineTextView : AppCompatTextView {private var stroke = falseprivate var strokeWidth = 0.0fprivate var strokeColor = 0constructor(context: Context?) : super(context!!) {}constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {initView(context, attrs)}constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context,attrs,defStyleAttr) {initView(context, attrs)}private fun initView(context: Context, attrs: AttributeSet?) {val type = context.obtainStyledAttributes(attrs, R.styleable.OutlineTextView)stroke = type.getBoolean(R.styleable.OutlineTextView_out_line_text_view_has_stroke, false) // 아웃라인 유무strokeWidth = type.getFloat(R.styleable.OutlineTextView_out_line_text_view_stroke_width, 0.0f) // 아웃라인 두께strokeColor = type.getColor(R.styleable.OutlineTextView_out_line_text_view_stroke_color, -0x1) // 아웃라인 컬러}override fun onDraw(canvas: Canvas) {if (stroke) {val states = textColorspaint.style = Paint.Style.STROKEpaint.strokeWidth = strokeWidthsetTextColor(strokeColor)super.onDraw(canvas)paint.style = Paint.Style.FILLsetTextColor(states)}super.onDraw(canvas)}}반응형'개발 > Android' 카테고리의 다른 글
[Android | Kotlin] 프로그래스바 커스텀 하기 (0) 2023.06.06 [Android | Kotlin] Uri로 입력받은 이미지를 줄이는 방법 (0) 2023.06.04 심플 소프트웨어 : 소프트웨어 이해하기 (1) 2023.05.29 심플 소프트웨어 : 엔지니어링 팀에서 일하기 (0) 2023.05.28 심플 소프트웨어 : 프로그래머를 위한 원칙 (1) 2023.05.27