当前位置: 动力学知识库 > 问答 > 编程问答 >

android - Sending variables to OnTouch method

问题描述:

In this method i set mode to 1;

bTouch.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

mode1=1;

Intent startGame = new Intent(

"com.example.mygame.GFXSurface");

startActivity(startGame);

}

});

when i call that mode in other class in onTouch method returns 0

public boolean onTouch(View v, MotionEvent event) {

// TODO Auto-generated method stub

GameSurface gamesurface = new GameSurface(this);

Mode mode2 = new Mode();

mode= mode2.mode1;

if (mode == 1){ // this should be 1 but is 0

x = event.getX();

y = event.getY();

Anyone know the solution on how to do that?

网友答案:

No, mode1 values is not 1, It should be 0.

Just look at these two code lines..

Mode mode2 = new Mode();
mode= mode2.mode1; 

Now from 1 code line Mode mode2 = new Mode();

you are creating a new Class Mode object mode2.

As per the class object initializing rules you are allocated a memory for a new Mode class. So all its member variables and fields are initializing to with new mwmory.

Now come on code line 2

mode = mode2.mode1; 

you are accessing mode1 member field of newly created class Mode with object mode2.

So how it can hold the old value 1? (Think again)

Now how can you access this value in other class?

Either make a member field mode1 as a static and directly access the field with class Name,

like, Mode.mode1

Or use the same object for retrieving (get) value of mode1 from which you set the value for mode1.

分享给朋友:
您可能感兴趣的文章:
随机阅读: