0

I'm a newbie to the android development. I have two approaches to change the layout background color via Java. Which one could be more appropriate and why?

The first approach is:

LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.translation_container);
layout.setBackgroundColor(mColor);

and the second one:

View view = convertView.findViewById(R.id.translation_container);
int color = ContextCompat.getColor(getContext(),mColor);
view.setBackgroundColor(color);
Dave Thomas
  • 3,667
  • 2
  • 33
  • 41
Misanty
  • 86
  • 10
  • `translation_container` is a LinearLayout which is located into another LinearLayout. Since it's LinearLayout, why should I assign it into `View`? – Misanty Nov 09 '17 at 16:32

2 Answers2

1

Well for one there is something very wrong between the two, and that is the fact that you are calling ContextCompat.getColor(getContext(), mColor) with one and directly setBackgroundColor(mColor) on the other.

ContextCompat.getColor is supposed to be called with a color resource ID, ie. a R.color.value. It returns the color value from your resources that corresponds to that resource ID.

Depending on what you have in the value of ```mColor''', there is a good chance that one of these options is not setting the correct color you are expecting.

If mColor is a color resource ID, then the second one is correct. If mColor is the color you want to set, then the first is correct.

When it comes to the cast you are doing into a LinearLayout it is unnecessary. Both options call the same method View.setBackgroundColor. You can go with View for now as the type of your view variable.

Dave Thomas
  • 3,667
  • 2
  • 33
  • 41
  • Sorry, I didn't specify about it, `mColor` gets its value from resource. Why should one of them get its value from resource whereas other shouldn't? – Misanty Nov 09 '17 at 17:03
  • Then your second option, which calls ContextCompat.getColor, is the one you want to use. Your first one is setting the background color to the value of the resource ID, you def do not want that. – Dave Thomas Nov 09 '17 at 17:10
0

LinearLayout extends ViewGroup which extends View. So LinearLayout also a View. So there is no difference between View.setBackgroundColor() and LinearLayout.setBackgroundColor(). LinearLayout did not override this method.

See View.setBackgroundColor()

See: https://developer.android.com/reference/android/widget/LinearLayout.html

nhoxbypass
  • 9,695
  • 11
  • 48
  • 71
  • Alternate universe; even if LinearLayout overrides setBackgroundColor, a LinearLayout cast as a View will call the overridden method. Basis of polymorphism -> https://stackoverflow.com/questions/22874640/overriding-methods-in-java-and-then-casting-object-to-parent-class-behavior – Dave Thomas Nov 09 '17 at 17:08