How to set up animated drawable with recyclerview? - android

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));
});

Related

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
}

Android - How to get the image resource to use in if statement

So I set a onClick listener to my ImageView via the xml file. It's called changeImage(). In that, I want it to be so:
if(img.getImageResource == R.drawable.1){
img.setImageResource(R.drawable.2);
}else if(img.getImageResource == R.drawable.2){
img.setImageResource(R.drawable.1)
}
Only the problem is, there's no such thing as getImageResource. How do I do it?
EDIT:
public void changeImage(View v) {
ImageView img = (ImageView) v.findViewById(R.id.img);
Drawable drawable = img.getDrawable();
if(drawable == getResources().getDrawable(R.drawable.lightbulb_off)){
img.setImageResource(R.drawable.ic_launcher);
}else if(drawable == getResources().getDrawable(R.drawable.ic_launcher)){
img.setImageResource(R.drawable.lightbulb_off);
}
}
does not work. Why???????? :'(
As alanv states, using a selector would work, where you'd be able to check the selected state of the ImageView.
I'd recommended separating your business logic from the UI though; e.g. create a LightBulb class which has a state of ON or OFF. Instead of relying on the current state of the ImageView when toggling, you'd just check the state of your lightBulb:
private void toggleSwitch() {
lightBulb.toggleSwitch();
updateLightBulbImage();
}
private void updateLightBulbImage() {
if (lightBulb.isSwitchedOn()) {
img.setImageResource(R.drawable.switched_on);
} else {
img.setImageResource(R.drawable.switched_off);
}
}
Calling Resources.getDrawable() returns a unique object each time, so == comparison will never return true. Drawables also don't generally implement Object.equals() in a way that would solve your issue either.
Instead, consider using a selector drawable as your image and ImageView.setSelected(boolean) to toggle between states.
res/drawable/lightbulb.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="#drawable/ic_launcher" />
<item android:drawable="#drawable/lightbulb_off" />
</selector>
res/layout/your_layout.xml:
<ImageView android:id="#+id/img" android:src="#drawable/lightbulb" />
In your code, toggle selection state.
public void changeImage(View v) {
ImageView img = (ImageView) v.findViewById(R.id.img);
img.setSelected(!myImageView.isSelected());
}

android change image of imageview in listview

I have created a sliding menu.
In that i put image-view, on clicking image-view it shows me content,all works fine.
Now what i want to do is,
on selecting image-view, which is active i want to change its image and remaining things will still be unchanged... (i have created for that adapter )
private void onMenuItemClick(AdapterView<?> parent, View view,
int position, long id) {
//bla bla bla
//some other code
if (selectedItem.compareTo("ABC") == 0) {
View subview = view.findViewById(R.id.list_image);
((ImageView) subview).setImageResource(R.drawable.img1);
fragment = new abcactivity();
} else if (selectedItem.compareTo("XYZ") == 0) {
View subview = view.findViewById(R.id.list_image);
((ImageView) subview).setImageResource(R.drawable.img2);
fragment = new xyzactivity();
} else if (selectedItem.compareTo("Another") == 0) {
View subview = view.findViewById(R.id.list_image);
((ImageView) subview).setImageResource(R.drawable.img3);
fragment = new anotheractivity();
}
here i put images in
images = new ArrayList<Integer>();
images.add(R.drawable.img1);
images.add(R.drawable.img2);
images.add(R.drawable.img3);
I want change only activated image and that's also i have done but it should change to previous if i am selecting second position image.!
I think what you need is a selector file. You need add a image_change.xml in your /res/drawable folder.
img_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/image_white" android:state_activated="false" />
<item android:drawable="#drawable/image_black" android:state_pressed="true" />
<item android:drawable="#drawable/image_black" android:state_activated="true" />
</selector>
And in your ImageView, you must set the drawable file:
<ImageView
...
android:background="#drawable/img_selector"
... />
Or, in your code:
images.setBackground(R.drawable.img_selector);
I hope I've helped

How to Get Android TableRow background color?

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();

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

Categories

Resources