사용자 지정 보기를 만든 이유는 무엇입니까?
- 레이아웃에서 중복 코드 재사용하게 만든
이 앱에서는 하단에 표시되는 버튼을 재사용할 수 있도록 만들었습니다.
레이아웃 xml 파일 생성
- 맞춤 보기 기본으로 사용할 레이아웃 파일그것을 만드십시오.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="@dimen/default_height" android:background="@color/theme_yellow" android:padding="8dp" > <TextView android:id="@+id/customText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="완료" android:textColor="@color/white" android:textSize="@dimen/content_size" android:textStyle="bold" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
속성 정의
res/values/attrs.xml파일 생성<declare-styleable>리소스 추가 상황에 따라 변경해야 하는 속성 정의하다.- 각
attr필드name이 사용자 지정 보기 클래스에서 속성을 정의하는 데 사용됩니다.<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CustomBottomButton"> <attr name="customText" format="reference|string" /> <attr name="customTextColor" format="reference|color"/> </declare-styleable> </resources>
CustomView 클래스 작성
-
사용자 지정 보기를 함수로 사용하는 데 필요한 속성 정의하다
obtainStyledAttributes()속성을 적용합니다.class CustomBottomButton(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) { private var customText: TextView init { val v = View.inflate(context, R.layout.custom_bottom_btn, this) customText = v.findViewById(R.id.customText) context.theme.obtainStyledAttributes( attrs, R.styleable.CustomBottomButton, 0,0 ).apply { try { setText(getString(R.styleable.CustomBottomButton_customText)) setTextColor(getColor(R.styleable.CustomBottomButton_customTextColor, 0)) } finally { recycle() } } } fun setText(text: String?) { customText.text = text onRefresh() } fun setTextColor(color: Int){ customText.setTextColor(color) } private fun onRefresh() { invalidate() requestLayout() } }
CustomView 사용
- 함수로 정의된 속성을 쉽게 사용할 수 있습니다.
<com.chloedewyes.walkmydog.custom.CustomBottomButton android:id="@+id/continueBtn" android:layout_width="match_parent" android:layout_height="@dimen/default_height" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:customText="다음" app:customTextColor="@color/white" />