첫 번째 행 코드 ----Material Design(1-3)

***
이 장은 모두 8개의 소절로 나뉘는데 개별적인 소절은 한 개의 지식점이 아니기 때문에 전체적으로 보면 이 장의 내용이 매우 많기 때문에 우리가 진지하게 대해야 한다!
1. Material Design 소개
간단하게 말하면 Material Design은 구글이 내놓은 훌륭하고 새로운 인터페이스 디자인 언어이다.
2.Toolbar
ActionBar (제목 표시줄) 에서 계승되는 Material 컨트롤이지만, 더욱 유연하고 사용하기 쉬워서, 현재는 ActionBar 대신 자주 사용됩니다.
기본 ActionBar를 어떻게 대체할까요?우선 원본 제목 표시줄을 숨기고res->values->styles를 수정합니다.xml 파일의parent 속성은 두 가지 선택이 있습니다: Theme.AppCompat.Light.NoActionBarTheme.AppCompat.NoActionBar.전자는 연한 색 주제이고 후자는 짙은 색 주제이다. 여기서 나는 전자의 연한 색 주제를 선택한다.styles.xml 파일은 일부 item 속성을 수정할 수 있지만, 내가 시험해 봤는데, textColor Primary, window Background,navigation BarColor는 모두 효과가 없었다. 나도 깊이 연구하지 않았는데, 무슨 원인인지 모르겠다.
그런 다음 activity 수정main.xml의 코드:
<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
	<android.support.v7.widget.Toolbar
        android:id="@+id/toolbars"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

그 중에서 xmlns:app는 5.0버전 전의 오래된 시스템을 호환하기 위한 것이다.android:theme는Toolbar에 짙은 색 테마를 사용하기 위한 것이다.app:popupTheme는 팝업된 메뉴 항목에 옅은 색 테마를 사용하기 위한 것입니다.
마지막으로 MainActivity를 수정하고 두 줄의 코드를 추가하면 됩니다.
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbars);
setSupportActionBar(toolbar);

단지 하나의 제목이 너무 단조로우니, 아래에 단추 아이콘을 추가하십시오
아이콘 그림을drawable-xxhdpi 디렉터리에 놓고res 디렉터리에menu 파일을 새로 만들고 그 다음에toolbar를 만듭니다.xml 파일, 코드는 다음과 같습니다.
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto">
            <item
                android:id="@+id/backup"
                android:icon="@drawable/ic_backup"
                android:title="Backup"
                app:showAsAction="always"/>
            <item
                android:id="@+id/delete"
                android:icon="@drawable/ic_delete"
                android:title="Delete"
                app:showAsAction="ifRoom"/>
            <item
                android:id="@+id/setting"
                android:icon="@drawable/ic_settings"
                android:title="Setting"
                app:showAsAction="never"/>
    </menu>

설명하고자 하는 것은 app:show Action뿐입니다. 이것은 단추의 표시 위치를 지정하는 데 사용됩니다. 그 중에서always는 Toolbar에 영원히 표시되고 공간이 부족하면 표시되지 않습니다.ifRoom은 화면 공간이 충분하면 Toolbar에 표시하고 부족하면 메뉴에 표시한다.never는 메뉴에 영원히 표시됩니다.
마지막으로 MainActivity를 수정합니다.
 public boolean onCreateOptionsMenu(Menu menu){
            getMenuInflater().inflate(R.menu.toolbar,menu);
            return true;
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()){
                case R.id.backup:
                    Toast.makeText(this,"You clicked Backup",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.delete:
                    Toast.makeText(this,"You clicked delete",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.setting:
                    Toast.makeText(this,"You clicked setting",Toast.LENGTH_SHORT).show();
                    break;
                case android.R.id.home:
                    mDrawerLayout.openDrawer(GravityCompat.START);
                    break;
                default:
            }
            return true;
        }

그중onCreateOptionsMenu() 방법에toolbar가 불러왔습니다.xml 메뉴 파일, 그리고 onOptionsItemSelected()에서 각 단추의 클릭 이벤트를 처리했습니다.
3. 슬라이딩 메뉴
슬라이딩 메뉴는 일부 메뉴를 숨기고 화면 공간을 절약하며 슬라이딩을 통해 표시할 수 있습니다.
슬라이딩 메뉴는 주로 DrawerLayout 컨트롤을 통해 이루어진다. 이 컨트롤은 하나의 레이아웃으로 두 개의 직접 하위 컨트롤이 있는데 첫 번째 하위 컨트롤은 메인 화면 내용을 표시하고 두 번째 하위 컨트롤은 슬라이딩 메뉴의 내용을 표시한다.
<android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <FrameLayout
      	      
        </FrameLayout>
        <TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_gravity="start"/>
        </android.support.v4.widget.DrawerLayout>

그 중에서 TextView android:layout_gravity="start" 에서 지정한 슬라이딩 메뉴가 어디에 있는지 시스템 언어가 어디에서 어디에 있는지에 따라 결정됩니다. 물론left와right도 직접 지정할 수 있습니다.
다음에 네비게이션 단추를 추가하여 이 단추를 눌러도 미끄럼 메뉴를 보여주는 기능을 실현한다. 아이콘 그림을 먼저 drawable-xxhdpi 디렉터리에 놓고 다음에MainActivity 코드를 수정하고oncrete()에 코드를 추가한다.
  private DrawerLayout mDrawerLayout;
      mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
      ActionBar actionBar=getSupportActionBar();
            if(actionBar!=null){
                actionBar.setDisplayHomeAsUpEnabled(true);//      ,       
                actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);//       menu  
            }

다시 onOptionsItemSelected()에 코드를 넣는다.
 //HomeAsUp id    android.R.id.home
    case android.R.id.home:
                    mDrawerLayout.openDrawer(GravityCompat.START);
                    break;

이 섹션 완료
슬라이딩 메뉴가 아름답지 않으므로 NavigationView 컨트롤을 사용하기 쉽도록 계속 수정해야 합니다.
우선 의존 관계를 추가하고 app/build을 엽니다.gradle 파일, 가입:
compile 'com.android.support:design:27.+'
compile 'de.hdodenhof:circleimageview:2.1.0'

자신의 sdk버전과 일치해야 하며, 확실하지 않으면'+'로 범지한다.두 번째 의존은 그림의 원형화 기능을 실현하기 위한 개원 프로젝트이다.
다음은menu와header Layout의 머리 레이아웃을 준비해야 합니다. 먼저menu를 준비해야 합니다. 아이콘 그림을 drawable-xxhdpi 디렉터리에 놓고 menu 아래에 nav 를 새로 만듭니다.menu 파일:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_call"
                android:icon="@drawable/nav_call"
                android:title="Call"/>
            <item
                android:id="@+id/nav_friends"
                android:icon="@drawable/nav_friends"
                android:title="Friends"/>
            <item
                android:id="@+id/nav_location"
                android:icon="@drawable/nav_location"
                android:title="Location"/>
            <item
                android:id="@+id/nav_mail"
                android:icon="@drawable/nav_mail"
                android:title="Mail"/>
            <item
                android:id="@+id/nav_task"
                android:icon="@drawable/nav_task"
                android:title="Task"/>
        </group>
    </menu>

menu에 그룹 탭을 끼워 넣으면 그룹을 표시합니다. android: checkable Behavior = "single"은 그룹의 모든 항목을 선택할 수 있습니다.다음 layout에 nav 라는 이름의 Layout resource file 파일을 새로 만듭니다.header.xml, 코드는 다음과 같습니다.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="180dp"
        android:padding="10dp"  android:background="?attr/colorPrimary">
    
        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/icon_image"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/nav_icon"
            android:layout_centerInParent="true"/>
        <TextView
            android:id="@+id/mail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="[email protected]"
            android:textColor="#FFF"
            android:textSize="14sp"/>
        <TextView
            android:id="@+id/username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@id/mail"
            android:text="Tony Green"
            android:textColor="#FFF"
            android:textSize="14sp"/>
    
    </RelativeLayout>

이 속성이 있는 메인 컨트롤의 내부 레이아웃 (하위 컨트롤) 의 경계를 의미하는padding만 설명합니다.반면margin은 반대로 이 속성이 있는 주 컨트롤의 외부 레이아웃 (부 레이아웃) 의 경계를 의미한다.
마지막으로 activity 수정main.xml 코드, 원래 TextView를 다음 코드로 교체합니다.
 <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:menu="@menu/nav_menu"
            app:headerLayout="@layout/nav_header"/>

MainActivity의 코드를 수정하고 onCreate()에 다음을 추가합니다.
NavigationView navView=(NavigationView)findViewById(R.id.nav_view);
    navView.setCheckedItem(R.id.nav_call);//     
    navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    mDrawerLayout.closeDrawers();
                    return true;
                }
            });

소스 주소: Material Design 전체 소스

좋은 웹페이지 즐겨찾기