안드로이드 스튜디오를 켜서 템플릿을 보니 네비게이션 템플릿이 있었다.

그래서 오늘은 이에대해 공부해보기로 하였다.


먼저 템플릿을 선택하여 접속하여 컴파일해보면 아래와 같은 그림이 나오는데, 



안드로이드에서 Sample있는 부분이 툴바라는 부분이다.



1
2
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cs

위와 같이생성되며 onCreate() 에 액티비티 생성후 만들면 된다.

그러면 이제 왼쪽에서부터 어떻게 만드는지 차례대로 살펴보자

1
2
3
4
5
6
7
8
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
 
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
cs

위외 같이 네비게이션 뷰를 생성하고 싶다면 이렇게 생성한다. 

ActionBarDrawerToggle의 매개변수는 다음과 같다.
1
2
ActionBarDrawerToggle (Activity activity, DrawerLayout drawerLayout,
        int drawerImageRes, int openDrawerContentDescRes, int closeDrawerContentDescRes)
cs



 R.string.navigation_drawer_open와 R.string.navigation_drawer_close는 String.xml에

1
2
<string name="navigation_drawer_open">Open navigation drawer</string>
<string name="navigation_drawer_close">Close navigation drawer</string>



로 저장되어있다.




네비게이션 뷰를 누르면 이런 화면이 뜨는데, 이러한 화면은 xml에서 만들어준다. 또한 위의 코드 6-7 라인이 없으면 각각의 아이템이 클릭이 되지않는다.

아래 코드는 네비게이션 뷰 xml파일이다. 

살펴보면

android:checkableBehavior="single" 이 부분이있는데 선택형태를 정해주는 부분이다.

그종류로는 none, single, all 이 있는데, 차례대로 none은 단순리스트형태, single은 라디오 버튼형태로 단일 선택형, all은 체크박스 형태로 다중선택형을 나타낸다.

지금으로써는 없어도 무방하다.

그리고 item밑에 하위 item도 사용할수 있다. 23번라인부터 끝까지 보면 communicate로 구분을 지어서 사용하고 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
 
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_camera"
            android:icon="@drawable/ic_menu_camera"
            android:title="Import" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Slideshow" />
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/ic_menu_manage"
            android:title="Tools" />
    </group>
 
    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="Send" />
        </menu>
    </item>
 
</menu>
 
cs



그다음은 오른쪽 맨끝에있는 옵션바를 살펴보자.



1
2
3
4
5
6
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
cs

옵션메뉴는 프래그먼트로 만들어져 있으며, 위와같이 추가한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
 
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Toast.makeText(getApplicationContext(),"settings",Toast.LENGTH_SHORT).show();
            return true;
        }else if(id == R.id.action_sample){
            Toast.makeText(getApplicationContext(),"sample",Toast.LENGTH_SHORT).show();
            return true;
        }
 
        return super.onOptionsItemSelected(item);
    }

cs

옵션메뉴의 메뉴를 클릭했을때 각각의상태는 위와 같이 사용하며,

현재는 settings 와 samples 항목을 만들었고 Toast로 선택시 각각의 메시지를 띄워주게 만들었다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
 
    <item
        android:id="@+id/action_sample"
        android:orderInCategory="100"
        android:title="@string/action_samples"
        app:showAsAction="never" />
</menu>



옵션메뉴의 xml은 위와 같이 만들었으며, 


1
2
<string name="action_settings">Settings</string>
<string name="action_samples">Samples</string>

cs


title은 string.xml에 위와같이 저장되어있다.



toolbar를 사용하여 액티비티위에 여러 메뉴를 만들수 있어서,

어플리케이션 구현시 효율적이고 이쁘게 만들수 있을것 같다.

'Programming > Android' 카테고리의 다른 글

안드로이드의 구성요소 요약  (0) 2016.09.05
Thread (백그라운드에서 UI변경)  (0) 2016.09.03
manifest  (0) 2016.09.02
notification 고정시키기  (1) 2016.08.28
JSONobject 과 JSONarray  (0) 2016.08.27

+ Recent posts