How to create counter on button?

后端 未结 3 1066
你的背包
你的背包 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);
    }
    
    0 讨论(0)
  • 2021-01-28 16:24
    private static int counter = 0;
    
    button1.setOnClickListener(new OnClickListener(){
        @Override
        onClick(View v){
           counter += 1
           button.setText("Some text" + counter);
        }
     });
    
    0 讨论(0)
  • 2021-01-28 16:44

    Try this way,hope this will help you to solve your problem.

    main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">
        <Button
            android:id="@+id/btnCounter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Some Text"/>
    </LinearLayout>
    

    strings.xml

    <string name="button_text">Some Text  %1d</string>
    

    MyActivity.java

    public class MyActivity extends Activity{
    
        private Button btnCounter;
        private int count;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            btnCounter = (Button) findViewById(R.id.btnCounter);
    
            btnCounter.setText(String.format(getString(R.string.button_text),count));
    
            btnCounter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    count++;
                    btnCounter.setText(String.format(getString(R.string.button_text),count));
                }
            });
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题