计算器从数字开始

时间:2014-04-23 16:27:08

标签: java android

我正在尝试这样做,当应用程序打开时,它将从一个数字开始并减去/添加1到该数字,如20。所以,当他们点击+1时,它将转到21而不是从0开始。寻求帮助。

    int counter;
Button add , sub; 
TextView D1;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);
    counter = 0;
    add = (Button) findViewById(R.id.btn1);
    sub = (Button) findViewById(R.id.btn2);
    D1 = (TextView) findViewById(R.id.txt1);

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Adds 1 to the counter
            counter = counter + 1;
            D1.setText(" " + counter);

        }
    });

    sub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Subtract 1 from counter
            counter = counter - 1;
            D1.setText(" " + counter);

        }
    });
}
}

1 个答案:

答案 0 :(得分:4)

只需使用您选择的值初始化计数器。 例如,如果您希望它为20,请执行

counter = 20;

或者如果您希望它是随机数,您可以使用Random类。

Random generator = new Random();
counter = generator.nextInt(); //If you want it to be any random integer value
counter = generator.nextInt(50); //If you want any random integer value from (inclusively 0,  exclusively 50)

所以看起来像这样:

int counter;
Button add, sub; 
Random generator;
TextView D1;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);
    generator = new Random();
    counter = generator.nextInt(50);

    add = (Button) findViewById(R.id.btn1);
    sub = (Button) findViewById(R.id.btn2);
    D1 = (TextView) findViewById(R.id.txt1);

    D1.setText(" " + counter);

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Adds 1 to the counter
            counter = counter + 1;
            D1.setText(" " + counter);

        }
    });

    sub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Subtract 1 from counter
            counter = counter - 1;
            D1.setText(" " + counter);

        }
    });
}
}