Saving state of a specific like Button in recycler view - android

In recycler view I have pictures with "Like" buttons on them. When I click a "Like" button for a specific picture, its color changes to red. But when I reopen the app, All "Like" buttons are red, even the ones which I didn't clicked.
I'm using sharedPreferences to save the state of the button.
In onBindViewHolder:
myPref = context.getSharedPreferences("MINE", Context.MODE_PRIVATE);
myEditor = myPref.edit();
myEditor.putBoolean("isChecked", false);
holder.likeBtn.setChecked(myPref.getBoolean("isChecked", false));
holder.likeBtn.setOnCheckStateChangeListener((view, checked) -> {
if (checked) {
myEditor.putBoolean("isChecked", true);
myEditor.apply();
} else {
myEditor.putBoolean("isChecked", false);
myEditor.apply();
}
}
So, here how can save clicked state of a specific like button. How can I get the position of a button that I want to click.

Related

Change color of List View row to user's desired color

I'm developing a "Notes" application. I've added an option in Action Bar which shows different colors. When users click on any color it changes the background color but as soon as the user exits that particular activity and goes back to the List View the color is lost. It doesn't show on that particular list view item. Can anyone tell me how can i retain the color changed state? Thank you.
Probably the easiest thing to do would be to save the user's color choice in SharedPreferences. You could read the list's background color in onCreate() and update the preference every time the user chose a color from the toolbar.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
SharedPreferences prefs = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
int color = prefs.getInt("KEY_COLOR", -1);
if (color == -1) {
color = /* your default color here */;
}
listView.setBackgroundColor(color);
}
private void onToolbarColorSelected(int color) {
listView.setBackgroundColor(color);
SharedPreferences prefs = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
prefs.edit().putInt("KEY_COLOR", color).apply();
}

Change background of ImageButton in popup window

I'm building an app and want to change the teamcolors in a popup window. I used ImageButtons to show the users the teamcolors. One button in the main activity and four buttons in the popup window. When I click one in the popup window, I can switch the backgrounds but when I close the popup window and open it again, the buttons in the popup window has been reseted.
How can I close my popup window without the reset?
public void colorchange(final View view){
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popwindow, null);
relativeLayout = (RelativeLayout) findViewById(R.id.popup);
popupWindow = new PopupWindow(container, relativeLayout.getWidth(), relativeLayout.getHeight(), true);
popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, (int)relativeLayout.getX(),(int)relativeLayout.getY());
ImageButton narancs = (ImageButton) container.findViewById(R.id.imgbutton1);
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return false;
}
});
narancs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Drawable asds = v.getBackground();
Log.d("hatter", String.valueOf(asds));
v.setBackgroundResource(R.drawable.bluebutton);
view.setBackgroundResource(R.drawable.orangebutton);
Log.d("hatter", String.valueOf(view.getBackground()));
//popupWindow.dismiss();
}
});
}
This code runs on mainactivity button click event.
If I understand your answer correctly, you want to "save" the button background color on click. If that is so, you could use Shared Preferences (Android Developer - Shared Preferences) to store the selected color on click. in the activity, you could set the color of the button from the shared preferences.
On Click
SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.apply();
Afterwards, you can load this value to set the color of the Background
SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
//You can use a switch or if else
if(settings.getString(key, defValue).toUppercase.equals("BLUE")){
//set Color Blue as Background
v.setBackgroundResource(R.drawable.bluebutton);
}else if(...)
I hope this helps :)

ListView Images change back to original settings when scrolled out of view - Android

I have a ListView that contains multiple ListView items. The ListView items Layout contains an ImageView. I use this ImageView as a button. When the button is clicked it changes the ImageView from a gray image to a green image. But when I scroll the ImageView out of visible view and then back to it, it returns to its original color. When the ImageView is created it can be either green or gray, it depends on a JSON array. So if an image is green and clicked it turns to gray. Then when its out of visible view and returned to visible view it is green again! How can I make the images maintain their new state?
Here is my code,
if(p.getJSON().equals("NO")){
imageView.setBackgroundResource(R.drawable.gray);
imageView.setTag(0);
}//end if equals NO
if(p.getJSON().equals("YES")){
imageView.setClickable(false);
imageView.setBackgroundResource(R.drawable.green);
imageView.setTag(1);
}//end if equals yes
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View imageView) {
final int status = (Integer) imageView.getTag();
if (status == 0){
imageView.setBackgroundResource(R.drawable.green);
imageView.setTag(1);
}
else{
imageView.setBackgroundResource(R.drawable.gray);
imageView.setTag(0);
}
}//end on click
});
You need to persist the state for the items that you have modified with the button press and then restore that state when your adapter's getView() is called for that item.
There are many ways you can do this: in memory, database, etc. You'll have to pick the method that works best for your purposes.
i.e. - item 3 gets clicked and the image changes from grey to green, store something to represent the state of the image (grey vs. green, a boolean would be great for this exact case) and then persist that data somewhere. Then when getView() gets called again for item 3 (it's about to be displayed again) you set the color of the image based on the data you persisted for item 3.
You could just modify the value in the original JSONArray that backs the ListView, btw.
The reason for this behaviour is because you do not persist the state of the items (if they were clicked or not). Each time the list is scrolled, the getView() is called and it executes the following code and the state is reset:
if(p.getJSON().equals("NO") ){
imageView.setBackgroundResource(R.drawable.gray);
imageView.setTag(0);
}//end if equals NO
if(p.getJSON().equals("YES")){
imageView.setClickable(false);
imageView.setBackgroundResource(R.drawable.green);
imageView.setTag(1);
}//end if equals yes
What is needed is a way to keep track of the state of each item based on its position. So you could confidently tell: item at position k is "YES" or "NO"!
You need to keep track of the items which have been clicked so that when getView() is called, you can update the state of the based on its current value (not based on JSON value).
1) Maintain a map of items positions which are checked, and corresponding state value ("YES" or "NO").
2) If item is clicked, add its (position, new state) to the map. If it is clicked again, update its state inside the map.
3) Use this map and set the state of the item in the getView(), something like:
Private field:
HashMap<Integer, String> map = new HashMap<Integer, String>();
In your getView():
String state = p.getJSON();
if(map.containsKey(position)) {
state = map.get(position);
}
if(state.equals("NO") ){
imageView.setBackgroundResource(R.drawable.gray);
imageView.setTag(0);
}//end if equals NO
if(state.equals("YES")){
imageView.setClickable(false);
imageView.setBackgroundResource(R.drawable.green);
imageView.setTag(1);
}//end if equals yes
final int pos = position;
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View imageView) {
final int status = (Integer) imageView.getTag();
if (status == 0){
imageView.setBackgroundResource(R.drawable.green);
imageView.setTag(1);
map.put(pos, "YES")
}
else {
imageView.setBackgroundResource(R.drawable.gray);
imageView.setTag(0);
map.put(pos, "NO")
}
}//end on click
});
Note: this is just one of the many ways of getting what you want, however the basic idea should be the same..

highlight the linearlayout background in android

I have to develop one android application.
Here is the scenario:There are many images in a linearlayout. When selected, the layout should be displayed with another background. This works well now.
Now, I would like that when I open a new activity and come back tho this one, the last selected layout should still be the highlighted one (with the second background).
How can this be done ???
Now i have used below code for highlighting the image when pressed:
LinearLayout ar = new LinearLayout(this);
ar.setOrientation(LinearLayout.VERTICAL);
ar.setPadding(3, 3, 3, 3);
ar.setLayoutParams(artiLayoutParams);
ar.setGravity(Gravity.CENTER);
ar.setBackgroundColor(Color.parseColor("#666666"));
ar.setBackgroundDrawable(getResources().getDrawable(R.drawable.list_selector));
ar.setId(position);
position++;
ar.setOnClickListener(mArticleClick);
EDIT:
private OnClickListener mArticleClick = new OnClickListener()
{
#Override
public void onClick ( View v )
{
int object = v.getId();
v.setSelected(true);
String articletitle = Appscontent.Sub_arraylist.get(object).toString();
Intent in = new Intent(MainActivity.this, SubCate.class);
in.putExtra("Title", articletitle);
startActivity(in);
}
};
Here i have to clicked one item means it is go to next activity.afterthat i have clicked back button means the selected item is stay on highlighted with another background.afterthat i have selected another item means its go to next activity.now i have to click back button means these item only highlight with background....but the pervious item also highlighted....
I wish to need the o/p like :
The last selected item only highlighted after click the back button...please help me...how can i do ..
EDIT:
I have declared int prevPosition = -1; globally...
Afterthat i have save the value here:
ar = new LinearLayout(this);
ar.setOrientation(LinearLayout.VERTICAL);
ar.setPadding(3, 3, 3, 3);
ar.setLayoutParams(artiLayoutParams);
ar.setGravity(Gravity.CENTER);
ar.setBackgroundColor(Color.parseColor("#666666"));
ar.setBackgroundDrawable(getResources().getDrawable(R.drawable.list_selector));
ar.setId(position);
position++;
ar.setOnClickListener(mArticleClick);
SharedPreferences preferences = getSharedPreferences(SPF_NAME, android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("POSITION", prevPosition);
editor.commit();
In Onclick method:
private OnClickListener mArticleClick = new OnClickListener()
{
#Override
public void onClick ( View v )
{
int object = v.getId();
SharedPreferences preferences = getSharedPreferences(SPF_NAME, android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("POSITION", -1);
editor.commit();
But my background color is not staying here after press the back button...
This is "easy". In order to be able to know which image should be highlighted, you need to store this information somewere. A good practice is a database, but if you have only this info to store, you can create something like a shared preferance or some other types of global variables. Then, when you will re-open the activity with your listview (or come back to it), you should tell to your listview which item should be highlighted and highlight this item.

how to change text of custom listview button that is added dynamically and how to perform click event of this button

I have a listiview in which rows are like this
ListView
[Text1] [Button1]
[Text2][Text3] [Text3]
when i click on button according to status text call go to server.
If suppose status is invite and we click the button call send to server according to invite and if status is chat request then button text will be invite and one more button will be shown is this case and if in this case if user click on invite ,then invitation send to visitor.and button text change to join and then if click on join then status text will be again change.how can this possible.
You can do this in the adapter for your ListView. There is a getView() method that you should override.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view = super.getView(position, convertView, parent);
final Button button = (Button) view.findViewById(R.id.rowButton);
//now that you have it, you can change text whatever
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View button) {
//do whatever
}
});
return view;
}
I yet not understand your flow of app but i think,you need two or three button depending on some condition of your listitem's buttons clicked.
If so,then simply you will have to design your listitem with 3 buttons only,and when you need 2 of them,just invisible the unwanted one.You can do that in the onClick of the button of your listitem which decides total number of buttons to be displayed.
EDIT :
You can follow below code in getView() of your custom adapter class:
lets assume that you have buttons button1,button2,button3:
for status="chat":
button1 text="invite"
button2 text="deny"
button3 is invisible
For otherwise,
button1 text="Join"
button2 text="Invite"
button3 text="Something" and its visible.
...getView(...)
{
...
if(status.equals("chat"))
{
holder.button1.setText("Accept");
holder.button2.setText("Deny");
holder.button3.setVisibility(View.GONE);
}
else
{
holder.button1.setText("Join");
holder.button2.setText("Invite");
holder.button3.setVisibility(View.VISIBLE); // you can set its visibility for according cases
holder.button3.setText("Something");
}
holder.button1.setOnClickListener(new On....{
..onClick(){
if(status.equals("chat"))
{ // code for invite }
else
{ //code for join }
}
});
holder.button2.setOnClickListener(new On....{
..onClick(){
if(status.equals("chat"))
{ // code for deny }
else
{ //code for invite }
}
});
holder.button3.setOnClickListener(new On....{
..onClick(){
if(status.equals("chat"))
{ //code for the case when the button is visible }
}
});
return ..;
}

Categories

Resources