Search code examples
androidonclicksharedpreferencesonclicklistenerclass-variables

Class variables in OnClickListener


I have a separate class for my OnClickListeners. I would like to add items to an arraylist when i click a button, and remove them when I click a 2nd time. I have the framework here:

public void onClick(View v) {
        Button button = (Button)v;
        if(isClicked) {
            button.setText("Enabled");
            Log.v("Spirit: ", v.getTag() + "");
            spirits_list.add(v.getTag() + "");
            isClicked = false;
        } else {
            button.setText("Disabled");
            spirits_list.remove(v.getId()-1);
            isClicked = true;
        }



    }

I also have an ArrayList initialized at the top, but every time I click a button it reinitializes the ArrayList. How can I get around this? Also, I need to be able to save the ArrayList to SharedPreferences - how can I do this from my OnClickListener?


Solution

  • Since you use your own class, you can pass all the goodness around in class members:

    class MyListener implements View.OnClickListener {
    
        private ArrayList<Object> spirits_list;
        private Context ctx;
    
        public MyListener( Context ctx, ArrayList<Object> list ) {
            super();
            this.ctx = ctx;
            this.spirits_list = list;
        }
    
        public void onClick(View v) {
            Button button = (Button)v;
            if(isClicked) {
                button.setText("Enabled");
                Log.v("Spirit: ", v.getTag() + "");
                this.spirits_list.add(v.getTag() + "");
                isClicked = false;
            } else {
                button.setText("Disabled");
                this.spirits_list.remove(v.getId()-1);
                isClicked = true;
            }
    
    
    
        }
    
    }
    

    The context will allow you to access SharedPrefs as well. You can then invoke this bit as follows:

    view.setOnClickListener( new MyListener( this, spirits_list ) );