[UMC Android 스터디] 워크북 1주차 - 2

박진성·2023년 6월 11일

UMC Android 스터디

목록 보기
2/3

Pallete 항목 조사하기

TextView

→ 개요

  • 사용자에게 글을 보여줄 수 있다.
  • 사용자 입력 못받음

→ 속성들

<TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="안녕하세요"
      android:textColor="@color/black"
      android:textStyle="bold"
      android:textSize="18dp"/>

// width & height 는 주로 wrap_content 사용.
// color & style & size 설정 가능

→ +) EditText

  • 사용자에게 글을 보여줄 수 있다.
  • 사용자 입력값 넣을수 있음
  • 어떤값을 입력받는지에 따라, inputType 다르게 입력
    • inputType 에 따라 올라오는 자판이 달라짐

      <!-- Password (Nemeric) xml Code -->
       <EditText
              android:id="@+id/editTextNumberPassword"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:hint="Password (Numeric)"
              android:inputType="numberPassword"/>
      
      // hint 는, edittext 클릭하기 전 흐리게 적혀있는 글씨
      종류입력 가능한 값설명inputType
      Plain Text모든 문자, 기호, 숫자기본 입력none
      Password모든 문자, 기호, 숫자비밀번호 입력. * 처리textPassword
      Password (Numeric)숫자비밀번호 숫자만 입력. * 처리numberPassword
      모든 문자, 기호, 숫자비밀번호 입력. * 처리 안함textVisiblePassword
      E-mail모든 문자, 기호, 숫자이메일 입력textEmailAddress
      Phone모든 문자, 기호, 숫자발음문자 입력textPhonetic
      Postal Address모든 문자, 기호, 숫자우편번호 입력textPostalAddress
      Multiline Text모든 문자, 기호, 숫자줄바꿈 설정 가능textMultiLine
      Time: 기호 숫자시간 입력time
      Date- 기호 숫자날짜 입력date
      Number숫자숫자 입력number
      Number (Signed)숫자부호있는 숫자 입력numberSigned
      Number (Decimal). 기호 숫자소수 입력numberDecimal

Button

→ 개요

  • 기본적인 Button.
  • 클릭시 SetOnClickListener 를 구현하여 이벤트 처리 가능
<Button
			android:id="@+id/btn"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Basic Button" />
btn.setOnClickListener {
    // 버튼 클릭시 이벤트 코딩
}
  • 버튼이 아닌 View에도 clickable = true 속성을 추가시키면, clicklistener 를 사용하여 클릭시 액션을 부여할 수 있다!

ImageView

→ 개요

  • View 속성을 상속받아, 이미지 화면에 표시 가능
<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/myimage" />

// src속성으로 drawable 폴더에 있는 이미지 불러오기 가능

→ 속성들

  • android:src
    • android:src="@drawable/img_pdp_top_01"
    • img_pdp_top_01 라는 이름의 이미지파일을 불러옴 (폴더는 drawable만 붙여도 알아서 찾아감)
  • android:contentDescription
    • android:contentDescription="@string/description_product_detail_thumbnail"
    • 해당 이미지에 대한 설명을 values/string.xml 에 해당 name으로 저장
  • android:scaleType

    • 이미지를 어떻게 보여줄지 결정하는 속성
    • https://sharp57dev.tistory.com/23 참조
    • centerCrop
      • 이미지 가로/세로중 짧은쪽을 ImageView 레이아웃에 꽉 차게 크기 맞춰 출력
      • 원본 가로세로 비율은 유지됨
      • 레이아웃을 벗어나면, 벗어난 이미지 출력되지 않음
    • centerInside
      • 이미지 가로/세로중 긴쪽을 ImageView 레이아웃에 꽉 차게 크기 맞춰 출력
      • 원본 가로세로 비율은 유지됨
      • 남는 공간은 background 의 색으로 채워짐
      • 이미지가 imageView 보다 작으면, 크기 유지됨
    • fitCenter
      • centerInside와 거의 유사, 이미지 크기가 ImageView보다 작으면 ImageView의 크기에 따라 달라짐
    • fitXY
      • 가로 세로 비율에 상관없이, imageView에 이미지가 꽉차게 보여짐!!!
    • center
      • 이미지 원본 크기,비율 유지하며 이미지 중앙을, layout_height / layout_width 안에 출력한다.
      • 레이아웃 벗어나면, 벗어난 이미지 출력되지 않는다
      • 레이아웃보다 이미지가 작으면, 이미지를 정가운데 정렬한다
  • android:alpha

    • 이미지의 채도 설정
    • 0 ~ 1 사이 값 설정
    • 0 에가까울수록 흐려짐, 1에가까울수록 원본과 같음
  • app:layout_constraintDimensionRatio

    • height 기준으로 width와 의 비율을 정의
    • app:layout_constraintDimensionRatio=”w, 1:1”
      • width와 1대 1 비율로 설정해줘 라는 뜻

FragmentContainerView

→ 개요

  • Fragment를 담기위해 설계된 View.
  • 한개의 화면을 분할하여, Fragment 여러개를 담을때 사용
  • Navigation 으로 BottomNavigationView 를 연결할때, 사용
<androidx.fragment.app.FragmentContainerView
    android:id="@+id/fragmentContainerView"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

// name 속성에 Fragment 를 추가시킨다

ImageButton

→ 개요

  • 기본 Button 이지만, 이미지를 Button에 삽입 가능
  • src 속성으로 이미지 불러오기 가능
    <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

→ 속성

ImageView와 속성 거의 유사. 사진을 fitting 하려면 자동으로 꽉차는 ImageView 와 달리 설정을 더 해줘야한다.

  • android:scaleType

    • 이미지를 어떻게 보여줄지 결정하는 속성
    • https://sharp57dev.tistory.com/23 참조
    • centerCrop
      • 이미지 가로/세로중 짧은쪽을 ImageView 레이아웃에 꽉 차게 크기 맞춰 출력
      • 원본 가로세로 비율은 유지됨
      • 레이아웃을 벗어나면, 벗어난 이미지 출력되지 않음
    • centerInside
      • 이미지 가로/세로중 긴쪽을 ImageView 레이아웃에 꽉 차게 크기 맞춰 출력
      • 원본 가로세로 비율은 유지됨
      • 남는 공간은 background 의 색으로 채워짐
      • 이미지가 imageView 보다 작으면, 크기 유지됨
    • fitCenter
      • centerInside와 거의 유사, 이미지 크기가 ImageView보다 작으면 ImageView의 크기에 따라 달라짐
    • fitXY
      • 가로 세로 비율에 상관없이, imageView에 이미지가 꽉차게 보여짐!!!
    • center
      • 이미지 원본 크기,비율 유지하며 이미지 중앙을, layout_height / layout_width 안에 출력한다.
      • 레이아웃 벗어나면, 벗어난 이미지 출력되지 않는다
      • 레이아웃보다 이미지가 작으면, 이미지를 정가운데 정렬한다
  • android:alpha

    • 이미지의 채도 설정
    • 0 ~ 1 사이 값 설정
    • 0 에가까울수록 흐려짐, 1에가까울수록 원본과 같음
  • Background 설정

    android:background="@android:color/transparent"
    • 이렇게 해줘야, 배경이 투명해져서 이미지가 꽉차게 보인다.

Switch

→ 개요

  • 토글식 버튼. OnOff 스위치 처럼 생김
    • ToggleButton / Chip / RadioButton / CheckBox 와 유사
<ToggleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Toggle"
    android:textOff="Off"
    android:textOn="On" />

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOff="Off"
    android:textOn="On"
    android:checked="true" />

캡처.JPG

→ 속성

캡처.JPG

→ 이벤트 처리

  • setonCheckedChangeListener 사용,
  • ischecked 변수로 상태표시
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.togglebutton)

       
        switch1.setOnCheckedChangeListener { button, ischecked ->
            if(ischecked)
                Toast.makeText(this, "Switch is checked", Toast.LENGTH_SHORT).show()
            else
                Toast.makeText(this, "Switch is unchecked", Toast.LENGTH_SHORT).show()

        }
    }
}

ChipGroup & Chip

→ 개요

  • 토글식 버튼 다수)
    • 마치 index 목차처럼, 눌렀을때 어떤 대응되는 동작이 실행되는 버튼
    • 토글버튼이므로 다른걸 누르면, 눌렸던게 비활성화 된다
    • ToggleButton / Switch / RadioButton / CheckBox 와 유사
  • Style 적용을 AppCompat 이 아닌 MaterialComponents 로 변경 필요
    • app 모듈의 build.gradle 에 코드 추가

      implementation 'com.google.android.material:material:$version'
    • resource style 수정

      <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">

캡처.JPG

→ 속성

  • ChipGroup 안에 Chip들이 들어가있는 형태
<?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"
    ...>

        <com.google.android.material.chip.ChipGroup
            android:id="@+id/chipGroup"
            app:chipSpacingHorizontal="30dp"
            app:singleSelection="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:id="@+id/chip01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipMinHeight="40dp"
                app:chipStartPadding="20dp"
                app:chipEndPadding="20dp"
                app:chipBackgroundColor="@color/chip_check"
                android:textSize="18sp"
                android:textColor="@color/white"
                android:text="Chip 1"/>

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:id="@+id/chip02"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipStartPadding="20dp"
                app:chipEndPadding="20dp"
                app:chipStrokeColor="@color/chip_border_check"
                app:chipStrokeWidth="2dp"
                app:chipBackgroundColor="@color/chip_check"
                android:textSize="18sp"
                android:textColor="@color/white"
                android:text="Chip 2"/>

            <com.google.android.material.chip.Chip
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:id="@+id/chip03"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipStartPadding="20dp"
                app:chipEndPadding="20dp"
                app:chipBackgroundColor="@color/chip_check"
                android:textSize="18sp"
                android:textColor="@color/white"
                android:text="Chip 3"/>

        </com.google.android.material.chip.ChipGroup>

</LinearLayout>
  • ChipGroup 속성

    • chipSpacingHorizontal 속성: chip 버튼 간에 Horizontal 거리를 설정한다.
    • singleSelection 속성: True 값을 줌으로써 Group 내에 포함된 chip 중 하나만을 선택이 가능하도록 만든다.
  • Chip 속성

    • chipMinHeight 속성 : chip 버튼의 높이를 설정할 수 있다.
    • chipStartPadding&chipEndPadding 속성: 각각 chip 버튼의 좌우 패딩을 값을 설정한다.
    • chipStrokeWidth&chipStrokeColor 속성: 각각 테두리의 굵기와 색상을 설정한다.
    • chipBackgroundColor 속성: chip 버튼의 백그라운드 색을 설정한다.

CheckBox

→ 개요

  • 토글식 버튼 : 체크가 가능
    • ToggleButton / Chip / RadioButton / Switch 와 유사

→ 속성

<CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="check" 
				android:checked="true"/>

// text 로 체크박스 오른쪽에 글을 표시할수 있다
// checked 로 최초 체크박스의 체크상태를 표시할 수 있다.

→ 이벤트 처리

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.checkbox)
        // setOnClickListener 설정
        checkBox.setOnClickListener{
            // check 된다면
            if(checkBox.isChecked)
                Toast.makeText(this, "checked", Toast.LENGTH_SHORT).show()
            // uncheck 된다면
            else
                Toast.makeText(this, "unchecked", Toast.LENGTH_SHORT).show()
        }
    }
}

RadioGroup & RadioButton

→ 개요

  • 토글식 버튼 : 여러항목중 선택
    • ToggleButton / Chip / CheckBox / Switch 와 유사
    • 여러개의 체크박스가 Chip처럼 작동한다고 생각하면 됨!

캡처.JPG

→ 속성

  • RadioGroup 안에 RadioButton 들이 들어가있는 형태
<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 1" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 2" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 3" />

</RadioGroup>

→ 이벤트 처리

  • radioGroup 에 setOnCheckedChangeListener 메소드로 이벤트 처리
  • checkedId 로 체크된 항목 구분
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.radiobutton)

        radioGroup.setOnCheckedChangeListener {  group, checkedId ->
            val radio: RadioButton = findViewById(checkedId)
            Toast.makeText(applicationContext," On checked change :" + " ${radio.text}", Toast.LENGTH_SHORT).show()
        }
    }

        fun radio_button_click(view: View){
            val radio: RadioButton = findViewById(radioGroup.checkedRadioButtonId)
            //Toast.makeText(applicationContext,"On click : ${radio.text}", Toast.LENGTH_SHORT).show()
    }

}

FloatingActionButton

→ 개요

  • 여러개의 버튼이 겹쳐있다가, 애니메이션으로 나뉘는 효과 구현 가능

  • Style 적용을 AppCompat 이 아닌 MaterialComponents 로 변경 필요

    • app 모듈의 build.gradle 에 코드 추가

      implementation 'com.google.android.material:material:$version'
    • resource style 수정

      <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
  • 기본형 / 소형 / 확장형 3가지 있음
    • 소형 버전은 fabSize 속성을 mini 로 지정
    • Extended 버전은 아예 View 자체가 다름

캡처.JPG

캡처2.JPG

캡처.JPG

→ 속성

<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:src="@drawable/ic_my_icon"
        android:contentDescription="@string/submit"
				app:rippleColor="@color/pink"/>
  • rippleColor

    • 클릭시 변하는 색상 설정
  • src

    • 아이콘 삽입 가능

→ 이벤트처리

val fab: View = findViewById(R.id.fab)
fab.setOnClickListener { view ->
    Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
            .setAction("Action", null)
            .show()
}

WebView

→ 개요

  • View 속성을 상속받아, 특정한 url과 연결된 화면을 표시!
  • 앱으로 웹을 감싼다고 생각하면 편함!
<WebView
            android:id="@+id/wView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
  • 특별한 속성은 없지만, 웹과의 데이터 전송, 이벤트 처리에 kotlin class 로 작업 필요

ProgressBar

→ 개요

  • 진행상황을 나타내는 원형의 컴포넌트를 화면에 표시. (로딩창)
  • 디폴트는 원형이지만, 원형과 가로줄 모두 많이 쓰임

→ ProgressBar (Horizontal)

  • 진행상황을 나타내는 가로줄의 컴포넌트를 화면에 표시. (로딩창)
  • style 에 .Horizontal 적용하면 됨

→ 속성

<ProgressBar
        android:id="@+id/pb_ingame_timebar"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="120dp"
        android:layout_height="30dp"
        android:layout_marginLeft="10dp"
        android:progress="100"
        android:progressBackgroundTint="@color/black"
        android:progressTint="#DBA901"
        android:scaleY="3" />

// style : 가로 ProgressBar를 진행하기 위해, 해당 스타일을 Horizontal로 적용시킨다
// progressBackgroundTint : 비어있는 진행바 부분 색상을 선택한다
// progressTint: 채워져있는 진행바 부분 색상을 선택한다
// scaleY : 진행바의 굵기를 선택한다
// progress : 진행바의 채워져있는 비율을 선택한다. 이부분을 시간에따라 변화시키면 된다

SeekBar

→ 개요

  • 진행 상황을 나타내는 가로줄의 컴포넌트
  • 드래그나 키보드 방향키로 진행 수준을 설정할 수 있음. (동영상 재생바)

→ SeekBar (Discrete)

  • SeekBar 와 같지만, 특정 값에 점이 찍혀있어, 점사이 이동 가능
  • theme 에 SeekBar.Discrete 적용시킴

→ 속성

<SeekBar
     android:id="@+id/sb"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:max="100"
		 android:progress="50"
     android:thumb="drawable/"
     android:theme="@style/Widget.AppCompat.SeekBar.Discrete" />

// max : 바의 최댓값
// progress : 처음 보일때 진행도 설정
// thumb : 드래그 할때 커서모양 설정 가능

Spinner

→ 개요

  • 드롭다운 형태로, 사용자가 원하는 아이템 선택할수 있도록 해주는 레이아웃
  • 따로 특별한 속성은 없으나, 목록 연결은 Activity 및 Fragment 에서 진행.

캡처.JPG

→ 사용법

  • 배열을 사용 Or values 폴더에 xml 파일로 목록 생성
  • ArrayAdapter 및 click Listener 사용하여, 연결

ScrollView

→ 개요

  • 수직으로 스크롤 가능한 View. 화면크기 이상의 위젯을 넣을 수 있다
  • 보통 ScrollView 안에 LinearLayout 의 orientation vertical 을 넣어 짝을 이룬다
  • 반드시 하나의 자식만 가질 수 있다!!!!

→ 속성

<ScrollView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:fillViewport="true"
      android:scrollbars="none"/>

// scrollbars : 스크롤바 유무 / 방향 설정
// fillViewport : 스크롤뷰 하위 항목의 높이가 더 작은경우, 부모View 만큼 높이 확장 가능. 되도록 true로 놓는다

HorizontalScrollView

→ 개요

  • 수평으로 스크롤 가능한 View

  • 보통 ScrollView 안에 RelativeLayout 또는 LinearLayout(horizontal) 을 넣어 짝을 이룬다

  • 반드시 하나의 자식만 가질 수 있다!!!!

  • 속성은 ScrollView 와 같다

NestedScrollView

→ 개요

  • 한 화면에 여러개의 스크롤을 사용할 수 있다.

  • ScrollView 안에 Recycler View 넣어야 할때 자주 사용됨

  • 스크롤을 감지해서 변화를 주어야 할때, CoordinatorLayout / AppBarLayout과 함께 자주 사용됨

  • ScrollView 와 마찬가지로 하나의 자식만 가질 수 있다!!

    • 사용법 또한 ScrollVIew 와 다를게 없다

<androidx.core.widget.NestedScrollView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  app:layout_behavior="@string/appbar_scrolling_view_behavior">

  <androidx.constraintlayout.widget.ConstraintLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content">

  . . . 

  </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>

RecyclerView

→ 개요

  • 같은 형태의 아이템을, 내용만 바꿔 여러번 사용해야될때 사용.

    • ex) 인스타 댓글, 인스타 게시물, 네이버웹툰의 웹툰목록
    • ‘틀’ 은 같지만 내용물이 다른것들!
  • 총 2가지 XML 파일이 필요하다

    • 우선, RecyclerView 자체가 View로서 존재하기 떄문에, 이를 삽입할 layout이 필요하다

    • 두번째로, 아이템을 RecyclerView에 띄우는 것이므로, 아이템 하나의 형태를정의하는 layout이 필요하다

      
      // RecyclerView 의 XML
      
      <androidx.recyclerview.widget.RecyclerView
              android:id="@+id/test"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
              tools:listitem="@layout/recycler_test"/>
      
      // Item 의 XML
      
      <?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"
          android:id="@+id/recycler_comment_layout"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
      
          <ImageButton
              android:id="@+id/img_btn"
              android:layout_width="25dp"
              android:layout_height="25dp"
              android:background="@android:color/transparent"/>
      
      </LinearLayout>

→ ListView vs RecyclerView

ListView의 단점 (View 재활용 없음)

  1. 스크롤시 버벅임. findViewById 메소드 사용으로 비용이 상당히 많이듬
  2. 기본 애니메이션 지원이 없음. 커스터마이징 해야함
  3. 오직 수직 스크롤만 가능

캡처.JPG

위의 단점들을 보완한것이 RecyclerView 이다

→ 동작 원리

Adapter 가 데이터를 View에 바인딩 한후, 이를 LayoutManager 에게 제공한다

ViewHolder에 화면에 맞는 아이템 뷰의 수만 할당하고, 스크롤할때 화면에서 사라지는 View 객체는, 사라지는게 아닌 위치만 이동하여 재사용 된다. View 객체만 재사용되는 것이지, View 객체 안에 담긴 데이터는 갱신된다 (ViewHolder 의 bind 함수를 통하여 갱신됨)

onCreatViewHolder 를 호출하여 View를 생성, 그후 onBindViewHolder 를 호출하여 View를 바인딩하고, 최종적으로 리턴

→ RecyclerView 의 4가지 주 컴포넌트

  1. Adapter

앱의 데이터에서 RecyclerView에 표시되는 아이템뷰에 바인딩을 제공. 각 아이템 뷰의 위치를 데이터 소스의 특정 위치에 연결할 수 있다

  1. LayoutManager

RecyclerView 내에 아이템을 어떻게 배치할지 설정 가능. Linear 또는 Grid 를 기본으로 사용 가능

  1. ItemAnimator

기본 애니메이션이 제공되며, 이를 오버라이드하고 변경할 수 있다.

  1. ViewHolder

화면에 그리고 싶은 개별적인 아이템의 UI를 그릴 수 있도록 도와줌

ViewPager2

→ 개요

  • 좌우 / 상하 스크롤시 View가 바뀌는 애니메이션을 포함한 View
  • ViewPager2 사용시 주로 TabLayout 도 같이 사용!
    • ViewPager2 로 스와이핑 되는 내역을, TabLayout 에서 표시
    • 하단 점 5개가 TabItem 없이 구현된 TabLayout 이다
  • 의존성 추가해줘야함
implementation "androidx.viewpager2:viewpager2:1.0.0"
  • RecyclerView 와 마찬가지로, 총 두가지 layout 이 필요함.
    • ViewPager 자체를 담는layout
    • ViewPager 에 띄울 아이템을 담는 layout

캡처.JPG

BottomNavigationView

→ 개요

  • 하단의 Nav Bar를 생성하는 View
  • Navigation 을 연결하거나 수동으로 연결하여 사용한다

캡처.JPG

→ 사용법

1. BottomNavigationView 작성

//activity_home.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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">

    ...

	
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/home_navigation"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:menu="@menu/navigation_home_menu"
        app:itemTextColor="@drawable/menu_selector_color"
        app:labelVisibilityMode="labeled"/>

</androidx.constraintlayout.widget.ConstraintLayout>

// menu : 메뉴아이콘들을 담은 파일을 연결하는 속성
  • 선택안된 메뉴 라벨이 안보이는 현상

labelVisibilityMode=”labeled” 로 해결

라벨없는 BtnV 는 “unlabeled” 로 설정

  • menu selector 파일과의 연결

menu=”@menu폴더” 로 해결

2. menu 폴더&파일 생성

메뉴 아이콘 설정 & 클릭시 버튼모양 바뀌는 설정

→ 아이콘 파일 생성

  • src/res/drawable 폴더에 아이콘 파일 추가

→ Selector 파일 생성

  • src/res/drawable 폴더에 selector.xml 파일 생성 (아이콘 4면 4개의 selector 파일)
  • selector 컴포넌트로 구성된 xml 파일은, 우상단에 State Selector 라는 버튼이 있다
    • 클릭시, 여러 상태값을 볼 수 있다! 클릭 이외에도 여러가지 구현 가능!
// selector_download_icon.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/download_on" android:state_selected="true"/>
    <item android:drawable="@drawable/download_off" android:state_selected="false"/>
</selector>

// selector_game_icon.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/game_on" android:state_selected="true"/>
    <item android:drawable="@drawable/game_off" android:state_selected="false"/>
</selector>

// selector_home_icon.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/home_on" android:state_selected="true"/>
    <item android:drawable="@drawable/home_off" android:state_selected="false"/>
</selector>

// selector_newhot_icon.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/video_on" android:state_selected="true"/>
    <item android:drawable="@drawable/video_off" android:state_selected="false"/>
</selector>

→ menu 파일 생성

  • src/res 하위에 menu 폴더 생성
  • menu폴더 내부에 menu.xml 파일 생성
  • 각 아이템 icon 속성에, selector 파일 연결
// navigation_home_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/selector_home_icon"
        android:title="" />

    <item
        android:id="@+id/navigation_game"
        android:icon="@drawable/selector_game_icon"
        android:title="게임" />

    <item
        android:id="@+id/navigation_newhot"
        android:icon="@drawable/selector_newhot_icon"
        android:title="NEW HOT" />

    <item
        android:id="@+id/navigation_stored"
        android:icon="@drawable/selector_download_icon"
        android:title="저장된 목록" />
</menu>
  • 아이콘색상 반영 안되는 오류 발생

.itemIconTintList = null 로 해결

// HomeActivity
override fun onStart() {
        val bnView = findViewById<BottomNavigationView>(R.id.home_navigation)
        bnView.itemIconTintList = null
}

TabLayout

→ 개요

  • 터치한 탭에 따라 보여주는 화면을 다르게 하는 컴포넌트
  • BottomNavigationView 와 비슷한 기능
  • 주로 ViewPager2 의 indicator 역할을 함

캡처.JPG

→ 속성

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="scrollable"/>

// tabMode 를 scrollable 하게되면,  Tab이 화면에 다 안나올정도로 많을때, scroll 가능해진다
// 기본값은 fixed
  • 이렇게 TabItem 을 하위에 넣어서도 사용 가능. Tab 안에 이미지나 텍스트 삽입
<com.google.android.material.tabs.TabLayout
         android:layout_height="wrap_content"
         android:layout_width="match_parent">

   <com.google.android.material.tabs.TabItem
           android:text="@string/tab_text"/>

   <com.google.android.material.tabs.TabItem
           android:icon="@drawable/ic_android"/>

</com.google.android.material.tabs.TabLayout>



profile
Android Developer

0개의 댓글