카테고리 없음

안드로이드 커스텀 뷰(Custom View)

show2888 2022. 11. 22. 14:54
반응형
Android View를 상속받아서 새로운 뷰를 만드는 것

 

커스텀뷰를 만드는 방법

1. XML에 레이아웃을 직접 만들어 View를 가져오는 방법

  - LayoutInflater 혹은 Binding을 이용해 레이아웃 소스를 addView()해서 사용함

class CustomViewTest @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private val binding =
        CustomViewTestBinding.inflate(LayoutInflater.from(context), this, true)

addView()대신에 binding을 이런식으로 선언하면 addView()를 생략할 수 있다. 왜냐하면 this로써 view에 layout을 주기 때문이다.

2. 직접 Canvas에 그림을 그리는 방법

  - onDraw(canvas: Canvas)를 override해서 Canvas에 작업함

  - view에 어떤 작업이 없으면 onDraw()함수가 불리지 않기때문에  background나 forground에 대한 내용을 작성해야한다.

    XML이나 코드상에다 셋팅해도 괜찮다.

 

 

커스텀뷰에 Attributes 셋팅 하는방법

- context에서 obtainStyledAttributes()함수로 받아와 셋팅할 수 있다. 혹은 withStyledAttributes()를 사용해도 된다.

val t = context.obtainStyledAttributes(attrs, R.styleable.TransformFrameLayout)
radius = t.getDimension(R.styleable.TransformFrameLayout_transformCornerRadius, 0f).toInt()

t.recycle()

recycle() 메소드는 TypedArray를 사용후에 꼭 호출해야함

TypedArray는 Cache를 위한 배열을 포함하고 있어 매번 할당하지 않기위해 스태틱 필드로 캐시된다.

recycle()를 호출하게되면 캐시로 사용한 객체를 반환해서 Garbage Collection의 대상에서 제외시킨다.

init { 
     context.withStyledAttributes(attrs, R.styleable.MultiLineBoxEditText) {
     applyAttributes(this) }
    }
        
private fun applyAttributes(typedArray: TypedArray) {
        val hint = typedArray.getString(R.styleable.CustomAttribute_hint).orEmpty()
반응형