Thursday, June 11, 2020

android kotlin - Context menu example

MainActivity.kt

package com.example.jetpack

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.ContextMenu
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // register context menu for constraint layout
        // long press the constraint layout to show context menu
        registerForContextMenu(constraintLayout)
    }


    override fun onCreateContextMenu(
        menu: ContextMenu?,
        v: View?,
        menuInfo: ContextMenu.ContextMenuInfo?
    ) {
        // inflate the context menu
        menuInflater.inflate(R.menu.context_menu,menu)

        // set a header for context menu
        menu?.setHeaderTitle("Context Menu")

        super.onCreateContextMenu(menu, v, menuInfo)
    }


    override fun onContextItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.red->{
                constraintLayout.background = ColorDrawable(Color.RED)
            }R.id.green->{
                constraintLayout.background = ColorDrawable(Color.GREEN)
            }R.id.yellow->{
                constraintLayout.background = ColorDrawable(Color.YELLOW)
            }R.id.gray-> {
                constraintLayout.background = ColorDrawable(Color.GRAY)
            }
        }
        return super.onContextItemSelected(item)
    }


    override fun onContextMenuClosed(menu: Menu) {
        Toast.makeText(
            this,
            "Context Menu Closed",
            Toast.LENGTH_SHORT
        ).show()
        super.onContextMenuClosed(menu)
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"/>
res/menu/context_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/red"
        android:title="Red" />
    <item
        android:id="@+id/green"
        android:title="Green" />
    <item
        android:id="@+id/yellow"
        android:title="Yellow" />
    <item
        android:id="@+id/gray"
        android:title="Gray" />
</menu>