2018/11/15

[Android] SeekBar

Android APP 有個可以拖曳調整的 SeekBar 工具。
在 xml 中加入 SeekBar 工具,設定格數255,最大值255。
activity_main.xml:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context="com.example.chris.myapplication.MainActivity">
  8.  
  9. <TextView
  10. android:id="@+id/id_tvShow"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:layout_marginEnd="8dp"
  14. android:layout_marginStart="4dp"
  15. android:layout_marginTop="8dp"
  16. android:text="Test"
  17. app:layout_constraintEnd_toEndOf="parent"
  18. app:layout_constraintStart_toStartOf="parent"
  19. app:layout_constraintTop_toTopOf="parent" />
  20.  
  21. <SeekBar
  22. android:id="@+id/id_sb_Show"
  23. android:layout_width="244dp"
  24. android:layout_height="wrap_content"
  25. android:layout_marginEnd="8dp"
  26. android:layout_marginTop="8dp"
  27. android:max="255"
  28. android:progress="255"
  29. app:layout_constraintEnd_toEndOf="parent"
  30. app:layout_constraintStart_toStartOf="parent"
  31. app:layout_constraintTop_toBottomOf="@+id/id_tvShow" />
  32.  
  33. </android.support.constraint.ConstraintLayout>

MainActivity.java:
  1. package com.example.chris.myapplication;
  2.  
  3. import android.os.Bundle;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.widget.SeekBar;
  6. import android.widget.TextView;
  7.  
  8. public class MainActivity extends AppCompatActivity{
  9.  
  10. private TextView tv_show;
  11. private SeekBar sbShow;
  12.  
  13. @Override
  14. protected void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.activity_main);
  17.  
  18. tv_show = (TextView)findViewById(R.id.id_tvShow);
  19.  
  20. sbShow = (SeekBar)findViewById(R.id.id_sb_Show);
  21. sbShow.setOnSeekBarChangeListener(sbList);
  22. }
  23.  
  24. private SeekBar.OnSeekBarChangeListener sbList = new SeekBar.OnSeekBarChangeListener(){
  25. @Override
  26. public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  27. switch (seekBar.getId()) {
  28. case R.id.id_sb_Show:
  29. tv_show.setText("Para:" + progress);
  30. break;
  31. }
  32. }
  33. @Override
  34. public void onStartTrackingTouch(SeekBar seekBar) {}
  35. @Override
  36. public void onStopTrackingTouch(SeekBar seekBar) {}
  37. };
  38. }
如果要用程式自動設定 Seekbar 的值,可以用
  1. sbColorH.setProgress(value);
END

沒有留言:

張貼留言