安卓:如何在SeekBar中设置间隔

18
在我的应用程序中,我有一个在对话框中显示的Seekbar。现在我想设置Seekbar的间隔和步进值。间隔应为0-250,每个步长应为5分钟。
到目前为止,这是我的代码:
public class seekActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {
    SeekBar seekbar;
    Button button;
    TextView textview;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //set up main content view
        setContentView(R.layout.main);
        //this button will show the dialog
        Button button1main = (Button) findViewById(R.id.Button01main);
        button1main.setOnClickListener(this);
    }
    public void onClick(View v) {
        //set up dialog
        Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.maindialog);
        dialog.setTitle("This is my custom dialog box");
        dialog.setCancelable(true);
        button = (Button) dialog.findViewById(R.id.Button01);
        seekbar = (SeekBar) dialog.findViewById(R.id.seekBar1);
        seekbar.setOnSeekBarChangeListener(this);
        textview = (TextView) dialog.findViewById(R.id.textView1);
        dialog.show();
    }
    public class SeekBarPreference {
    }
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {
        // TODO Auto-generated method stub
        textview.setText(progress + "");
    }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    };
}

有谁能给我一些提示或代码,怎样做呢?

谢谢!


你的问题是如何让它每5分钟走一步吗? - cyngus
不要担心,如果默认情况下移动滑块时它会一次跨越一个步骤:1、2、3、4、5、6、7、8、9、10。我想让它每次移动5个步骤:5、10、15、20、25、30、35、40。如果这很难做到,请帮我调整间隔! - Seb
3个回答

45

你只需要按照以下方式更新onProgressChanged方法。


int stepSize = 5;
public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
    progress = ((int)Math.round(progress/stepSize))*stepSize;
    seekBar.setProgress(progress);
    textview.setText(progress + "");

}

4
由于progressstepSize已经是int类型,所以不需要使用Math.round(progress/stepSize) * stepSize就可以了。 - nemo
7
堆栈溢出...SeekBar的任何更改都会再次影响自身。 - Hossein Mansouri

29

为什么不直接将 SeekBar 的最大值设为 50(250/5),然后从 SeekBar 值到“实际”值进行必要的转换呢?


老问题,但仍然有效。将SeekBar的最大值设置为您想要的步骤数。SeekBar逻辑会为您完成其余部分。 - NikkyD

2
如果您使用

Math.round((float)progress / stepSize) * stepSize

您的阈值将位于两个步骤的中间

如果您使用

progress / stepSize * stepSize

滑块将总是跳到左侧的步骤。这只是在除法中截断小数位。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接