3월 11일

SJY0000·2022년 3월 14일
0

Android

목록 보기
9/15

오늘 배운 것

  • TODO Project의 TODO APP 만들기(4)

메인액티비티

package com.example.todo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.example.todo.fragment.user.UserInfoFragment;
import com.example.todo.fragment.user.UserModifyFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;

public class MainActivity extends AppCompatActivity {

    public static final String TAG = "Main";
    public static final int USER_INFO = 0;
    public static final int USER_MODIFY = 1;
    DrawerLayout drawerLayout;
    TextView textview;
    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 인텐트 객체 참조 가져오기(From LoginActivity)
        Intent intent = getIntent();
        // 데이터 받기 1)
        String loginId = intent.getStringExtra("loginId");
        String firstName = intent.getStringExtra("firstName");
        String lastName = intent.getStringExtra("lastName");
        // 데이터 받기 2)
//        Bundle bundle = intent.getExtras();
//        loginId = bundle.getString("loginId");

//        textview = findViewById(R.id.tvProfileName);
//        textview.append( "\n 로그인 아이디 : " + loginId);

        // 툴바 참조 가져오기
        toolbar = findViewById(R.id.toolbar);
        // 툴바를 액션바로 사용한다고 선언
        setSupportActionBar(toolbar);

        // 액션바 참조 가져오기
        ActionBar actionBar = getSupportActionBar();
        // 액션바 제목 숨기기
        actionBar.setDisplayShowTitleEnabled(false);

        // drawerlayout에 액션바 토글버튼으로 NavigationView 띄우기 설정
        drawerLayout = findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close
        );
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();

        // 내비게이션 뷰에 메뉴아이템 이벤트 연결하기
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            // nav에서 선택한 아이템이 MenuItem으로 넘어옴
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                if (itemId == R.id.menu_user_logout) {
                    Log.d(TAG, "로그아웃 메뉴 선택됨");
                    showDialogLogout();
                } else if (itemId == R.id.menu_user_info) {
                    Log.d(TAG, "내 정보 조회 메뉴 선택됨");
                    onFragmentChanged(USER_INFO);
                } else if (itemId == R.id.menu_user_modify) {
                    Log.d(TAG, "내 정보 수정 메뉴 선택됨");
                    onFragmentChanged(USER_MODIFY);
                } else if (itemId == R.id.menu_user_remove) {
                    Log.d(TAG, "회원탈퇴 메뉴 선택됨");
                }
                return true;
            }
        });
        // 내비게이션 뷰의 헤더레이아웃에 로그인 사용자정보 설정하기
        View headerView = navigationView.getHeaderView(0);
        TextView tvProfileName = headerView.findViewById(R.id.tvProfileName);
        TextView tvProfileIntro = headerView.findViewById(R.id.tvProfileIntro);
        tvProfileName.setText(firstName + lastName);
        tvProfileIntro.setText(loginId);

        // Bottom 내비게이션뷰에 메뉴아이템 선택 이벤트 연결하기
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navi);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch(item.getItemId()) {
                    case R.id.bottom_menu_mytodo: Log.d(TAG, "내 할일 메뉴 선택됨"); break;
                    case R.id.bottom_menu_alltodo: Log.d(TAG, "모든 할일 메뉴 선택됨"); break;
                    case R.id.bottom_menu_chart: Log.d(TAG, "차트 메뉴 선택됨"); break;
                }

                return false;
            }
        });


    } // onCreate

    private void showDialogLogout() {
        // 대화상자 준비하기
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                                                .setTitle("로그아웃")
                                                .setMessage("로그아웃 하시겠습니까?")
                                                .setIcon(android.R.drawable.ic_dialog_alert)
                                                .setPositiveButton("예", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        // 파일에 저장한 로그인 상태유지 관련 정보 모두 삭제하기
                                                        SharedPreferences pref = getSharedPreferences("todo", Activity.MODE_PRIVATE);
                                                        SharedPreferences.Editor editor =  pref.edit();
                                                        editor.clear();
                                                        editor.commit();

                                                        //로그인 화면 띄우기
                                                        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                                                        startActivity(intent);

                                                        //현재 MainActivity 닫기
                                                        finish();

                                                    }
                                                })
                                                .setNeutralButton("취소", null)
                                                .create();
        alertDialog.show();
    }// processLogout

    // drawerLayout이 열려 있으면 app을 종료하지 않고 drawerLayout을 종료함
    @Override
    public void onBackPressed() {
        if(drawerLayout.isDrawerOpen(GravityCompat.START)) {// 하위호환성을 위해 START 사용
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed(); // 완전히 재정의 하는 경우는 드물고 기능이 들어있기 때문에 삭제X
        }

    }// onBackPressed

    public void onFragmentChanged(int index) {
        Fragment fragment = null;
        if (index == USER_INFO) {
            fragment = new UserInfoFragment();
        } else if (index == USER_MODIFY) {
            fragment = new UserModifyFragment();
        }
        if (fragment == null) {
            return;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                        .replace(R.id.container, fragment)
                        .commit();
        drawerLayout.closeDrawer(GravityCompat.START);
    }// onFragmentChanged
}

메인 화면(중요)

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:id="@+id/drawer_layout"

    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <!--> 화면 비율을 계산해서 출력하는게 coordinator<-->
        <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <com.google.android.material.appbar.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
                <!--> 실제 눈에 보이는 객체<-->
                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/material_dynamic_neutral80"
                    android:elevation="10dp"
                    android:theme="@style/ThemeOverlay.AppCompat.Dark" />
            </com.google.android.material.appbar.AppBarLayout>

            <FrameLayout
                android:id="@+id/container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="50dp">
            </FrameLayout>
            <!-->CoordinatorLayout안에 하나만 넣어야됨<-->
        </androidx.coordinatorlayout.widget.CoordinatorLayout>
        <!-->밑에서 항상 띄워져 있는 네브바<-->
        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navi"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:menu="@menu/activity_main_bottom"/>
    </LinearLayout>

    <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:id="@+id/nav_view"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>

네브 헤더

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="230dp"
    android:background="@color/material_dynamic_neutral80"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Light">

    <ImageView
        android:id="@+id/imgProfile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_foreground" />

    <TextView
        android:id="@+id/tvProfileName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="이름"
        android:textSize="28sp"
        android:textStyle="bold"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2" />

    <TextView
        android:id="@+id/tvProfileIntro"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="자기소개"
        android:textSize="20sp"
        android:textStyle="bold" />
</LinearLayout>

메인 드로워

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <!--> android:checkableBehavior="single" 한 번에 하나만 선택</-->
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/menu_user_info"
            android:title="내 정보 조회"
            android:icon="@android:drawable/ic_menu_myplaces"/>
        <item
            android:id="@+id/menu_user_pwd"
            android:title="내 비밀번호 수정"
            android:icon="@android:drawable/ic_lock_idle_lock"/>
        <item
            android:id="@+id/menu_user_modify"
            android:title="내 정보 수정"
            android:icon="@android:drawable/ic_menu_edit"/>
        <item
            android:id="@+id/menu_user_remove"
            android:title="회원탈퇴"
            android:icon="@android:drawable/ic_delete"/>
        <item
            android:id="@+id/menu_user_logout"
            android:title="로그아웃"
            android:icon="@android:drawable/ic_lock_power_off"/>
    </group>
</menu>

바텀바

<?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/bottom_menu_mytodo"
        android:title="내 할일"
        android:icon="@android:drawable/ic_lock_idle_alarm"
        android:enabled="true"
        app:showAsAction="ifRoom"/>
    <item
        android:id="@+id/bottom_menu_alltodo"
        android:title="전체 할일"
        android:icon="@android:drawable/ic_menu_share"
        android:enabled="true"
        app:showAsAction="ifRoom"/>
    <item
        android:id="@+id/bottom_menu_chart"
        android:title="차트"
        android:icon="@android:drawable/ic_menu_report_image"
        android:enabled="true"
        app:showAsAction="ifRoom"/>

</menu>







위의 결과를 합치면

MainActivity

drawerLayout

로그아웃 클릭(터치) 시

설정파일에 수정

1) String.Xml파일에 추가

2) themes.xml파일내용 변경(noActionbar)


Drawer의 내 정보 조회 클릭(터치) 시

InfoFragment

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".fragment.user.UserInfoFragment" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="내정보조회" />
</LinearLayout>
// 내 정보 조회 부분화면
public class UserInfoFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_user_info, container, false);

        return view;
    }
}

ModifyFragment

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/material_dynamic_neutral30"
    android:orientation="vertical"
    tools:context=".fragment.user.UserInfoFragment">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="내정보수정" />
</LinearLayout>
// 내 정보 수정 부분화면
public class UserModifyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_user_modify, container, false);

        return view;
    }
}

터치를 하면

잘 이동하는 것을 알 수 있다.

0개의 댓글

관련 채용 정보