gaurav tiwari gaurav tiwari - 2 months ago 8
Android Question

Select and Unselect buttons

I have a list of text views in which some goal is defined. User can select maximum 3 goals. He can also unselect his selected goal and select another. Currently what I have done is user can select only 3 goals but if user unselect any goal and try to select another goal its not happening.

Here is my code:

public void onClick(View v) {


switch (v.getId()) {
case R.id.goalText1:
if (count <= 2 && isSelected) {
goals.add(mGoal1.getText().toString());
mGoal1.setTextColor(getResources().getColor(R.color.black));
count++;
isSelected=false;
mGoal1.setSelected(true);

} else {
isSelected = true;
goals.remove(mGoal1.getText().toString());
mGoal1.setTextColor(getResources().getColor(R.color.white));
mGoal1.setSelected(false);

}
break;

case R.id.goalText2:

if (count <= 2 && isSelected) {
goals.add(mGoal2.getText().toString());
mGoal2.setTextColor(getResources().getColor(R.color.black));
count++;
mGoal2.setSelected(true);
isSelected=false;
} else {
isSelected = true;
goals.remove(mGoal1.getText().toString());
mGoal2.setTextColor(getResources().getColor(R.color.white));
mGoal2.setSelected(false);
Toast.makeText(getApplicationContext(), "select upto 3 fitness goals only " , Toast.LENGTH_LONG).show();

}
break;

case R.id.goalText3:

if (count <= 2 && isSelected) {
goals.add(mGoal3.getText().toString());
mGoal3.setTextColor(getResources().getColor(R.color.black));
count++;
mGoal3.setSelected(true);
isSelected=false;
} else {
isSelected = true;
goals.remove(mGoal1.getText().toString());
mGoal3.setTextColor(getResources().getColor(R.color.white));
mGoal3.setSelected(false);
Toast.makeText(getApplicationContext(), "select upto 3 fitness goals only " , Toast.LENGTH_LONG).show();

}
break;

case R.id.goalText4:

if (count <= 2 && isSelected) {
goals.add(mGoal4.getText().toString());
mGoal4.setTextColor(getResources().getColor(R.color.black));
count++;
mGoal4.setSelected(true);
isSelected=false;
} else {
isSelected = true;
goals.remove(mGoal1.getText().toString());
mGoal4.setTextColor(getResources().getColor(R.color.white));
mGoal4.setSelected(false);
Toast.makeText(getApplicationContext(), "select upto 3 fitness goals only " , Toast.LENGTH_LONG).show();

}
break;

Answer

First apply this logic for first goal and check if it is working or not then you can apply for all goal with little modifications like change id and all,

    case R.id.goalText1:
            if (goals.size <= 2 && ! mGoal1.isSelected()) 
            {
                goals.add(mGoal1.getText().toString());
                mGoal1.setTextColor(getResources().getColor(R.color.black));
                mGoal1.setSelected(true);

            } else {
                goals.remove(mGoal1.getText().toString());
                mGoal1.setTextColor(getResources().getColor(R.color.white));
                mGoal1.setSelected(false);

            }
            break;