【问题标题】:Change color of imagebutton on clicking it in Recyclerview在 Recyclerview 中单击时更改图像按钮的颜色
【发布时间】:2016-05-19 16:57:41
【问题描述】:

我已经实现了 recyclerview,它下面有一个图像和图像按钮。当我单击图像按钮时,我已经设置了一个祝酒词,当我单击它时,我还想更改图像按钮的颜色,当视图离开可见区域后,位于该位置的所有项目的颜色会发生变化,即如果我单击在第二个图像按钮处,所有可见的第二个图像按钮都变为彩色

我该如何解决这个问题??

这是我的代码:

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

            }
        }

【问题讨论】:

    标签: android onclick android-recyclerview imagebutton


    【解决方案1】:

    老问题没有答案,所以对于您或未来或当前的搜索者,我正在发布答案。

    与其在 onBindViewHolder 中定义点击侦听器,不如在你的类 ViewHolder 中简单地完成,就像我在下面发布的那样,它将避免调用 RecyclerView 和整个项目中的点击一次一行,同样的方法也可以用你的方法来完成,但是这很昂贵,阅读THIS为什么在 onBindViewHolder 中定义点击事件不是一个好习惯。

    现在来回答部分如何在点击时更改 imageButton 的颜色并显示 toast。

    RecyclerAdapter 类:

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

    这样,您可以在单击 imageButton 时更改图标或更改颜色并显示消息。

    这可能对某些人有帮助。

    【讨论】:

      猜你喜欢
      • 2021-05-28
      • 1970-01-01
      • 2021-07-07
      • 2012-12-06
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 2021-05-21
      相关资源
      最近更新 更多