0

当我单击添加按钮时,它从 0 开始计算数字并一个接一个地显示,但是当我单击删除按钮时,它会清除编辑文本,但是当开始再次单击添加按钮时,它会从最后一个数字开始计数,所以我想要什么时候我每次从(0)开始计数时都单击它。

final Button add = (Button) findViewById(R.id.button1);
    final Button delet = (Button) findViewById(R.id.button2);
    final EditText edit = (EditText) findViewById(R.id.editText1);

    add.setOnClickListener(new View.OnClickListener() {

        private int number = 1;


        public void onClick(View v) {
            // TODO Auto-generated method stub
            // random = random();
            edit.setText("" + number++); // i want when i click on it in every single time it beginning to count from( 0 )
                               //because when i delete it and start to click again on add button it count from the last number that stop on it 


        }
    });
    delet.setOnClickListener(new View.OnClickListener() {

        private int numberr;

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            edit.setText("0");  // should i change this clean code to make it count from the beginning in every single click ?
        }
    });
}
4

1 回答 1

0

您必须使数字变量成为全局变量才能使代码正常工作。

只要您单击按钮,它将始终初始化为 1。

    add.setOnClickListener(new View.OnClickListener() {


          // make it global or store in intent to retain its value after incrementing and intialize it globally and not here else again will be same case.
//            number = 1;


            public void onClick(View v) {
                // TODO Auto-generated method stub
                // random = random();
                edit.setText("" + number++); // i want when i click on it in every single time it beginning to count from( 0 )
                                   //because when i delete it and start to click again on add button it count from the last number that stop on it 


            }
        });
于 2013-10-19T14:10:34.683 回答