메뉴 건너뛰기

조회 수 1280 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

1. Switch 주요 속성

속성명 설명
android : showText

on/off (설정/해제) Text가 보일지 안보일지를 결정하는 속성.

showText = true 설정된 모습
android : thumbTextPadding Switch Caption과 Thumb 사이의 간격
android : switchMinWidth 스위치의 너비 최소 크기
android : switchPadding Switch Caption과 스위치 사이의 간격
androiid : switchAppearance on/off Text의 Style 지정
android : textOff off 상태일 때 표시 될 Text 지정
android : textOn On 상태일 때 표시 될 Text 지정
android : textStyle Text Style(bold, italic, bolditalic)
android : thumb  사용자 드래그를 통해 on/off 설정이 가능하도록하는 thumb 모양
android : thumbTint thumb에 색상 지정
android : track track 모양 지정
android : trackTint track에 색상 지정

2. Switch 구현 예제

2.1 메인 화면 XML 레이아웃 리소스

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    tools:context=".MainActivity">

    <Switch
        android:id="@+id/visibilitySwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:switchMinWidth="100dp"
        android:switchPadding="20dp"
        android:text="Text Visibility"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Switch
        android:id="@+id/boldSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:switchMinWidth="100dp"
        android:switchPadding="20dp"
        android:text="Text Bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/visibilitySwitch" />

    <Switch
        android:id="@+id/colorSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:switchMinWidth="100dp"
        android:switchPadding="20dp"
        android:text="Text Color"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/boldSwitch" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Hello World"
        android:textSize="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/colorSwitch" />
</android.support.constraint.ConstraintLayout>

 

 

 레이아웃 형태는 ConstraintLayout 아래에 Switch 3개와 TextView 한 개를 배치하였습니다. 각 Switch는 하단에 표시되는 TextView의 Style 및 Visibility에 대한 Option을 제어하도록 구현할 것입니다. 


2.2 Switch option 변경에 따른 이벤트 처리

각 Switch의 On/Off 설정 변경에 대한 이벤트 처리를 위해 각 Switch에 대한 리스너를 구현합니다.

    class visibilitySwitchListener implements CompoundButton.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                textView.setVisibility(View.INVISIBLE);
            else
                textView.setVisibility(View.VISIBLE);
        }
    }

    class boldSwitchListener implements CompoundButton.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                textView.setTypeface(null, Typeface.BOLD);
            else
                textView.setTypeface(null, Typeface.NORMAL);
        }
    }

    class colorSwitchListener implements CompoundButton.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                textView.setTextColor(Color.RED);
            else
                textView.setTextColor(Color.BLACK);
        }
    }

 

▼ CompoundButton.OnCheckedChangeListener 인터페이스를 상속받아 각 Switch에 대한 리스너를 구현합니다. 두 번째 인자로 현재 Switch가 On 인지 Off 상태인지를 체크할 수 있는 boolean 타입의 매개변수가 전달되는데 해당 변수를 통해 분기를 하여 각 Switch 설정에 따른 동작을 구현하시면 됩니다.


2.3 onCreate() 구현

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

        visibilitySwitch = findViewById(R.id.visibilitySwitch);
        boldSwitch = findViewById(R.id.boldSwitch);
        colorSwitch = findViewById(R.id.colorSwitch);
        textView = findViewById(R.id.textView);

        visibilitySwitch.setOnCheckedChangeListener(new visibilitySwitchListener());
        boldSwitch.setOnCheckedChangeListener(new boldSwitchListener());
        colorSwitch.setOnCheckedChangeListener(new colorSwitchListener());
    }

▼onCreate()에서는 XML 레이아웃 리소스에 정의된 Swtich와 TextView에 대한 참조 객체를 얻어오고 앞서 구현한 리스너의 객체를 생성하여 setOnCheckedChangeListener()를 통해 리스너를 등록합니다.


List of Articles
번호 제목 날짜 조회 수
257 [하이브리드앱] userAgent를 이용해서 웹 / 앱 접속 구분하기 2021.09.30 1280
256 [하이브리드앱] 링크를 웹뷰가 아닌 새로운 브라우저에서 열기 2021.09.30 292
255 Firebase - 푸시알림 보내기 (2) 2021.09.30 768
254 Firebase - 푸시알림 보내기 file 2021.09.30 339
253 앱 번들(Android App Bundle) 만들기 file 2021.09.14 305
252 [Android] 퍼미션 권한체크(테드퍼미션) 2021.09.14 616
251 안드로이드 액티비티 세로고정 2021.09.14 207
250 안드로이드 - 커스텀 폰트(Custom Font) 적용하기 file 2021.04.02 342
249 안드로이드 - RecyclerView의 ViewType 구분하기 file 2021.04.02 931
248 안드로이드 - 리사이클러뷰 (RecyclerView) notifyDataSetChanged 실행 시 깜빡 거리는 현상 2021.04.02 746
247 안드로이드 - 갤러리에서 이미지 가져오기 2021.04.02 665
246 안드로이드 - 플로팅 액션 버튼(Floating Action Button) 사용법 file 2021.04.02 969
245 안드로이드 - Text 입력 이벤트 처리 - TextWatcher file 2021.04.02 556
244 안드로이드 - KeyEvent(키 이벤트) 처리 file 2021.04.02 1210
243 안드로이드 - BottomNavigationView 사용하여 하단 메뉴 만들기 file 2021.04.02 1430
242 안드로이드 - 프래그먼트 (Fragment) 사용하기 file 2021.04.02 486
» 안드로이드 - switch를 사용법 및 구현 file 2021.04.02 1280
240 안드로이드 - RatingBar를 통해 별점주기 file 2021.04.02 842
239 안드로이드 - SharedPreferences에 앱 정보 저장하기 file 2021.04.02 395
238 안드로이드 - 뷰페이저(ViewPager) 구현 file 2021.04.02 322
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved