Android - Using int in different classes
i have this int MASK..
public class Canvastutorial extends Activity {
/** Called when the activity is first created. */
public int MASK=R.drawable.face00;
public void setMask(int value)
{
MASK=value;
}
its value is changed in the same class Canvastutorial as
public void onClick(DialogInterface dialog, int item)
{
if(items[item]=="Mask 1")
{
setMask(R.drawable.face00);
开发者_StackOverflow }
else if(items[item]=="Mask 2")
{
setMask(R.drawable.face01);
}
else if(items[item]=="Mask 3")
{
setMask(R.drawable.face02);
}
else if(items[item]=="Mask 4")
{
setMask(R.drawable.face03);
}
else if(items[item]=="Mask 5")
{
setMask(R.drawable.face04);
}
i want to use this int MASK in other class
public class Panel extends SurfaceView implements SurfaceHolder.Callback{
i am unable to do so.. so far i tried to call MASK as Canvastutorial.ct = new Canvastutorial(); and then using ct.MASK;
but this forced closed the application..
Any ideas how to do so?
One way to do it would be to use a static int and a static method. These could be accessed from anywhere using Canvastutorial.MASK and Canvastutorial.setMask(...). Probably not the cleanest approach, but it would work.
You could also keep the code as you have it now, but create a static instance of that class, and use Canvastutorial.getInstance() to access it (instead of creating new classes).
The other approach is to use the ApplicationContext() (essentially a global context).
You declare the application context class like this in the manifest:
<application
android:name=".model.AppModel">
</application>
Then you extend from the Application class to make your custom ApplicationContext Object like so:
public class AppModel extends Application {
private User user;
public void setUser(User user) {
this.user = user;
}
public User getUser() {
return user;
}
And whenever you need to access you object, you do this:
AppModel appModel = ((AppModel) getApplicationContext());
appModel.setUser(user);
You can access your appModel anywhere.
精彩评论