Created
December 7, 2022 19:02
-
-
Save molidev8/bb7b7a923e958c49e259239b730fe8c4 to your computer and use it in GitHub Desktop.
CustomView implementation with Factory Pattern
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 CustomSwitch : ConstraintLayout { | |
private lateinit var manager: CustomSwitchManager | |
constructor(context: Context) : super(context) | |
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { | |
readAttrs(attrs) | |
} | |
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super( | |
context, | |
attrs, | |
defStyleAttr | |
) { | |
readAttrs(attrs) | |
} | |
private fun readAttrs(attrs: AttributeSet) { | |
with(context.theme.obtainStyledAttributes(attrs, R.styleable.CustomSwitch, 0, 0)) { | |
inflateView( | |
getSwitchTypeFromAttr(this), | |
getBoolean(R.styleable.CustomSwitch_anim_text, false), | |
getBoolean(R.styleable.CustomSwitch_manual, false), | |
getBoolean(R.styleable.CustomSwitch_textVisible, false), | |
getString(R.styleable.CustomSwitch_text).orEmpty() | |
) | |
recycle() | |
} | |
} | |
private fun getSwitchTypeFromAttr(attributes: TypedArray): CustomSwitchType = | |
when (attributes.getInt(R.styleable.CustomSwitch_switch_type, 1)) { | |
1 -> Vanilla | |
2 -> CustomThumbSmallSwitch | |
3 -> CustomThumbBigSwitch | |
else -> CustomTrackPillSwitch | |
} | |
private fun inflateView( | |
type: CustomSwitchType, | |
animText: Boolean, | |
manual: Boolean, | |
textVisible: Boolean, | |
text: String | |
) { | |
manager = CustomSwitchFactory.build(type) | |
removeAllViews() | |
manager.initView(context, this, animText, manual, textVisible, text) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment