Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Composable
- fun ContextMenu(
- builder: ContextMenu.Builder.() -> Unit
- ) {
- val contextMenu = remember(builder){
- val contextMenuBuilder = ContextMenu.Builder()
- builder.invoke(contextMenuBuilder)
- contextMenuBuilder.build()
- }
- for(i in contextMenu.sections.indices){
- ContextMenuSection(contextMenu.sections[i])
- if(i < contextMenu.sections.size - 1) ContextMenuSeparator()
- }
- }
- @Composable
- private fun ContextMenuSection(section: ContextMenu.Section){
- if(section.title!!.isNotBlank() && false){
- TextLine(
- text = section.title!!,
- style = TextStyle()
- )
- }
- for(option in section.options){
- ContextMenuOption(option)
- }
- }
- @Composable
- private fun ContextMenuOption(option: ContextMenu.Option){
- Row(
- Modifier
- .clickable(onClick = option.onClick)
- .fillMaxWidth()
- .padding(
- vertical = 16.dp,
- horizontal = 32.dp
- )
- ){
- Icon(
- painter = painterResource(option.drawableId),
- contentDescription = ""
- )
- Text(
- text = option.label,
- modifier = Modifier
- .padding(start = 16.dp)
- )
- }
- }
- @Composable
- private fun ContextMenuSeparator(){
- Divider(
- Modifier
- .fillMaxWidth()
- .height(1.dp)
- )
- }
- class ContextMenu(val sections: List<Section>) {
- class Builder {
- private val sections = mutableListOf<Section>()
- private var currentSection = Section()
- fun setSectionTitle(title: String){
- if(currentSection.title != null){
- throw IllegalStateException("A section is already active." +
- "To start a new section call addSeparator() first." +
- "If addOption() is used without a setSectionTitle before the section title will be empty.".trimIndent())
- }
- currentSection.title = title
- }
- fun addOption(@DrawableRes drawableId: Int, label: String, onClick: () -> Unit){
- if(currentSection.title == null) currentSection.title = ""
- currentSection.options.add(Option(drawableId, label, onClick))
- }
- fun addSeparator(){
- if(currentSection.title == null){
- throw IllegalStateException("No Section active. Call setSectionTitle() or addOption() first.")
- }
- sections.add(currentSection)
- currentSection = Section()
- }
- fun build(): ContextMenu {
- if(currentSection.title != null) sections.add(currentSection)
- return ContextMenu(sections)
- }
- }
- class Option(
- @DrawableRes val drawableId: Int,
- val label: String,
- val onClick: () -> Unit
- )
- class Section {
- var title: String? = null
- set(title){
- field = title
- options = mutableListOf()
- }
- internal var options = mutableListOf<Option>()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement