简体   繁体   English

从扩展视图的类中调用活动类中的变量或方法?

[英]Calling a variable or method in the activity class from a class that extends view?

I am very new to android and I need help. 我是Android新手,需要帮助。

I have got a GameActivity class and I set the setContentView to GameView class. 我有一个GameActivity类,并将setContentView设置为GameView类。 I want to access a variable that is located in GameView class from the GameActivity class. 我想从GameActivity类访问位于GameView类中的变量。

Is this possible? 这可能吗?

public class GameActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    View gameview = new GameView(this);
    setContentView(gameview);

    }

}

And this is my GameView class 这是我的GameView类

public class GameView extends View {

    private static final String TAG = null;     // for log.e

    private Ball ball1;                         // ball1
    private GameContainer gameContainer;        // frame for the game
    private Racket racket;                      // controller
    int viewWidth = 0;                          // width onchange
    int viewHeight = 0;                         // height onchange    
    private Score score;


    // constructor
    public GameView(Context context) {
        super(context);

        ball1 = new Ball(Color.GREEN, 24, 10, 2);   // colour, radius,speedx, speedy 
        ball1.setBallLocation(10, 5);   // x, y of ball    
        gameContainer = new GameContainer(Color.GRAY);
        racket = new Racket(Color.BLACK);    
        score = new Score(Color.WHITE);     
    }

    @Override
    public void onDraw(Canvas canvas){
        gameContainer.container(1, 2, 100, 100);
        gameContainer.display(canvas);

        ball1.drawBall(canvas);
        ball1.moveBall(gameContainer);

        // check the ball if it is out display the alert box
        if (ball1.getEndGame()){
            Log.e(TAG, "END of game");
        }   
    }   
}

Plain Old Java conventions should work. Plain Old Java约定应该起作用。

Add getter/setter methods for the variables you need access to and use them to get the values. 为您需要访问的变量添加getter / setter方法,并使用它们获取值。

public int getHeight(){
     return viewHeight;
}

Would this not work 这行不通吗

To access some property directly, first, declare it as public: 要直接访问某些属性,首先,将其声明为public:

public int viewWidth = 0;                              

second, just call it: 其次,只需调用它:

gameview.viewWidth = ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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