How to create counter on button?

后端 未结 3 1067
你的背包
你的背包 2021-01-28 15:44

I want to create button with text = \"SomeText\" on center of this button and \"0\" on right part of button. Where \"0\" is the Counter and when I click this button Counter++ i

3条回答
  •  鱼传尺愫
    2021-01-28 16:23

    There are several options.

    Create a static variable:

    private static int buttonClickCount = 0;
    
    public void but1_Count(View v){
        buttonClickCount++;
        v.settext("Clicked " + buttonClickCount);
    }
    

    Create custom button by extending base button class and implement onClickListener:

    public class MyButton extends Button implements View.OnClickListener {
        private int counter = 0;
        public MyButton(...){
            this.setOnClickListener(this);
        }
        public void onClick(View v) {
            counter++;
            v.setText("Clicked"+counter);
        }
    }
    

    Extract value from clicked button, parse it as int, and increment:

    public void but1_count(View v){
        int curr = Integer.parseInt(v.getText().toString());
        v.setText(""+curr);
    }
    

提交回复
热议问题