How to Get Android TableRow background color? - android

I've created a spreadsheet in Android to display the results of a data search using TableRow. The TableRows are dynamically created so there can be up to 30 rows displayed at a time.
I'm trying to toggle the background color of a row when the user touches the row, and can easily change the background color with an android:onClick event. However once the row is clicked and the color changes I cannot toggle the color back when another android:onClick event is initiated.
So how do I determine the color state of the TableRow so I can construct the proper control flow and toggle the color appropriately? There are plenty of examples of how to set the background color, but nothing helpful in GETTING the background color.
Thanks

Try this:
// save old view style
Drawable defaultViewStyle = view.getBackground();
// set new style
view.setBackgroundResource(R.drawable.new_view_style);
// return default view style
view.setBackgroundDrawable(defaultViewStyle);
But I think it's not the right way. It is best to override all of the possible conditions for the view:
// res drawable my_table_row_style:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true" android:drawable="#drawable/my_table_row_style_selected"/>
<item android:state_focused="false" android:state_pressed="true" android:drawable="#drawable/my_table_row_style_selected"/>
<item android:state_focused="true" android:state_pressed="false" android:drawable="#drawable/my_table_row_style_selected"/>
<item android:state_focused="false" android:state_pressed="false" android:drawable="#drawable/my_table_row_style_default"/>
</selector>

Example:
int MyPosition=100000;
...
...
onclick()
{
if(MyPosition==100000)
{
//first time selection
MyPosition=a//a=any int position
//change bg of selected row
}
else
{
//now u r selecting second or N th time
//so first set previous bg of MyPosition
//and clear MyPosition
//Now set bg of current bg nd set MyPosition
}
}

You can save the color you set by setTag() and retrive it by getTag().
void OnClick(View v)
{
Integer color = v.getTag();
if (null == color) // not clicked yet
{
color = COLOR_NOT_TOGLED;
}
if (COLOR_NOT_TOGLED == color)
{
color = COLOR_TOGLED;
}
else
{
color = COLOR_NOT_TOGLED;
}
v.setBackGround(color);
v.setTag(color); // save
}
UPDATE
Ok, let's fix it))
void OnClick(View v)
{
Object o = v.getTag();
Integer color = (null == o) ? COLOR_NOT_TOGLED : (Integer) o;
if (COLOR_NOT_TOGLED == color) {
color = COLOR_TOGLED;
} else {
color = COLOR_NOT_TOGLED;
}
v.setBackgroundColor(color);
v.setTag(color); // save
}

If you take a look in source code of setBackgroundColor() you see how it works:
TableRow tr = (TableRow)v;
Drawable bg = tr.getBackground();
int oldColor = ((ColorDrawable) bg.mutate()).getColor();

Related

How to set up animated drawable with recyclerview?

Hello all I successfully set up a recycler view an implemented a thumb up function. I also set up a animation for the drawable. When a user gives something a thumb up an animation is displayed and the drawable is filled. I also set up a reverse animation to unfill the drawable. When I fetch data for the recyclerview I´m working with states. If the state is 0 the drawable is unfilled if its 1 its filled.
My drawable is a drawable state list. My issue is when the data is loaded it shows the animation so I tried it with replacing the drawable state list with only a filled or unfilled drawable on start and when the user gets an item a thumb up I replace it with the drawable state list and set a state for that. The problem with that sometimes it didn´t animate the drawable.
I have the same issue in a detail fragment of the recycler items sometimes it changes spontaneously the state of the drawable. What would be the best solution for a drawable with different states in recycler view.
Would be thankful for any answers.
The drawable state list:
<!-- provide a different drawable for each state-->
<item
android:id="#+id/state_off"
android:drawable="#drawable/ic_herzspaceliked"
android:state_activated="false"
/>
<item
android:id="#+id/state_on"
android:drawable="#drawable/heartfill"
android:state_activated="true"
/>
<transition
android:drawable="#drawable/heartfill"
android:fromId="#id/state_off"
android:toId="#id/state_on"
android:reversible="true"
/>
<!-- specify transitions -->
How I set the drawable state in recylcerview:
((Eventholder)holder).likestate = Objects.requireNonNull(getItem(position)).getUserLikedState();
if (((Eventholder)holder).likestate== 0) {
//((Eventholder)holder).eventCardviewBinding.likebutton.getBackground().setState(new int[]{-android.R.attr.state_activated});
((Eventholder)holder).eventCardviewBinding.likebutton.setBackgroundResource(R.drawable.ic_herzspaceliked);
} else if (((Eventholder)holder).likestate==1) {
((Eventholder)holder).eventCardviewBinding.likebutton.setBackgroundResource(R.drawable.ic_herzliked);
//((Eventholder) holder).eventCardviewBinding.likebutton.getBackground().setState(new int[]{android.R.attr.state_activated});
}
((Eventholder)holder).eventCardviewBinding.likebutton.setOnClickListener(v -> {
if (((Eventholder)holder).likestate==0) {
((Eventholder)holder).likestate=1;
((Eventholder)holder).eventCardviewBinding.likebutton.setBackgroundResource(R.drawable.heartanimation);
((Eventholder)holder).eventCardviewBinding.likebutton.setActivated(true);
((Eventholder) holder).eventCardviewBinding.LikeCount.setText(String.valueOf(Integer.parseInt(((Eventholder) holder).eventCardviewBinding.LikeCount.getText().toString()) + 1));
}
else if (((Eventholder)holder).likestate==1) {
((Eventholder)holder).likestate=0;
((Eventholder)holder).eventCardviewBinding.likebutton.setBackgroundResource(R.drawable.heartanimation);
((Eventholder)holder).eventCardviewBinding.likebutton.setActivated(false);
((Eventholder) holder).eventCardviewBinding.LikeCount.setText(String.valueOf(Integer.parseInt(((Eventholder) holder).eventCardviewBinding.LikeCount.getText().toString()) -1 ));
}
itemClickHandler.likestate(getItem(position));
});
How I set up the drawable state list in details fragment:
public void ButtonUI()
{
//LikeButton
binding.likeButtonholder.setOnClickListener(v -> {
if (likestate==0)
likestate=1;
else
likestate=0;
mainViewModel.init(firebaseAuth.getUid(),Events.getId(),Events.getEventName(),Events.getArt(),Events.getGENRE());
mainViewModel.getLikeStateLiveData().observe(getViewLifecycleOwner(), state -> {
if (state==1){
Events.setUserLikedState(1);
binding.likeButtonholder.setSelected(true);
binding.likecounter.setText(String.valueOf((Events.getLikes()) + 1));
Events.setLikes(Events.getLikes() + 1);
}
else if (state==0){
//binding.likeButtonholder.setBackgroundResource(R.drawable.white_heartanimation);
binding.likeButtonholder.setSelected(false);
binding.likecounter.setText(String.valueOf((Events.getLikes()) - 1));
Events.setUserLikedState(0);
Events.setLikes(Events.getLikes() - 1);
}
else
Toast.makeText(getContext(),"Error",Toast.LENGTH_LONG).show();
});
});
}
public void Observe()
{
//AccountData
//EventDetailsData
viewModel.getEvents().observe(getViewLifecycleOwner(), events -> {
Events=events;
likestate=events.getUserLikedState();
if (likestate==0) {
binding.likeButtonholder.getBackground().setState(new int[]{-android.R.attr.state_selected});
}
else
binding.likeButtonholder.getBackground().setState(new int[]{android.R.attr.state_selected});
)};
}
I solved my problem by adding an animated drawable also as state_off drawable!
<animated-selector
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- provide a different drawable for each state-->
<item
android:id="#+id/state_on"
android:drawable="#drawable/heartfill"
android:state_selected="true"
/>
<item
android:id="#+id/state_off"
android:drawable="#drawable/heart_unfill"
/>
<transition
android:drawable="#drawable/heartfill"
android:fromId="#id/state_off"
android:toId="#id/state_on"
/>
<transition
android:drawable="#drawable/heart_unfill"
android:fromId="#id/state_on"
android:toId="#id/state_off"
/>
<!-- specify transitions -->
Thats the right way.
Also changed my code as Pawel told me:
((Eventholder)holder).likestate=Objects.requireNonNull(getItem(position)).getUserLikedState();
((Eventholder)holder).eventCardviewBinding.likebutton.setSelected((((Eventholder)holder).likestate==1));
((Eventholder)holder).eventCardviewBinding.likebutton.jumpDrawablesToCurrentState();
((Eventholder)holder).eventCardviewBinding.likebutton.setOnClickListener(v -> {
if (((Eventholder)holder).likestate==1) {
((Eventholder)holder).likestate=0;
((Eventholder) holder).eventCardviewBinding.LikeCount.setText(String.valueOf(Integer.parseInt(((Eventholder) holder).eventCardviewBinding.LikeCount.getText().toString()) -1 ));
}
else {
((Eventholder)holder).likestate=1;
((Eventholder) holder).eventCardviewBinding.LikeCount.setText(String.valueOf(Integer.parseInt(((Eventholder) holder).eventCardviewBinding.LikeCount.getText().toString()) + 1));
}
((Eventholder)holder).eventCardviewBinding.likebutton.setSelected(((Eventholder)holder).likestate==1);
itemClickHandler.likestate(getItem(position));
});

I want to Change the backgroud Colo of Specific Recycler VIew Item

I want to change the Background Color Green OF the Recycler View data Whose Status IS Ture and Set Backround Color RED whose status is False.
The Round One Status is True and rest are False.
So can any one tell me how i Differentiate ...
My Recycler View code Write Below.
#Override
public void onBindViewHolder(DocRecycleAdoptor.MyViewHolder holder, int position) {
final EmpAttandance empAttandance = mDocs.get(position);
holder.txtDocID.setText(empAttandance.getDOC_ID());
holder.txtEmpID.setText(empAttandance.getEMP_ID());
holder.dateTime.setText(empAttandance.getDATE()+" "+empAttandance.getTIME());
holder.txtCoID.setText(empAttandance.getCO_ID());
holder.txtStatus.setText(empAttandance.getSA());
holder.empName.setText(empAttandance.getEmpName());
if(empAttandance.getStatus() == "True"){
holder.itemView.setBackgroundColor(Color.GREEN);
}else{
holder.itemView.setBackgroundColor(Color.RED);
}
}
Now it Shows like This.
But I want When Status is False Color Will Red.
it didit hapen.
top three Status are True And Other is false.
Showing all in same color
In your onBindViewHolder add below check
if(empAttandance.getStatus()){
//set your desired color on textview or a view for status true
}else{
//set your desired color on textview or a view for status false
}
#Override public void onBindViewHolder(DocRecycleAdoptor.MyViewHolder holder, int position) {
final EmpAttandance empAttandance = mDocs.get(position);
holder.txtDocID.setText(empAttandance.getDOC_ID());
holder.txtEmpID.setText(empAttandance.getEMP_ID());
holder.dateTime.setText(empAttandance.getDATE()+" "+empAttandance.getTIME());
holder.txtCoID.setText(empAttandance.getCO_ID());
holder.txtStatus.setText(empAttandance.getSA());
holder.empName.setText(empAttandance.getEmpName());
// this is it
holder.rootLayout.setBackgroundColor(empAttandance.getStatus() ? GREEN : RED);
}
inside your activity_docattd_list_items add linear layout.
add inside linearlayout a drawable #drawarble/selector_gray_view.
#selector_gray_view.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/gradient_gray_light"
android:state_pressed="true"/>
<item android:drawable="#color/clicked"
android:state_focused="true"/>
</selector>
and after that add drawble #gradient_gray_light.
#gradient_gray_light.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#30888888"
android:endColor="#30888888"
android:angle="90" />
</shape>`enter code here`
and after that add another drawable ,
click inside your selector_gray_view.xml,
#drawable/color.
and also intialize linearlayout in myviewholder.
use it inside onbindviewholder like as:
holder.linearlayout.setonclicklistener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
);
happy coding.
In ANdroid == are Not working. so i use empAttandance.getStatus().equal("True") instead Of == and its working Fine.
Thanks to All of you Guys for helping me out. much appreciate.
if(empAttandance.getStatus().equal("True")){
//set your desired color on textview or a view for status true
}else{
//set your desired color on textview or a view for status false
}

Change TapDown Color on ListView

I have a list view and when the user taps down on the item it looks like this.
This is what it looks like noramally:
How do I change this default light blue color?
I need the color to be set programatically in the activity file, as it is not always the same color, and also how do you change the color of the fuzzy stuff that comes up at the bottom of a ListView when you continue to scroll down?
Thanks for the help
EDIT
Also how do you change the tap down color of the action bar back button,
For the row color, you need to create a StateListDrawable and set it as the selector for the ListView.
The states to include should be, at least:
pressed (android.R.attr.state_pressed)
selected (android.R.attr.state_selected)
"normal" (empty state list)
For each state you can set any drawable. If what you need is a plain color, you can programmatically create a ColorDrawable on the spot.
For example:
StateListDrawable selector = new StateListDrawable();
ColorDrawable red = new ColorDrawable(Color.RED);
ColorDrawable transparent = new ColorDrawable(Color.TRANSPARENT);
selector.addState(new int[] { android.R.attr.state_pressed }, red);
selector.addState(new int[] { android.R.attr.state_selected }, red);
selector.addState(new int[] { }, transparent);
listView.setSelector(selector);
As for the "fuzzy stuff that comes up at the bottom", it's slightly more complicated.
Prior to Android 5.0 there was no public API for changing it.
In Lollipop it can be set via the theme, but not programmatically.
For pre-5.0 there is a well-known workaround (described here) which involves tampering with the drawables that are used. However this solution crashes in 5.0, because those resources do not exist anymore.
For Android 5.0, if a static color is acceptable, you can just configure the new theme attribute android:colorEdgeEffect (which is the same as android:colorPrimary by default).
If a programmatic solution for Android 5.0 is necessary, you could alternatively change the EdgeEffect objects that the ListView has internally using reflection. I've tested this and it works, though it's not the prettiest code:
EdgeEffect edgeEffectTop = new EdgeEffect(this);
edgeEffectTop.setColor(Color.RED);
EdgeEffect edgeEffectBottom = new EdgeEffect(this);
edgeEffectBottom.setColor(Color.RED);
try {
Field f1 = AbsListView.class.getDeclaredField("mEdgeGlowTop");
f1.setAccessible(true);
f1.set(listView, edgeEffectTop);
Field f2 = AbsListView.class.getDeclaredField("mEdgeGlowBottom");
f2.setAccessible(true);
f2.set(listView, edgeEffectBottom);
} catch (Exception e) {
e.printStackTrace();
}
Therefore, a full programmatic solution may run something like this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
// For Android >= 5.0, use setColor() on EdgeEffect
EdgeEffect edgeEffectTop = new EdgeEffect(this);
edgeEffectTop.setColor(Color.RED);
EdgeEffect edgeEffectBottom = new EdgeEffect(this);
edgeEffectBottom.setColor(Color.RED);
try {
Field f1 = AbsListView.class.getDeclaredField("mEdgeGlowTop");
f1.setAccessible(true);
f1.set(listView, edgeEffectTop);
Field f2 = AbsListView.class.getDeclaredField("mEdgeGlowBottom");
f2.setAccessible(true);
f2.set(listView, edgeEffectBottom);
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
// For Android < 5.0, change overscroll_glow and overscroll_edge
int glowDrawableId = getResources().getIdentifier("overscroll_glow", "drawable", "android");
Drawable androidGlow = getResources().getDrawable(glowDrawableId);
androidGlow.setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
int edgeDrawableId = getResources().getIdentifier("overscroll_edge", "drawable", "android");
Drawable androidEdge = getResources().getDrawable(edgeDrawableId);
androidEdge.setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
}
How do I change this default light blue color?
you have to create StateListDrawable and set it as the selector for the ListView. the answer of matiash is good and I do not want to explain it again.
change the color of the fuzzy stuff that comes up at the bottom of a
ListView when you continue to scroll down
setCacheColorHint (int color)
Also how do you change the tap down color of the action bar back
button
<style name="actionbarCustomBackground" parent="#style/Theme.Holo.Light" >
<item name="android:selectableItemBackground">#drawable/actionbar_item_background</item>
</style>
then in the actionbar_item_background:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:exitFadeDuration="#android:integer/config_mediumAnimTime">
<item
android:state_focused="true"
android:state_pressed="true"
android:drawable="#android:color/holo_orange_dark" />
<item
android:state_pressed="true"
android:drawable="#android:color/holo_orange_dark" />
<item
android:drawable="#android:color/transparent" />
</selector>
You can set row's background dynamically in getView(..) method.
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
.......... //your code
view.setBackgroundColor(Color.RED)
return view;
}

change backgroundcolor and image of listview when click on listview

hi dear i have 5 rows in my listview each listview have image and text associated with it ,i want when i click on listview at any position it changes its background color and when i click another position in list previosly selected list row comes to its former condition and selected change the color and image ...how to achive it ?thanks
my code is ..but it does not retain previously selected row...
public void onListItemClick(ListView parent, View v, int position,
long id) {
if(position == 0)
{
v.setBackgroundColor(Color.WHITE);
}
if(position == 1)
{
v.setBackgroundColor(Color.WHITE);
}
Toast.makeText(getApplicationContext(), "You have selected "
+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
You can use the concept of selector. Create a selector xml and use it as the background of the row. it may help you.like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="#drawable/selector_s" />
<item android:state_pressed="true" android:drawable="#drawable/selector_s" />
<item android:drawable="#drawable/selector_d" />
</selector>
you can use this link
http://android-journey.blogspot.com/2009/12/android-selectors.html

Why can't I set my custom Listview item's background dynamically?

I have a custom listview and I am using a custom listadapter to display that list. In my custom listadapter I am trying to set the colour of each item dynamically depending on a value within the object. However whenever I try to do this the items become faded rather than getting the colour they were set to. I am applying a few styles to the project but when I remove their effect it still doesn't work. This is my code to change the background colour of each item:
private class stationAdapter extends ArrayAdapter<Station>{
private ArrayList<Station> stations;
public stationAdapter(Context context, int textViewResourceId, ArrayList<Station> stations) {
super(context, textViewResourceId, stations);
this.stations = stations;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Station temp = stations.get(position);
if (temp != null) {
TextView stationName = (TextView) v.findViewById(R.id.stationname);
TextView serviced = (TextView) v.findViewById(R.id.inservice);
try{
if(temp.getLine().equals("red")){
v.setBackgroundColor(R.color.red);
}
else{
v.setBackgroundColor(R.color.green);
}
}catch(Exception e){
Log.d(TAG, "Null pointer");
}
if (stationName != null) {
stationName.setText("Station: "+temp.getName()); }
if(serviced != null){
serviced.setText("In Service: "+ temp.getInServive());
}
}
return v;
}
}
If anyone could point out what I am doing wrong I would really appreciate it.
You cant use setBackgroundColor and then reference a resource. if you want to use setBackgroundColor() you need to use the Color class like:
setBackgroundColor(Color.BLACK);
Instead if you want to set a resource (R.drawable, R.color etc...) you need to do it like
v.setBackgroundResource(R.color.black);
EDIT:
The cache color hint is what is needed if the items start becoming gray while scrolling the list. You need to set it to a transparent color if you are adding custom backgrounds to items and lists.
Like Darko mentioned, you're trying to set a color but using a resource ID instead. With that said, using a solid color for a list item background is a big no-no, you definitely want to use a selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_pressed="false" android:state_selected="false"
android:state_checked="false" android:state_enabled="true" android:state_checkable="false"
android:drawable="#color/red" />
</selector>
Put that in a list_red_background.xml in your drawables folder and use setBackgroundResource() instead.
Have you switched fading off?
http://developer.android.com/resources/articles/listview-backgrounds.html
Add this to the ListView layout file:
android:cacheColorHint="#00000000"

Categories

Resources