Search code examples
javaandroidonclicklistenerencapsulation

using variable in another class


Iam creating an android app that has many classes inside the main Java package. The MainActivity class implements Button onClick Listener and do some coding with assigning values to variable x inside the method when button is clicked, now I have class#2 use the same variable x in some other coding. I want the onClick method when it is called to send the variable x value to class#2

MainActivityCalss {

    hi.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            int x = 1;
        }
    });

}

Class2 {

    Method() {
        y = x + 1;
    }

}

Solution

  • Define "x" in other class and set it using setter method, and where ever you get it through getter.

    public class value {
        public static int x;
    
        public static void set(int value) {
            x = value;
        }
    
        public static int get() {
            return x;
        }
    }
    

    And in onclicklistener of mainactivity.

    hi.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            value.set(1);
        }
    });
    

    In class2

     Method() {
            y = value.get()+1;
        }