Programmatically setting TextView background - java

I've defined a background for my TextView:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape= "rectangle" >
<solid android:color="#000"/>
<stroke android:width="1dp" android:color="#ff9"/>
</shape>
Now I'm trying to set it to my TextView programmatically:
textview.setBackground((Drawable)findViewById(R.drawable.cellborder));
This isn't working though, it's telling me it can't cast a View as a Drawable. Is there another way to do this?

If you want backwards compatibility then use the following:
textView.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.cellborder));
Replace MainActivity.this with the name of the activity from where are you calling these methods.
If you call textView.setBackground(...) from Pijamas activity then do the following:
textView.setBackground(ContextCompat.getDrawable(Pijamas.this, R.drawable.cellborder));

You have to use
getResources().getDrawable(R.drawable.cellborder);
which will return a Drawable.
If you use findViewById() it will try to find a View in the View Hierarchy and return that. A View is not a Drawable, so you can't cast it.

try to set drawable like this
textview.setBackgroundDrawable( getResources().getDrawable(R.drawable.cellborder) );
visit for more help.
set background drawable programmatically in Android

Related

Dynamically change drawable colors

In my application I have a lot of drawables defined with xml files. For example I have a button defined like that:
button.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Bottom 3dp Shadow -->
<item android:top="3dp">
<shape android:shape="rectangle">
<corners android:radius="3dp" />
<solid android:color="#color/black_30" />
</shape>
</item>
<!-- green top color -->
<item android:top="3dp" android:bottom="3dp" android:id="#+id/background">
<shape android:shape="rectangle">
<corners android:radius="3dp" />
<solid android:color="#color/green1" />
</shape>
</item>
</layer-list>
and then I display a button like that:
layout.xml
<Button
android:id="#+id/button"
android:layout_gravity="center"
android:layout_height="60dp"
android:layout_width="fill_parent"
android:textSize="17sp"
android:gravity="center"
android:background="#drawable/button" />
When I navigate in the app, I want to "theme" some views (some colors are changing in function of the context) and to do that I would like to be able to change dynamically the color of the button (green1) at runtime.
1) One first nice approach would be to change the color definition in button.xml with an ?attr/my_color. And then define the different color values I need in the theme file style.xml. Then at runtime, I can switch to the desired theme and that will work. The complete steps are here:
How to reference colour attribute in drawable?
The issue is that it works on Android 5 but not on Android 4 ( and I need to support this version) (we get an android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>)
2) The second approach is to load the drawable in the code and then use setColorto change the color of the drawable: (written in Xamarin.Android but I am sure that you will understand the corresponding Java version)
LayerDrawable button = (LayerDrawable)Resources.GetDrawable(Resource.Drawable.normal_question_button);
GradientDrawable background = (GradientDrawable)button.FindDrawableByLayerId(Resource.Id.background);
background.SetColor(Android.Graphics.Color.Red.ToArgb());
The good things is that it's works... but randomly... Sometimes when I am displaying the button again, it's still the original green that is displayed. Sometimes, it's the new color... And once I have one of the both behaviour, the same color can stay many time and suddenly it changes again to the correct one.
Someone could explain this? Is there some caching on drawables that can gives that kind of issue?
3) I was thinking about a third solution: dynamically change the color defined in colors.xml (where green1 is defined) but it doesn't seem possible
In fact for 2) one really simple solution is:
instead of trying to customize the drawable coming from the xml file:
LayerDrawable button = (LayerDrawable)Resources.GetDrawable(Resource.Drawable.normal_question_button);
GradientDrawable background = (GradientDrawable)button.FindDrawableByLayerId(Resource.Id.background);
background.SetColor(Android.Graphics.Color.Red.ToArgb());
We can change directly the color on each button once we have an instance for them:
LayerDrawable buttonDrawable = _button.Background;
GradientDrawable background = (GradientDrawable)buttonDrawable.FindDrawableByLayerId(Resource.Id.background);
background.SetColor(Android.Graphics.Color.Red.ToArgb());

Simple gradient in Android

I'm kinda new to Android, and I'm looking to create a really simple gradient of 2 colors, from top to bottom, display it on the view, and maybe save it as an image. I really didn't find an answer that suits my needs, I'm really looking for the simplest and most straight-forward way.
Thanks!
I think the easiest way is to create a simple Shape template in XML, and then use it in any view you want, like this:
shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:type= "linear"
android:startColor="#474946"
android:endColor="#181818"
android:angle="270"/>
</shape>
then in your view tag just add:
android:background="#drawable/shape"
I will answer in two parts creating gradient and the displaying it.
To create gradient Create a new xml file in your drawable folder and name it whatever you want. In this case i will call it myGradient.xml.
Open myGradient.xml file and paste the code below which will help create two color gradient. You can change the values of color to what you need.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:bottom="6px" android:right="4dp">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#d7009482"
android:endColor="#ad1c4e9b"
android:centerX="100%"
android:centerY="150%"
android:type="linear"
android:angle="135"/>
</shape>
</item>
</layer-list>
This will give you output below.
Gradient with two colors
The second part will be to display this gradient in view.
Open your view and set background to be the gradient.
android:background="#drawable/myGradient
Hope that will help you

Change ListView item background to gradient

I am able to setup a listview using custom adapter which shows correct output..Now i want to change the background of each listview items to a gradient.. how it could be done?
My files...
activity_main.xml....Main xml file
MainActivity.java....Main activity
Item.java.... item selector method
ItemAdaptor.... custom adapter
list_item.xml..... item (textView) styling
I have created my gradient code which is like..
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#FFFAFAFA"
android:centerColor="#FFFFFFFF"
android:endColor="#FFFAFAFA"
android:angle="90"/>
</shape>
also how could I change the separator color,and the background color of the whole listview..
Have you mentioned android:background="#drawable/customshape" in your rowLayout.xml so that it knows which shape is to be used? Also use android:divider="#FFCC00" in your listview tag to change the seperator color. Add <solid android:color="#F0F0F0" /> to your shape so as to change the background color.
Have a look on this tutorial
author created list-view with gradient effect, I think this is exactly what you need.

Highlight selected items in ListFragment (MultiChoiceModeListener)?

I want to be able to see what items that have been selected in my list. Before turning ListView into ListFragment, the selected items had a blue background color (Holo Dark), but now I can only see the blue color while pressing the items - then it disappears. I do not have a problem with the items getting "checked", because they are. You just can't see it.
Here's what I do in onActivityCreated():
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setItemsCanFocus(false);
getListView().setMultiChoiceModeListener(new LongPress());
LongPress() is a private class implementing ListView.MultiChoiceModeListener. It opens up a contextual action bar when holding finger on an item. The user can then select more items, and this is where the problem occurs. You can not see which items are checked or not (I want them to be highlighted). Why did it work before extending ListFragment? I tried to create a custom selector in my .xml-files, that didn't seem to work either. I would prefer using the custom one, if there's any.
Here's another method in my ListFragment class:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_listview, container, false);
}
fragment_listview.xml isn't doing anything special apart from changing the background color and the color of the divider.
What should I do?
I tried this, but it didn't work:
In my list_item.xml:
android:background="#drawable/selector"
selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="#drawable/item_checked" />
</selector>
item_checked.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http//schemas.android.com/apk/res/android" >
<solid android:color="#000000" />
</shape>
I was having the exact same issue.
I found a solution in this post: Highlight custom listview item when long click
The trick:
Set in the layout file of your list's row (in the top level component, usually a LinearLayout or RelativeLayout):
android:background="?android:attr/activatedBackgroundIndicator"
I cannot find the details right now, but you have to provide a statelist drawable for the listview-items that provides a separate drawable for the checked state.

How to set background color of an Activity to white programmatically?

How can I set the background color of an Activity to white programatically?
Add this single line in your activity, after setContentView() call
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
Get a handle to the root layout used, then set the background color on that. The root layout is whatever you called setContentView with.
setContentView(R.layout.main);
// Now get a handle to any View contained
// within the main layout you are using
View someView = findViewById(R.id.randomViewInMainLayout);
// Find the root view
View root = someView.getRootView();
// Set the color
root.setBackgroundColor(getResources().getColor(android.R.color.red));
I prefer coloring by theme
<style name="CustomTheme" parent="android:Theme.Light">
<item name="android:windowBackground">#color/custom_theme_color</item>
<item name="android:colorBackground">#color/custom_theme_color</item>
</style>
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:id="#+id/myScreen"
</LinearLayout>
In other words, "android:background" is the tag in the XML you want to change.
If you need to dynamically update the background value, see the following:
Exercise: Change background color, by SeekBar
In your onCreate() method:
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.main_activity_background_color));
Also you need to add to values folder a new XML file called color.xml and Assign there a new color property:
color.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="main_activity_background_color">#000000</color>
</resources>
Note that you can name the color.xml any name you want but you refer to it by code as R.color.yourId.
EDIT
Because getResources().getColor() is deprecated, use getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.main_activity_background_color));
instead.
You can use this to call predefined android colours:
element.setBackgroundColor(android.R.color.red);
If you want to use one of your own custom colours, you can add your custom colour to strings.xml and then use the below to call it.
element.setBackgroundColor(R.color.mycolour);
However if you want to set the colour in your layout.xml you can modify and add the below to any element that accepts it.
android:background="#FFFFFF"
Button btn;
View root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
root =findViewById(R.id.activity_main).getRootView();
root.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
});
}
To get the root view defined in your xml file, without action bar, you can use this:
View root = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
So, to change color to white:
root.setBackgroundResource(Color.WHITE);
View randview = new View(getBaseContext());
randview = (View)findViewById(R.id.container);
randview.setBackgroundColor(Color.BLUE);
worked for me. thank you.
final View rootView = findViewById(android.R.id.content);
rootView.setBackgroundResource(...);
for activity
findViewById(android.R.id.content).setBackgroundColor(color)
The best method right now is of course
getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.main_activity_background_color));
Please be aware though, if you have anything set as the background color in Designer, it will overwrite anything you try to set in your code.

Categories

Resources