Tips

SeekBarを用いたサンプルアプリ

SeekBarを使ってみました。

※はじめに
この記事はAndroidアプリの開発が、初心者であるという方のための記事です。
そのため、なるべく複雑な説明は避け、コピー&ペイストですぐに動くものをご紹介します。
JavaやAndroidを理解されている方で細かい説明が必要な方は、当ブログ内の連載記事である「Android Tips」をご覧ください。

今回はSeekBarです。
SeekBarは音量や画面照度の調整等に使用します。
ここではSeekBarの最大値等はxml側で設定しています。

サンプルコード

アプリ実行図

1

2


画面レイアウトファイル(activity_main.xml)

アプリの画面レイアウトファイルです。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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:padding="15dp"
    android:orientation="vertical"
    tools:context=".MainActivity" >
 
    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="1000"
        android:progress="25"/>
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />
</LinearLayout>


Activityファイル(MainActivity.java)

Activityファイルです。

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
44
45
46
47
48
49
50
51
52
package com.example.seekbar;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
 
public class MainActivity extends Activity {
 
    private SeekBar seekBar;
    private TextView textView;
 
    int oldValue;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
 
            int oldValue;
 
            // ツマミに触れたときに呼び出される。
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
 
            }
 
            // ツマミをドラッグしたときに呼び出される。
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                oldValue = seekBar.getProgress();
                textView = (TextView) findViewById(R.id.textView1);
                textView.setText("音量:" + oldValue);
 
            }
 
            // ツマミを離したときに呼び出される。
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekBar.setSecondaryProgress(oldValue);
            }
 
        });
 
    }
 
}


以上でOKです。

Androidアプリ開発の必須知識!JAVAプログラミングを学べる連載リンク

はじめてのJAVA 連載

Recent News

Recent Tips

Tag Search