简体   繁体   中英

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

}

Creating a new Java class to hold all global variables is a very good idea.

public class GlovalVariable{
    public String x;
    public int y;
    // Generate getter/setter methods for all the variables defined here.
}

By creating this you will manage a variables very easily. If you want to rename the variable which is used through out the class, this method will make it very easy.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM