Search code examples
androidclicklogicimagebutton

Please help create code to calculate the percent of clicks on the button


I am a novice developer. Please help to create the code to count clicks on the buttons (on Android). I have three ImageButton (IB1, IB2, IB3) and I have 3 empty TextView (TV1,TV2, TV3). However, the counter should not be considered the number of clicks each of the three buttons. Counter should be considered the percentage of clicks each button to the total number of clicks on all three buttons in this session. Here is the beginning of my code. Thanks in advance to all.

public class ring_fight extends Activity implements View.OnClickListener {  



    ImageButton IB1, IB2, IB3;
    TextView TV1, TV2, TV3;

    // I declare counters
        int Count_for_IB1 = 0; //counter for ImageButton1 
        int Count_for_IB2 = 0; //counter for ImageButton2
        int Count_for_IB3 = 0;//counter for ImageButton3


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        IB1 = (ImageButton) findViewById(R.id.IB_first);
        IB2 = (ImageButton) findViewById(R.id.IB_second);
        IB3 = (ImageButton) findViewById(R.id.IB_third);

        TV1 = (TextView)findViewById(R.id.TextView1);
        TV2 = (TextView)findViewById(R.id.TextView2);
        TV3 = (TextView)findViewById(R.id.TextView3);


        IB1.setOnClickListener(this);
        IB2.setOnClickListener(this);
        IB3.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.IB1:
                TV1.setText("");
                break;
            case R.id.IB2:
                TV1.setText("");
                break;
            case R.id.IB3:
                TV1.setText("");
                break;
        }
    }
}

Solution

  • float count1=0, count2=0, count3=0, total=0;
    public void onClick(View v) {
        switch (v.getId()) {
              case R.id.IB1:
                   count1++;
              break;
              case R.id.IB2:
                   count2++;
              break;
              case R.id.IB3:
                   count3++;
              break;
       }
       total=count1+count2+count3;
       TV1.setText(String.valueOf(((count1/total)/100)));
       TV2.setText(String.valueOf(((count2/total)/100)));
       TV3.setText(String.valueOf(((count3/total)/100)));
    }