스크롤뷰안 리니어레이아웃에 ViewGroup.addView함수를 통해 뷰를 추가할수있습니다. 이때 생각난는 의문은 리사이클러뷰나 리스트뷰를 사용하여 뷰를 추가해주는것이 좋지 않을까 였습니다.
이방법은 더 좋을수도 있을꺼라는 생각이 듭니다. 뷰를 넣어줄때는 어짜피 지정된 레이아웃을 이용하여 넣어줄것이고 들어가는 데이터의 종류가 다르더라도 sealedClass로 묶는다면 해당데이터들을 손쉽게 다룰수 있을것입니다. 왜 addView를 사용하여 뷰를 추가할까요?
스크롤뷰 안에 적은 수의 아이템을 표시할 때나, 아이템의 수가 동적이며 자주 변경되지 않는 경우에 적합합니다.
리사이클러뷰나 리스뷰는 대량의 데이터를 표시하기에 적절합니다. 만약 앱을 만들때 작은 규모의 데이터를 사용한다면 리사이클러뷰를 이용해서 관리를 하는것은 좋은 석택지가 아닐것입니다. 그저 뷰만 넣으면 되니까 말이죠 그렇기에 간단하게 뷰를 추가할 수 있는 addView함수를 고려하게됩니다. 또한 View를 바꿀때도 해당뷰에만 접근하여 바꾸면되므로 좀더 간편하게 코드를 짤수있습니다.
넣어줄 뷰가 필요합니다. 간단한 TextView를 넣을수도있지만 이렇게 레이아웃을 추가할수도 있습니다.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SampleView">
<attr name="imageUrl" format="string"/>
<attr name="title" format="string"/>
</declare-styleable>
</resources>
class SampleView @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attributeSet, defStyleAttr) {
private lateinit var binding: ItemSampleBinding
private var title: String? = null
private var imageUrl: String? = null
init {
attributeSet?.let {
initAttr(it)
}
initView()
}
private fun initAttr(attrs: AttributeSet) {
context.theme.obtainStyledAttributes(
attrs,
R.styleable.MenuView,
0, 0
).apply {
title = getString(R.styleable.MenuView_title)
imageUrl = getString(R.styleable.MenuView_imageUrl)
}
}
private fun initView() {
val view = inflate(context, R.layout.item_sample, this)
binding = ItemMenuBinding.bind(view)
title?.let {
setTitle(it)
}
imageUrl?.let {
setImageUrl(it)
}
}
fun setTitle(title: String) {
this.title = title
binding.nameTextView.text = title
}
fun setImageUrl(imageUrl: String) {
this.imageUrl = imageUrl
Glide.with(binding.imageView)
.load(imageUrl)
.circleCrop()
.into(binding.imageView)
}
}
binding.sampleLayout.addView(
SampleView(context = requireContext()).apply {
setTitle(name)
setImageUrl(image)
}
)
referenc
https://coding-idiot.tistory.com/8
https://pluu.github.io/blog/android/2020/08/09/android-custom-view-style/