1

I am new to android. I got stuck while doing an application.I have taken 5 textviews with time slots,I would like to show that when I click one text view it should change its background color and when I click another textview the first text view's background color has to disappear and present text view's color has to be highlight.

Image Here

Here I am posting my code:

public void onClick(View v) {
    switch (v.getId()){
        case R.id.time_slot_one:
            setTimeSlotOne.setBackgroundColor(Color.parseColor("#bdbdbd"));
        break;

        case R.id.time_slot_two:
            setTimeSlotTwo.setBackgroundColor(Color.parseColor("#bdbdbd"));
            break;
        case R.id.time_slot_three:
            setTimeSlotThree.setBackgroundColor(Color.parseColor("#bdbdbd"));
            break;
        case R.id.time_slot_four:
            setTimeSlotFour.setBackgroundColor(Color.parseColor("#bdbdbd"));
            break;
        case R.id.time_slot_five:
            setTimeSlotFive.setBackgroundColor(Color.parseColor("#bdbdbd"));
            break;
    }
DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44

4 Answers4

2

A simple way would be to create a disable Background function that will be called each time you click a new one.

public void removeBackgroundColors() {
    setTimeSlotOne.setBackgroundColor(Color.WHITE);
    setTimeSlotTwo.setBackgroundColor(Color.WHITE);
    setTimeSlotThree.setBackgroundColor(Color.WHITE);
    setTimeSlotFour.setBackgroundColor(Color.WHITE);
    setTimeSlotFive.setBackgroundColor(Color.WHITE);
}

now simply change your code to:

case R.id.time_slot_two:  
    removeBackgroundColors();
    setTimeSlotTwo.setBackgroundColor(Color.parseColor("#bdbdbd"));
    break;
...

Even simpler is to call it before your case statement, depending on what actions you want to take.

0

Use if else to setBackground color, for example ; if onclick of firsttextview set its color and on click of second change firsttextview color and set seconds color

rahul sharma
  • 149
  • 1
  • 2
  • 11
0

You have to change the color of all Textviews. Example t1 is selectable change t1's color as selected and other textviews as unselected,so on for rest of the textviews

Richa
  • 3,165
  • 1
  • 22
  • 26
0

It would be better if you use radio group which handles all clicks and selection and highlighting if you have many textviews.

Please check below url. Url

In that link use answer by Sanjeet Ajnabee. It is excellent. I have been using it.

Community
  • 1
  • 1
Prashanth Debbadwar
  • 1,047
  • 18
  • 33