1

I simply need to change(toggle) the background colour of a textview upon each touch.

So when a user first touches the textview, it turns blue. Upon the next touch it turns back to the default theme color for the textview. I have not specified any colours at all in any of the XML files so far.

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list_item_name"
        android:onClick="ToggleListItemSelectedState"/>

In the click handler for the textbox:

TextView selectedTextView = (TextView)view;
defaultBackground=//?How to save the default background

From this stackoverflow answer, I tried defaultBackground=selectedTextView.getBackground(); int colorCode = defaultBackground.getColor();

but the getColor() isn't recognized.

I need to

  • Either get the default textview background colour from the theme

    OR

  • Save the background colour the first time the textview is touched and then subsequently reset the background using the saved colour.

Thank you

Community
  • 1
  • 1
iAteABug_And_iLiked_it
  • 3,725
  • 9
  • 36
  • 75

2 Answers2

0

Try

  mBackgroundColor = ((ColorDrawable) view.getBackground()).getColor();

  view.setBackgroundColor(mBackgroundColor);
Daniil
  • 1,290
  • 11
  • 17
0

You can retrieve the current background of the view using View#getBackground(). If you don't set any background, it returns null.

The background of the view can be set by View#setBackground(Drawable) or ViewCompat#setBackground(View, Drawable) if you target APIs below 16.

Therefore probably you want to store the original background and the desired background:

mOriginalBackground = textView.getBackground();
mOtherBackground = new ColorDrawable(otherColor);

And now toggle between them:

if (showOriginalBackground) {
    ViewCompat.setBackground(textView, mOriginalBackground);
} else {
    ViewCompat.setBackground(textView, mOtherBackground);
}

showOriginalBackground = !showOriginalBackground;

One of the answers to this question suggested using View#setBackgroundColor(int). Please note, that this will (on API 15 and above) mutate the original background if it is already a ColorDrawable. Therefore:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/red" />

mOriginalBackground = textView.getBackground(); // red
textView.setBackgroundColor(blue); // mOriginalBackground is now blue!
ViewCompat.setBackground(textView, mOriginalBackground); // user still sees blue!
Marcin Jedynak
  • 3,697
  • 2
  • 20
  • 19
  • ViewCompat.setBackground didn't quite work, I still was seeing the changed color. However, your answer did lead me to just setting the background to null ,i.e. selectedTextView.setBackground(null); and that worked. thank you – iAteABug_And_iLiked_it Mar 19 '17 at 13:59