IT/Android (안드로이드)

Android N.3-2 Creating Custom Views

Edmond Na 2025. 4. 21. 23:24

### #0 Custom  View 란?

TextView, ImageView 같은 뷰만으로 구성할 수 없는 개발자가 직


----------


접 만든 뷰를 의미합니다.


### #1 Custom View 만들기 (클래스 생성)

Android 프레임워크에 정의된 모든 뷰 클래스는 [View](https://developer.android.com/reference/android/view/View?hl=ko)를 확장합니다. 맞춤 뷰는 [View](https://developer.android.com/reference/android/view/View?hl=ko)를 직접 확장할 수도 있으며, 또는 기존의 뷰 서브클래스(예: [Button](https://developer.android.com/reference/android/widget/Button?hl=ko)) 중 하나를 확장하여 시간을 절약할 수 있습니다.

``` kotlin
  class PieChart(context: Context, attrs: AttributeSet) : View(context, attrs)
```
### #2 Custom View 만들기 (맞춤 속성 정의)

사용자 인터페이스에 내장  [View](https://developer.android.com/reference/android/view/View?hl=ko)를 추가하려면 XML 요소에 지정하고 요소 속성으로 모양과 동작을 제어합니다. 잘 작성된 맞춤 뷰는 XML을 통해 추가하고 스타일을 지정할 수도 있습니다. 맞춤 뷰에서 이 동작을 사용 설정하려면 다음을 실행해야 합니다.

-   `<declare-styleable>` 리소스 요소에서 뷰의 맞춤 속성 정의
-   XML 레이아웃에서 속성 값 지정
-   런타임에 속성 값 검색
-   뷰 검색된 속성 값 적용

``` xml
<resources>  
<declare-styleable  name="PieChart">  
<attr  name="showText"  format="boolean"  />  
<attr  name="labelPosition"  format="enum">  
<enum  name="left"  value="0"/>  
<enum  name="right"  value="1"/>  
</attr>  
</declare-styleable>  
</resources>
```

### #3 Custom View 만들기 (클래스 내의 맞춤 속성 정의)

XML 레이아웃에서 뷰를 만들면 리소스 번들에서 XML 태그의 모든 속성을 읽어 뷰 생성자에  [AttributeSet](https://developer.android.com/reference/android/util/AttributeSet?hl=ko)으로 전달합니다.  [AttributeSet](https://developer.android.com/reference/android/util/AttributeSet?hl=ko)에서 직접 값을 읽을 수 있지만, 그렇게 하면 몇 가지 단점이 있습니다.

-   속성 값 내의 리소스 참조가 결정되지 않습니다.
-   스타일이 적용되지 않습니다.

``` kotlin
  init  { 
  context.theme.obtainStyledAttributes( 
  attrs, 
  R.styleable.PieChart,  
  0,  
  0).apply {  

try { 
mShowText = getBoolean(R.styleable.PieChart_showText,  false) 
textPos = getInteger(R.styleable.PieChart_labelPosition,  0)  

finally { 
recycle()  
}  

```

### #4 Custom View 만들기 (속성 및 이벤트 추가)

``` kotlin
fun isShowText(): Boolean  {
return mShowText 
}  
fun setShowText(showText:  Boolean) { 
mShowText = showText  
invalidate() 
requestLayout()  
}
```