Is there such a method call \"getBackgroundColor\" in TextView? if I got 2 textViews: tv1 and tv2 in one LinearLayout. What I did:tv1.setBackgroundColor(Color.BLUE)
It works for me.
public static int getColor(View v) {
if(Build.VERSION.SDK_INT>=11)
{
return ((ColorDrawable)v.getBackground()).getColor();
}
else
{
try
{
Field f=View.class.getDeclaredField("mState");
f.setAccessible(true);
Object mState=f.get(v);
Field f2=mState.getClass().getDeclaredField("mUseColor");
f2.setAccessible(true);
return (int) f2.get(mState);
}
catch (Exception e)
{
}
}
return 0;
}
Here is an additional option:
The way I solved this problem for my app was to define the colors in values/color.xml.
<resources>
<color name="blue">#ff0099cc</color>
<color name="dark_grey">#ff1d1d1d</color>
<color name="white">#ffffffff</color>
...
<color name="textview_background">@color/white</color>
</resources>
In the layout the TextView
has:
android:background="@color/textview_background"
If I want to get the background color in code I can just use:
getResources().getColor(R.color.textview_background)
This gives me a Color
object directly without worrying about getting the color from a Drawable
.
There is a better solution than bourbons:
((ColorDrawable)view.getBackground()).getColor();
The advantage is we get an integer which is comparable to color enums given by Color class.
Setting a background color sets a Drawable with that specified color as the background, i.e. the following example will work just fine:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_layout_name);
TextView t1 = (TextView) findViewById(R.id.text1);
TextView t2 = (TextView) findViewById(R.id.text2);
t1.setBackgroundColor(Color.GREEN);
t2.setBackgroundDrawable(t1.getBackground());
}
You will find the solution here : http://groups.google.com/group/android-developers/browse_thread/thread/4910bae94510ef77/59d4bb35e811e396?pli=1
It will be something like that :
((PaintDrawable) tv.getBackground()).getPaint()
There is no such method, because in common there is now "background color" - there can be any Drawable
object(for example picture). So, you should remember what color do you set for text.
If you can't save it - use View.setTag()
and View.getTag()
methods to store any value, associated with view.