농장/Android

Android activity 상단바(appbar, toolbar)에 버튼 만들기

귤발자 2020. 11. 14. 23:24
728x90
반응형

안드로이드 액티비티 화면 앱바(정확히는 툴바)에 버튼을 만들어주려고 한다. 버튼 하나이기 때문에 한가지의 기능만 한다.

 

 

 

1. Menu Resource File 생성


app의 res/menu 폴더에서 메모 리소스 xml 생성

 

그럼 요렇게 뜨는데, 왼쪽의 메뉴 Menu Item을 컴퍼넌트 트리/menu 안에 넣어 새로 생성한다.

 

그럼 이렇게 드롭메뉴가 기본으로 생성되는데, 나는 버튼만 원하니 드롭메뉴를 없애주겠다.

그러기 위해 xml 코드를 연다.

 

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

    <item android:title="Item" />
</menu>

 

아래와 같이 바꿔주었다.

<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="이 메뉴를 사용할 액티비티경로">

    <item
        android:id="@+id/action_save"
        android:orderInCategory="100"
        android:title="SAVE"
        app:showAsAction="always" />
</menu>

 

액티비티 경로 예시 (app/java 하위 폴더 이름)

tools:context = "com.example.myproject.MainActivity"

 

title 대신 icon을 지정해주어도 된다. title과 icon 둘다 지정했다면 icon만 보인다.

<item
        android:id="@+id/action_save"
        android:icon="@android:drawable/ic_menu_save"
        android:title="SAVE"
        android:orderInCategory="100"
        app:showAsAction="always" />

 

 

 

 

 

2. Activity에 메뉴 리소스 지정


 

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.메뉴리소스파일명, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.메뉴리소스의 버튼ID값:
                //동작내용
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

메뉴를 사용할 액티비티 클래스에 onCreateOptionsMenu,  onOptionsItemSelected 함수를 오버라이트해준다.

직접 코드를 작성해도되지만, 마우스 우클릭>Generate...>Override Methods... 로도 만들 수 있다.

 

 

 

아래는 앞서 내가 지정한 버튼 ID로 작성했고, 뒤로가기 버튼도 넣은 모습이다.

switch (item.getItemId()) {
  case android.R.id.home:
    finish();
    return true;
  case R.id.action_save:
    //동작
    return true;
}

 

 

 

돌려보니 잘 나타난다. 

728x90
반응형