이 앱에서는 하단에 표시되는 버튼을 재사용하기 위해 만들었어요.
<?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>
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()
}
}
<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"
/>