Custom view class in kotlin with style attributes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<declare-styleable name="LeaderRankView"> | |
<attr name="leaderBackground" format="reference" /> | |
<attr name="leaderIcon" format="reference" /> | |
<attr name="leaderName" format="string" /> | |
<attr name="leaderRank" format="enum"> | |
<enum name="rank1" value="1" /> | |
<enum name="rank2" value="2" /> | |
<enum name="rank3" value="3" /> | |
</attr> | |
</declare-styleable> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LeaderRankView @JvmOverloads constructor( | |
context: Context, | |
val attrs: AttributeSet? = null | |
) : ConstraintLayout(context, attrs) { | |
var binding: ViewLeaderRankBinding | |
private var leaderIcon: Drawable? = null | |
set(value) { | |
field = value | |
value?.let { | |
binding.ivUserRankNumber.setImageDrawable(it) | |
} | |
} | |
private var leaderBackground: Drawable? = null | |
set(value) { | |
field = value | |
value?.let { | |
binding.clRoot.background = it | |
} | |
} | |
init { | |
binding = ViewLeaderRankBinding.inflate( | |
LayoutInflater.from(context), this, true | |
) | |
setupView() | |
} | |
private fun setupView() { | |
context.obtainStyledAttributes( | |
attrs, | |
R.styleable.LeaderRankView, | |
0, 0 | |
).apply { | |
try { | |
getDrawable(R.styleable.LeaderRankView_leaderBackground).let { | |
binding.clRoot.background = it | |
} | |
getDrawable(R.styleable.LeaderRankView_leaderIcon).let { | |
binding.ivUserRankNumber.background = it | |
} | |
getString(R.styleable.LeaderRankView_leaderName).let { | |
binding.tvUserName.text = it | |
} | |
} finally { | |
recycle() | |
} | |
} | |
} | |
} | |
No comments :
Post a Comment