Please Enable JavaScript!
Gon[ Enable JavaScript ]

안드로이드(Android) 옵션메뉴셋팅과 다이얼로그 띄우기

안드로이드 개발
반응형

안드로이드(Android) 옵션메뉴셋팅과 다이얼로그 띄우기

 

개발환경 : window 7 64bit, Eclipse Kepler, Android 4.2.2

 

안드로이드에서 옵션메뉴을 추가하기 위해서는

onCreateOptionsMenu 함수를 Override 해야 합니다.

기본적으로 프로젝트를 생성하게 되면 추가가 되어

있지만 그렇지 않다면 Override/Implement methods

대화상자에서 추가하면 됩니다.

 

옵션메뉴에 해당하는 함수 내용은 아래와 같습니다.

R.menu.main 을 파라미터로 넘기게 되어있는데

여기에 메뉴제목을 넣게 됩니다.

 

@Override
public boolean onCreateOptionsMenu(Menu menu) {

	// Inflate the menu; this adds items to the action bar if it is present.
	// 기본으로 들어가는 setting 메뉴
	getMenuInflater().inflate(R.menu.main, menu);
	return true;
}

예제에서는 메뉴제목을 두개 더 추가하게 되는데

 res / menu / main.xml 에 메뉴를 들어가게 됩니다. .

 

main.xml 을 열어봅니다. 아래와 같이 item 을 두개 추가합니다.

title string.xml 에 추가해서 그 제목을 넣으면 되겠죠.

 

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.sampledialogimage.MainActivity" >
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never"/>
    <item
        android:id="@+id/about"
        android:orderInCategory="100"
        android:title="@string/about"
        app:showAsAction="never"/>
    <item
        android:id="@+id/exit"
        android:orderInCategory="100"
        android:title="@string/exit"
        app:showAsAction="never"/>
</menu>

메뉴와 기타 문자열이 등록된 string.xml 입니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">SampleDialogImage</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="about">프로그램이란</string>
    <string name="exit">나가기</string>
    <string name="app_about_message">안드로이드팝업메시지</string>
    <string name="str_ok">OK</string>
    <string name="app_exit_message">나가기</string>
    <string name="str_no">NO</string>
</resources>

위와 같이 해놓으면 메뉴는 뜨게 됩니다.

다음은 메뉴를 클릭했을떄 이벤트를 등록해야 합니다.

우리가 메뉴를 등록하는 이유는 그에 해당하는 행위를

하기 위함입니다.

이벤트를 등록해야할 함수는 onOptionsItemSelected() 입니다.

함수의 내용은 아래와 같은데 파라미터로 MenuItem 객체가

넘어오게 됩니다. 이 객체는 메뉴를 등록한 main.xml 이 값으로

오므로 id  로 구분해 어떤 메뉴가 클릭되었는지 구분이

가능합니다. 그렇게 구분해서 그에 해당하는 행위함수를

등록하면 됩니다.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

	int id = item.getItemId();
	if (id == R.id.action_settings) {
		return true;
	} else if (id == R.id.about) {
		// 옵션메뉴에서 about 클릭했을때
		openOptionsDialog();

	} else if (id == R.id.exit) {
		// 옵션메뉴에서 Exit 를 클릭했을때
		exitOptionsDialog();

	}
	return super.onOptionsItemSelected(item);
}

메뉴가 클릭했을 때 행하는 함수는 두개인데 openOptionsDialog(),

exitOptionsDialog() 입니다.

openOptionsDialog()는 다이얼로그를 하나 띄우는 함수 입니다.

private void openOptionsDialog() {
	new AlertDialog.Builder(this)
	 .setTitle(R.string.about)
	 .setMessage(R.string.app_about_message)
	 .setPositiveButton(R.string.str_ok,
	    new DialogInterface.OnClickListener() {
		public void onClick(
	           DialogInterface dialoginterface, int i) {
		}
	}).show();
}

exitOptionsDialog() 함수도 다이얼로그를 띄우는 함수인데 OK 일때

프로그램을 빠져나가는 소스가 있습니다.

private void exitOptionsDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.exit)
.setMessage(R.string.app_exit_message)
.setNegativeButton(R.string.str_no,
	new DialogInterface.OnClickListener() {
	   public void onClick(
	      DialogInterface dialoginterface, int i) {
	   }
	})
.setPositiveButton(R.string.str_ok,
	new DialogInterface.OnClickListener() {
	   public void onClick(
	      DialogInterface dialoginterface, int i) {
		finish();
	     }
	}).show();
}

전제소스는 아래와 같습니다.

package com.example.sampledialogimage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends ActionBarActivity {

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

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		// 기본으로 들어가는 setting 메뉴
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		} else if (id == R.id.about) {
			// 옵션메뉴에서 about 클릭했을때
			openOptionsDialog();

		} else if (id == R.id.exit) {
			// 옵션메뉴에서 Exit 를 클릭했을때
			exitOptionsDialog();

		}
		return super.onOptionsItemSelected(item);
	}

	private void openOptionsDialog() {
		new AlertDialog.Builder(this)
				.setTitle(R.string.about)
				.setMessage(R.string.app_about_message)
				.setPositiveButton(R.string.str_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface, int i) {
							}
						}).show();
	}

	private void exitOptionsDialog() {
		new AlertDialog.Builder(this)
				.setTitle(R.string.exit)
				.setMessage(R.string.app_exit_message)
				.setNegativeButton(R.string.str_no,
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface, int i) {
							}
						})
				.setPositiveButton(R.string.str_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface, int i) {
								finish();
							}
						}).show();
	}
	
	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			return rootView;
		}
	}

}

결과 이미지는 다음고 같습니다. 옵션을 클릭하게 되면 세개의

옵션메뉴가 뜨게 됩니다 

 

클릭했을 때 다이얼로그가 뜹니다.

반응형
Posted by 녹두장군1
,