반응형

(210518 수정)

 

우리는 어떤 앱을 이용하든지 프로그래스바를 자주 볼 수 있다.

이 프로그래스바와 비슷한 '시크바(SeekBar)'는 프로그래스바를 상속했으며

프로그래스바의 속성을 그대로 사용할 수 있다.

 

추가적으로, 사용자가 핸들을 드래그하여 좌우로 이동하며

값을 직접 조절할 수 있다.

 

우리는 보통 시크바를 스마트폰 단말의 화면 밝기라든지 음량 조절에서 볼 수 있다.

 

이번에는 시크바를 이용하여 화면 밝기를 조절하는 기능을 구현해볼건데,

화면에 시크바를 놓고 시크바 조정에 따른 값을 시크바 밑의 텍스트뷰로 출력할 것이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">
 
    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100" />
 
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="밝기 조절"
        android:gravity="center"
        android:textSize="30sp" />
 
</LinearLayout>
cs

다음과 같이 XML 레이아웃 파일을 작성하게되면

 

시크바 초기 화면

이렇게 간단하게 만들 수 있다.

 

다음으로는 기능을 담당할 액티비티 화면을 만들어보겠다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class MainActivity extends AppCompatActivity {
    
    TextView tv;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        tv = (TextView)findViewById(R.id.tv);
        SeekBar seekBar = (SeekBar)findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { // 시크바의 값이 바뀔 때마다 리스너가 알려줌
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // 시크바의 값이 바뀔 때마다 호출됨
                Brightness(progress);
                tv.setText("화면 밝기 : " + progress); // progress로 밝기를 조절해서 텍스트뷰에 출력함
            }
 
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
 
            }
 
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
 
            }
        });
    }
 
    private void Brightness(int value) { 
        if(value < 10) {
            value = 10;
        } else if (value > 100) {
            value = 100;
        }
 
        // 윈도우 매니저로 화면 밝기 설정
        WindowManager.LayoutParams params = getWindow().getAttributes(); // 참조한 객체의 윈도우 정보를 확인/설정 할 수 있음
        params.screenBrightness = (float)value/100;
        getWindow().setAttributes(params);
    }
}
cs

 

이렇게 시크바를 움직임으로써 화면 밝기를 조절할 수 있다.

 

피드백은 언제나 환영입니다.

반응형

+ Recent posts