1

android newbie here.

My first game involves a custom view, which is going to draw a game board and some scoreboards on the screen. I need to know how many players there are in order to get the number of scoreboards up, and I need this to be in known in the constructor of the custom view, so that appropriate variables are initialised on time.

My current implementation is like this, is this the correct way to get variables into the custom view constructor?...

I instantiate the custom view from my activity like this:

numPlayers=2;
setContentView(R.layout.gamescreen);
mBoardView = (BoardView) findViewById(R.id.board_view);

And in the custom view constructor:

public BoardView(Context context, AttributeSet attrs){
            super(context, attrs);
vNumPlayers = ((GuappsXOMainGame)getContext()).getNumP(); 

That's how I have it now and it seems to work well enough, but is it better to be doing something along the lines of the answer to this question:?

android:how to instantiate my custom view with attributeset constructor

Community
  • 1
  • 1
CptLightning
  • 555
  • 1
  • 8
  • 18

1 Answers1

4

When a custom view (or SurfaceView) is the only view, often in games, then it is very easy to pass parameters like level, players, sound on etc by creating an instance of this view before setContentView(). An example:

MyView myView = new MyView(level, players, soundOn);
setContentView(myView);

In your case, your custom view is instantiated when the layout is created, hence you have to communicate back to the activity object to get the values. This is also possible. I have done this by setting static variables in the activity before calling setContentView(my_layout) then in the constructor for the custom view just say level = MyActivity.level

Or perhaps the way you are doing already where you obtain the instance of the activity and call a public method or variable.

In the link you provided an attribute is "hard-wired" into the XML layout. I don't see the advantage of that, when one can simply enter the value into the custom view class itself as a "final" variable.

Lumis
  • 21,517
  • 8
  • 63
  • 67