IT/Android

android - context 메뉴 추가

노마드오브 2018. 9. 20. 23:08

파일명 : activity_main.xml

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

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="배경색 변경" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="버튼 변경" />

</LinearLayout>


파일명 : menu1.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item
android:id="@+id/itemRed"
android:title="배경색 (빨강)" >
</item>
<item
android:id="@+id/itemGreen"
android:title="배경색 (초록)" >
</item>
<item
android:id="@+id/itemBlue"
android:title="배경색 (파랑)" >
</item>

</menu>


파일명 : menu2.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item
android:id="@+id/subRotate"
android:title="버튼 45도 회전" />
<item
android:id="@+id/subSize"
android:title="버튼 2배 확대" />

</menu>



파일명 : MainActivity.java

package com.example.it.myapplication7_3;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

LinearLayout baseLayout;
Button button1, button2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("배경색 바꾸기(컨텍스트 메뉴)");

baseLayout = (LinearLayout) findViewById(R.id.baseLayout);
button1 = (Button) findViewById(R.id.button1);
registerForContextMenu(button1);

button2 = (Button) findViewById(R.id.button2);
registerForContextMenu(button2);
}

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

MenuInflater mIn = getMenuInflater();
if (v == button1) {
menu.setHeaderTitle("배경색 변경");
mIn.inflate(R.menu.menu1, menu);
}

if (v == button2) {
mIn.inflate(R.menu.menu2, menu);
}
}

@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemRed:
baseLayout.setBackgroundColor(Color.RED);
return true;
case R.id.itemGreen:
baseLayout.setBackgroundColor(Color.GREEN);
return true;
case R.id.itemBlue:
baseLayout.setBackgroundColor(Color.BLUE);
return true;
case R.id.subRotate:
button2.setRotation(45);
return true;
case R.id.subSize:
button2.setScaleX(2);
return true;
}
return false;
}
}