How to increment a Counter inside an OnClick View Event

后端 未结 3 822
心在旅途
心在旅途 2020-12-18 10:11

I know this might sound very basic but here\'s my problem:

I have an onclickevent listener that\'s supposed to increment the counter indefinitely when it\'s clicked:

相关标签:
3条回答
  • 2020-12-18 10:32
        t.setOnClickListener(new View.OnClickListener() {
            int Counter = 0;
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), R.string.hey, Toast.LENGTH_SHORT).show();
                t.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                c.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                p.setVisibility(View.VISIBLE);
                if (Counter >= 0) {
                    Counter++;
                    e.setText("you clicked Click me "+Counter +"number of times");
                    e.setTextSize(15);
                    e.setTextColor(getResources().getColor(R.color.colorPrimary));
                    e.setSingleLine();
                }
    
    0 讨论(0)
  • 2020-12-18 10:37

    You could declare 'counter' outside the Activity's oncreate method.

    0 讨论(0)
  • 2020-12-18 10:46

    Solved:

    myimageView2.setOnClickListener(new OnClickListener() {
        int counter = 0;
        public void onClick(View v) {
            counter ++;
        }
    });
    
    0 讨论(0)
提交回复
热议问题