使两个子视图中的对象相等

时间:2019-02-13 16:17:41

标签: java android

我有两个视图类HitOrMissPlaceShips,它们扩展了一个类BuildGame。 BuildGame有一个对象mGame。在运行时,将创建2个mGame实例,每个子类一个。 mGame包含侦听器列表以及其他内容,但是HitOrMiss和PlaceShips仅将其侦听器添加到自己的mGame实例中。因此,只有在您点击特定视图时,各个视图才会更新。

基本上,我试图将其中一个视图的mGame设置为另一个视图的mGame,这样就只会更新对同一对象的引用,但是我不知道怎么做!将mGame设置为static确实可以,但是,我在本单元的讲师说,还有一种不使用静态的方法,我会丢分,这很公平。

BuildGame:

public class BuildGame extends View {
protected final BaseSubClass mGame = new BaseSubClass(10, 10, BattleshipGameBase.ShipData.CREATOR.newArray(5));
private Paint mGridPaint, mPlayer1Paint, mPlayer2Paint, mBGPaint, mHitPaint, mMissPaint;
protected float diameterX, diameterY, chosenDiameter, separatorSize, canvasWidth, canvasHeight;
protected int tokenAtPos;

public BuildGame(Context context, AttributeSet attrs) {
    super(context, attrs);
    initialise();
}

PlacedShips和HitOrMiss除了名称外,基本上是相同的代码段:

public class PlaceShips extends BuildGame {

private GestureDetector mGestureDetector;
private int placedShipNo = 0;

public PlaceShips(Context context, AttributeSet attrs) {
    super(context, attrs);
    mGestureDetector = new GestureDetector(context, new MyGestureListener());

    //GameplayListenerStuff
    BattleshipGameBase.BattleshipGameListener mGameplayListenerPS = new BattleshipGameBase.BattleshipGameListener() {
        @Override
        public void onGameChanged(BattleshipGameBase game, int column, int row) {
            System.out.println("onGameChangedPS");
            invalidate();
        }
    };
    mGame.addOnGameChangeListener(mGameplayListenerPS);
}

2 个答案:

答案 0 :(得分:0)

我了解您想要在mgamePlaceShips对象中使用相同的HitOrMiss对象吗?

您可以这样: BuildGame

public class BuildGame extends View {
    protected final BaseSubClass mGame;
    //...

    public BuildGame(Context context, AttributeSet attrs, BaseSubClass mGame) {
        super(context, attrs);
        this.mGame = mGame;
        initialise();
    }
}

PlaceShips和可比较的HitOrMiss

public class PlaceShips extends BuildGame {
    //...

    public PlaceShips(Context context, AttributeSet attrs, BaseSubClass mGame) {
        super(context, attrs, mGame);
        mGestureDetector = new GestureDetector(context, new MyGestureListener());

        //GameplayListenerStuff
        //...
        mGame.addOnGameChangeListener(mGameplayListenerPS);
    }
}

现在,当您创建新的PlaceShips对象或HitOrMiss对象时,必须给BaseSubClass作为第三个参数。在PlaceShips对象和HitOrMiss对象中拥有相同的mGame:

//...
BaseSubClass mySharedObject = new BaseSubClass(10, 10, BattleshipGameBase.ShipData.CREATOR.newArray(5));
PlaceShips ships = new PlaceShips(getApplicationContext(), myAttributeSet1, mySharedObject);
HitOrMiss hitOrNo = new HitOrMiss(getApplicationContext(), myAttributeSet2, mySharedObject);
//...

答案 1 :(得分:0)

事实证明,使用mGame的setter和getter方法是答案,并且在活动中将HitOrMiss的mGame设置为PlacedShips的mGame。在任何一个子类中都不能这样做。

事实证明,我创建监听器的方式是错误的,这无济于事。