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);
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.
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: https://developer.android.com/reference/android/widget/LinearLayout.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.