如何使用水平滚动按钮增加或减少计数器

时间:2013-07-19 13:56:27

标签: android counter

我正在创建一个Android应用程序,我想在其中添加一个水平滚动按钮来增加/减少计数器。

例如,如果用户向右滚动按钮,则计数器应增加1,向左滚动会使计数器减1。

请告诉我该怎么做才能完成任务。看一下具有我想要的功能的附加图像。

我希望计数器仅在用户滚动该特定按钮时增加,而不是在他在屏幕上的其他位置滑动时增加

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用SeekBar来增加或减少计数器。您可以使用的简单布局示例如下:

<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:orientation="vertical" >

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/counter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="0" >
    </TextView>

</LinearLayout>

代码就是这样:

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 TextView counter;

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

        // Selects the TextView which holds the value of the counter
        this.counter = (TextView) findViewById(R.id.counter);

        SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
        // Sets the initial value of the SeekBar (it must be the same initial
        // value of the counter)
        seekBar.setProgress(0);
        // Sets the max value of the counter
        seekBar.setMax(100);
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
            boolean fromUser) {
            // This code runs when you scroll the SeekBar to left or right.
            // If you scroll to the left, the counter decreases and if you
            // scroll to the right, the counter increases
            counter.setText(String.valueOf(progress));
        }
    });
}

}