Created
April 10, 2023 06:55
-
-
Save SurajBahadur/228ad080364b5fef9371661498a3a1fe to your computer and use it in GitHub Desktop.
Custom View Class In Kotlin with Style Attributes.
This file contains hidden or 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 hidden or 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() | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment