1

I have implemented recyclerview with an image and image-Button below it. I have set a toast when i click on the image button and i also want to change the color of the imagebutton when i click it color changes of all the items that are in that position after view has gone out of visible area i.e if i clicked at 2nd image-button then all the visible 2nd image-buttons come as colored

how can i solve this??

this is my code:

package com.example.tatson.bila;       

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder>  {


    private String imageUrl;
    private ImageLoader imageLoader;
    private Context context;
    String Load;
    static int count = 0;
    public static final String uu = "uu";
    String number;
    String  user1;
    public static final String UserNum = "UserNum";
    SharedPreferences sharedPref;

    private String[] pos;
    private int visibleThreshold = 5;
    private int lastVisibleItem, totalItemCount;
    private boolean loading;
    private OnLoadMoreListener onLoadMoreListener;
    // JSON parser class
    JSONParser jsonParser = new JSONParser();
    String url,imgoffset;
    //testing from a real server:
    private static final String LIKE_URL = "my php";

    //ids
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    List<SuperHeroes> superHeroes1;
    //List of superHeroes

    List<SuperHeroes> superHeroes;
    private RecyclerView recyclerView;


    public CardAdapter() {
    }

    public CardAdapter(List<SuperHeroes> superHeroes, Context context) {
        super();
        //Getting all the superheroes
        this.superHeroes = superHeroes;
        superHeroes1= superHeroes;
        this.context = context;
        sharedPref  =context.getSharedPreferences(UserNum, 0);
        number =  sharedPref.getString(uu, "");    
    }    

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.superheroes_list, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;    
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {

        SuperHeroes superHero = superHeroes.get(position);
       Log.d("position", String.valueOf(position));
        Log.d("url", superHero.getImageUrl());
        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));

        holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
        holder.textViewName.setText(superHero.getName());
        holder.textViewRank.setText(String.valueOf(superHero.getRank()));

        // holder.textViewPowers.setText(powers);
        holder.like.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {

                ImageButton like =(ImageButton) v.findViewById(R.id.button_like);
                like.setImageResource(R.drawable.plike);

                        SuperHeroes s = superHeroes.get(position);

                        Load = s.getImageUrl();
                        Log.d("test", Load);    

                        new LikeIt().execute();    
            }
        });    
    }


    @Override
    public int getItemCount() {
        return superHeroes.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        public NetworkImageView imageView;

        public TextView textViewName;
        public TextView textViewRank;
        public TextView textViewRealName;
        public TextView textViewCreatedBy;
        public TextView textViewFirstAppearance;
        public TextView textViewPowers;
       public ImageButton like;

        public ViewHolder(View itemView) {
            super(itemView);
            imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
            textViewName = (TextView) itemView.findViewById(R.id.textViewName);
            textViewRank = (TextView) itemView.findViewById(R.id.textViewRank);
            // textViewRealName= (TextView) itemView.findViewById(R.id.textViewRealName);
            // textViewCreatedBy= (TextView) itemView.findViewById(R.id.textViewCreatedBy);
            // textViewFirstAppearance= (TextView) itemView.findViewById(R.id.textViewFirstAppearance);
            // textViewPowers= (TextView) itemView.findViewById(R.id.textViewPowers);
            like = (ImageButton) itemView.findViewById(R.id.button_like);

        }    
    }

     class LikeIt extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag

             int success;

            String Imgurl = Load;
            Log.d("request!", number);

          //  try {
                // Building Parameters
                HashMap<String, String> Params = new HashMap<String, String>();
                Params.put("Imgurl", Imgurl);
           Params.put("user", number);


                Log.d("request!", "starting");    

                String encodedStr = getEncodedData(Params);

                //Will be used if we want to read some data from server
                BufferedReader reader = null;

                //Connection Handling
                try {
                    //Converting address String to URL
                    URL url = new URL(LIKE_URL);
                    //Opening the connection (Not setting or using CONNECTION_TIMEOUT)
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();

                    //Post Method
                    con.setRequestMethod("POST");
                    //To enable inputting values using POST method
                    //(Basically, after this we can write the dataToSend to the body of POST method)
                    con.setDoOutput(true);
                    OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
                    //Writing dataToSend to outputstreamwriter
                    writer.write(encodedStr);
                    //Sending the data to the server - This much is enough to send data to server
                    //But to read the response of the server, you will have to implement the procedure below
                    writer.flush();

                    //Data Read Procedure - Basically reading the data comming line by line
                    StringBuilder sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String line;
                    while((line = reader.readLine()) != null) { //Read till there is something available
                        sb.append(line + "\n");     //Reading and saving line by line - not all at once
                    }
                    line = sb.toString();           //Saving complete data received in string, you can do it differently

                    //Just check to the values received in Logcat
                    Log.i("custom_check","The values :");
                    Log.i("custom_check", line);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(reader != null) {
                        try {
                            reader.close();     //Closing the
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                //Same return null, but if you want to return the read string (stored in line)
                //then change the parameters of AsyncTask and return that type, by converting
                //the string - to say JSON or user in your case
                return null;
            }

        }
    private String getEncodedData(Map<String,String> data) {
        StringBuilder sb = new StringBuilder();
        for(String key : data.keySet()) {
            String value = null;
            try {
                value = URLEncoder.encode(data.get(key), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if(sb.length()>0)
                sb.append("&");

            sb.append(key + "=" + value);
        }
        return sb.toString();
    }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        protected void onPostExecute() {
            // dismiss the dialog once product deleted

            }
        }
mfaisalhyder
  • 2,250
  • 3
  • 28
  • 38
Tatson Baptista
  • 445
  • 3
  • 6
  • 18

1 Answers1

0

old question and unanswered so for you or future or current searchers i am posting answer.

Instead of defining the click listener inside onBindViewHolder do it simply inside your class ViewHolder like i posted below, it will avoid calling the clicks of item inside RecyclerView and the whole row at a time, same can also be done with your approach but that's expensive, read THIS why defining click events inside onBindViewHolder is not good practise.

Now coming towards answer part how to change color of imageButton on click and display a toast.

RecyclerAdapter Class:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ItemsViewHolder>{

private static List<MapperClass> wordsList;
// some other variables to use

public RecyclerAdapter(Context con, List<MapperClass> wordsList){
    RecyclerAdapter.wordsList=wordsList;
    RecyclerAdapter.context=con;
}

public static class ItemsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView txtViewWord,txtViewPOS;
    ImageButton imgButtonFavourite;
    boolean starred = false; //for checking that row is starred(favourite-d) or not      
                       // & to avoid resetting of imageButton on scroll of recyclerView. 


    public ItemsViewHolder(View itemView){ //here you should define click events.
        super(itemView);

        txtViewWord = (TextView) itemView.findViewById(R.id.txtView_Word);
        txtViewPOS = (TextView) itemView.findViewById(R.id.txtView_PartOfSpeech);
        imgButtonFavourite = (ImageButton) itemView.findViewById(R.id.imgButton_Favourite);

        itemView.setOnClickListener(this);
        imgButtonFavourite.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                if(starred){ 
                    Drawable starEmpty = view.getResources().getDrawable(R.drawable.ic_favourite);
                    starEmpty.setBounds(0,0,24,24);
                    imgButtonFavourite.setBackground(starEmpty);
                }else{ //here i am setting another pic when user marks word favourite i.e.
                     // filled star , you can change color of imageButton here instead of
                     // changing icon, u can simply getColor from getResource
                     // and pass it desired color                  
                    Drawable startFilled = view.getResources().getDrawable(R.drawable.ic_favourite_filled);
                    startFilled.setBounds(0,0,24,24);
                    imgButtonFavourite.setBackground(startFilled);

        //here instead of normal toast, i used Snackbar :D (Toast on Steroids) **requires design support library**  
       //when you will click imageButton a snackBar will pop out
                    Snackbar.make(view, "Icon changed of imageButton", Snackbar.LENGTH_LONG).show();

      // here you have toast as well, use any one 
      //Toast.makeText(view, "Icon changed of imageButton", Toast.LENGTH_LONG).show();
                }                   
                starred = !starred;             
            }   
        });
    }

This way you can change the icon or change color of imageButton upon clickcing it and also show a message.

This might be helpful for some.

Community
  • 1
  • 1
mfaisalhyder
  • 2,250
  • 3
  • 28
  • 38