2018/11/15

[Android] SeekBar

Android APP 有個可以拖曳調整的 SeekBar 工具。
在 xml 中加入 SeekBar 工具,設定格數255,最大值255。
activity_main.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="com.example.chris.myapplication.MainActivity">

    <TextView
        android:id="@+id/id_tvShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="4dp"
        android:layout_marginTop="8dp"
        android:text="Test"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <SeekBar
        android:id="@+id/id_sb_Show"
        android:layout_width="244dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="8dp"
        android:max="255"
        android:progress="255"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/id_tvShow" />

</android.support.constraint.ConstraintLayout>

MainActivity.java:
package com.example.chris.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity{

    private TextView tv_show;
    private SeekBar sbShow;

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

        tv_show = (TextView)findViewById(R.id.id_tvShow);

        sbShow = (SeekBar)findViewById(R.id.id_sb_Show);
        sbShow.setOnSeekBarChangeListener(sbList);
    }

    private SeekBar.OnSeekBarChangeListener sbList = new SeekBar.OnSeekBarChangeListener(){
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            switch (seekBar.getId()) {
                case R.id.id_sb_Show:
                    tv_show.setText("Para:" + progress);
                    break;
            }
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {}
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {}
    };
}
如果要用程式自動設定 Seekbar 的值,可以用
sbColorH.setProgress(value);
END

沒有留言:

張貼留言