I am learning Android by implementing a clone of Mastermind. I want to break up the screen (or View) into three parts: the board with the users guesses so far and feedback, a series of control buttons, and a series of buttons to pick the color of the next peg.
My instinct is to do this is a modular way. The layout files uses nested LinearLayouts (I know not the most efficient thing to do, but this is an educational experience.)
The "board" is a custom View where I do a lot of drawing with a Canvas. The buttons on the bottom are declared in the layout file. Notice the or开发者_Go百科ange strip to the right?
Right now that is another custom View. I want to add a variable number of buttons to that custom View based on the number of colors the player can choose from. A button press would select the color for the next peg in the player's guess. (There are 3 versions of the game, easy, medium, and hard each with a different number of colors.)
So, how do I add a variable number of buttons to the custom View I am creating? Or am I approaching this in the wrong way? Should I use a prebuilt layout? If so, which one and how could I dynamically change the number of buttons in the layout?
Thanks for any help. Cheers!
You can do this in two ways:
- Using a predefined layout and setting initially the property "visibility" of all the buttons to "gone", then programatically you can set the "visibility" of the buttons you need to "visible". The "gone" property makes the button invisible and also not consumes space in the layout.
- Adding dinamically buttons to the main layout, first you will have to create or "inflate" them.
The second options is more powerful, but also more difficult if you are learning.
精彩评论