Java/Android

[안드로이드 기본] 컨텍스트 메뉴 만들기

반나무 2020. 5. 18. 15:12

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HELLO WORLD"
        android:textSize="200px"
        android:typeface="serif"/>

</LinearLayout>

MainActivity.java

package com.example.contextmenu;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = (TextView) findViewById(R.id.TextView01);
        registerForContextMenu(text); //텍스트뷰에 컨텍스트 메뉴를 등록한다.
    }

    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
        super.onCreateContextMenu(menu,v,menuInfo);

        menu.setHeaderTitle("컨텍스트메뉴");
        menu.add(0,1,0,"배경색:RED");
        menu.add(0,2,0,"배경색:GREEN");
        menu.add(0,3,0,"배경색:BLUE");

    }

    public boolean onContextItemSelected(MenuItem item){
        switch(item.getItemId()){
            case 1:
                text.setBackgroundColor(Color.RED);
                return true;

            case 2:
                text.setBackgroundColor(Color.GREEN);
                return true;

            case 3:
                text.setBackgroundColor(Color.BLUE);
                return true;
            default:
                return super.onContextItemSelected(item);

        }
    }

}
반응형