본문 바로가기
코딩과 알고리즘

크레이의 앱개발 도전기 #2. 네비게이션 메뉴

※ 이 게시글은 크레이의 IT개발 관련 성장기를 다루고 있습니다. 관련지식이 약간 있어야 이해되실 수 있습니다. 가벼운 마음으로 읽어보시면서 흥미가 생기고 의욕이 생긴다면? 개발자의 자질이 있으신 겁니다 :)

크레이는 아래 구름에듀의 안드로이드 강좌를 보면서 따라하고 있는데요.

https://edu.goorm.io/learn/lecture/15564/현직개발자가-알려주는-안드로이드-앱-개발 

진행하다보면 #7. 네비게이션 만들기에서 막힐 수 있습니다.
그럴수 밖에 없는 것이 지금 다운받을 수 있는 버전은 "안드로이드 돌핀" 버전이지만
강좌하시는 분의 버전은 안드로이드 3.1.2 버전이거든요.

특히 Navigation Draw Activity 로 프로젝트를 생성할 때 소스 내용이 완전히 다르기 때문인데요.
강의에서 설명하는 소스 부분은 도저히 찾을 수 없습니다.
하지만 강좌를 따라하시는 분들, 걱정하지 마세요.

#7에서는 메뉴에 대해 설명만을 진행할 뿐 실습은 진행하지 않습니다.
#10 Navigation Menu 커스텀 편에서 Empty Activity에서 시작해서 새롭게 다시 다룹니다.
그러니 문제는 없습니다.

크레이도 #10을 따라하며 기본 소스를 구성하였는데요.
단순히 따라하기만 한 소스를 그대로 보여드린다면 크레이가 아니겠지요? :)

몇가지를 검색해서 기능을 붙여보았습니다.

우선 메뉴버튼을 Button 대신 ImageButton 으로 변경해보았는데요.

말 그대로 이미지로 구성된 버튼입니다.

그래서 버튼 태그의 XML 코드는 아래와 같지만,

<Button
    android:id="@+id/btn_close"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="#E08E3C"
    android:text="닫기"/>

 

이미지 버튼의 코드는 아래와 같습니다.

<ImageButton
    android:id="@+id/menu_snack"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:src="@drawable/chocolate">
</ImageButton>

버튼의 이미지는 무료 이미지 사이트 픽사베이의 이미지를 편집해 사용하였는데요.
한가지 주의할 점은 이미지 파일은 jpg 이미지를 사용해서는 안된다는 것입니다.
png 이미지를 사용해야 하지요.
만일 jpg 파일만 갖고 있다면 그림판으로 파일을 열어 png 파일로 저장해도 무난합니다.

이미지버튼에 이미지를 넣는 방법은 간단합니다.

1) 리소스에 이미지를 드래그해 넣고,


2) 이미지버튼의 android:src 속성을 추가해 위 리소스로 바꿔주는 것인데요.

android:src="@drawable/chocolate"

앞에서 언급한 홍드로이드님의 안드로이드 강좌를 보셨다면 리소스 입력을 어떻게 하는지 아실겁니다.

이미지 버튼은 특별한 태그가 2줄 입력되어야 하더라구요.
바로 아래 2줄의 태그인데, 이 태그를 안 넣으면 버튼에 그림이  딱 맞추어 나오는게 아니라
일부분만 보여지듯 보여서 어색해 집니다.

android:adjustViewBounds="true"
android:scaleType="fitXY"

또한 추가로 구현한 것은 액티비티 이동인데요. 간단히 말해 화면 전환입니다.
첫 번째 버튼을 클릭하면 과자류 메뉴판으로,
두 번째 버튼을 클릭하면 과일류 메뉴판으로 이동합니다.

기능적으로는 만족스럽지만, 약간 아쉬운 부분은 동일한 코드가 여기 저기에 중복되었다는 것인데요.
특히 슬라이드되는 부분은 코드를 한번만 사용할 방법이 있을듯 한데 아직 그 부분은 알지 못합니다.
하지만 진행하다 보면 알게 되겠지요 :)
느긋한 마음으로 차례대로 진행하려 합니다.
내놓기에 부끄러운 코드이지만,
어딘가 도움이 되는 분이 있을듯 도 생각되어 코드를 공개합니다.
스크롤 압박이 있으니 그냥 휙~ 넘어가셔도 됩니다.


프로젝트 탐색기 ( 흰색이 수정, 추가된 파일입니다 )


MainActivity.java

package com.example.customnaviexample;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private View drawView;

    private ImageButton menu_snack;
    private ImageButton menu_fruit;


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



        menu_snack = (ImageButton)findViewById(R.id.menu_snack) ;
        menu_snack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SubSnack.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent); // 액티비티 이동
            }
        });

        menu_fruit = (ImageButton)findViewById(R.id.menu_fruit) ;
        menu_fruit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SubFruit.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent); // 액티비티 이동
            }
        });

        Button btn_open =(Button)findViewById(R.id.btn_open);
        btn_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(drawView);
            }
        });

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawView = (View)findViewById(R.id.drawer);

        drawerLayout.setDrawerListener(listener);

        drawView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });

        Button btn_close = (Button) findViewById(R.id.btn_close);
        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.closeDrawers();
            }
        });

    }

    DrawerLayout.DrawerListener listener = new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {

        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {

        }

        @Override
        public void onDrawerStateChanged(int newState) {

        }
    };
}

SubFruit.java

package com.example.customnaviexample;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class SubFruit extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private View drawView;

    private ImageButton menu_snack;
    private ImageButton menu_fruit;
    private Button btn_home;

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

        menu_snack = (ImageButton)findViewById(R.id.menu_snack) ;
        menu_snack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SubFruit.this, SubSnack.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent); // 액티비티 이동
            }
        });

        Button btn_open =(Button)findViewById(R.id.btn_open);
        btn_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(drawView);
            }
        });

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawView = (View)findViewById(R.id.drawer);

        drawerLayout.setDrawerListener(listener);

        drawView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });

        Button btn_close = (Button) findViewById(R.id.btn_close);
        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.closeDrawers();
            }
        });

        Button btn_home = (Button) findViewById(R.id.btn_home);
        btn_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SubFruit.this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent); // 액티비티 이동
            }
        });
    }

    DrawerLayout.DrawerListener listener = new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {

        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {

        }

        @Override
        public void onDrawerStateChanged(int newState) {

        }
    };
}

SubSnack.java

package com.example.customnaviexample;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class SubSnack extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private View drawView;

    private ImageButton menu_snack;
    private ImageButton menu_fruit;
    private Button btn_home;

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

        menu_fruit = (ImageButton)findViewById(R.id.menu_fruit) ;
        menu_fruit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SubSnack.this, SubFruit.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent); // 액티비티 이동
            }
        });

        Button btn_open =(Button)findViewById(R.id.btn_open);
        btn_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(drawView);
            }
        });

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawView = (View)findViewById(R.id.drawer);

        drawerLayout.setDrawerListener(listener);

        drawView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });

        Button btn_close = (Button) findViewById(R.id.btn_close);
        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.closeDrawers();
            }
        });

        Button btn_home = (Button) findViewById(R.id.btn_home);
        btn_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SubSnack.this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent); // 액티비티 이동
            }
        });
    }

    DrawerLayout.DrawerListener listener = new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {

        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {

        }

        @Override
        public void onDrawerStateChanged(int newState) {

        }
    };
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
    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"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/btn_open"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="상품 보기"
            android:textSize="22sp" />

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            android:src="@drawable/grocery"/>
    </LinearLayout>

    <include layout="@layout/activity_drawer"/>


</androidx.drawerlayout.widget.DrawerLayout>

activity_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#8BC34A"
    android:id="@+id/drawer"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/menu_snack"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        android:src="@drawable/chocolate">
    </ImageButton>
    <TextView
        android:text="제과"
        android:gravity="center"
        android:background="#FF9800"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <ImageButton
        android:id="@+id/menu_fruit"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:src="@drawable/fruit"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"/>
    <TextView
        android:text="과일"
        android:gravity="center"
        android:background="#FF5722"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btn_close"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="#E08E3C"
        android:text="닫기"/>

</LinearLayout>

activity_sub_fruit.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
    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"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/btn_home"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="처음으로"
            android:textSize="22sp" />

        <Button
            android:id="@+id/btn_open"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="다른 상품 보기"
            android:textSize="22sp" />

        <Button

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="과일"
            android:textSize="22sp" />

        <TextView
            android:text="사과 - 2,000원"
            android:padding="10sp"
            android:layout_margin="5sp"
            android:textSize="30sp"
            android:textColor="@color/white"
            android:background="#4CAF50"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:text="바나나 - 1,500원"
            android:padding="10sp"
            android:layout_margin="5sp"
            android:textSize="30sp"
            android:textColor="@color/white"
            android:background="#4CAF50"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:text="딸기 - 3,000원"
            android:padding="10sp"
            android:layout_margin="5sp"
            android:textSize="30sp"
            android:textColor="@color/white"
            android:background="#4CAF50"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <include layout="@layout/activity_drawer"/>


</androidx.drawerlayout.widget.DrawerLayout>

activity_sub_snack.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
    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"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/btn_home"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="처음으로"
            android:textSize="22sp" />

        <Button
            android:id="@+id/btn_open"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="다른 상품 보기"
            android:textSize="22sp" />

        <Button

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="과일"
            android:textSize="22sp" />

        <TextView
            android:text="사과 - 2,000원"
            android:padding="10sp"
            android:layout_margin="5sp"
            android:textSize="30sp"
            android:textColor="@color/white"
            android:background="#4CAF50"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:text="바나나 - 1,500원"
            android:padding="10sp"
            android:layout_margin="5sp"
            android:textSize="30sp"
            android:textColor="@color/white"
            android:background="#4CAF50"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:text="딸기 - 3,000원"
            android:padding="10sp"
            android:layout_margin="5sp"
            android:textSize="30sp"
            android:textColor="@color/white"
            android:background="#4CAF50"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <include layout="@layout/activity_drawer"/>


</androidx.drawerlayout.widget.DrawerLayout>

필요하신 분에게 도움이 되셨을지 모르겠습니다.
오늘도 방문해주시는 모든 분들께 감사드립니다.