Friday, September 18, 2015

App a Day 4: Dice

Classes used: GridView, BaseAdapter, PreferenceActivity, Intent.

This one was a hair ripper. This isn't even true to my original concept and I came up with it for day 2. As you know I worked out only ONE die. However it's close enough.

It's basically what you get from this guide on GridViews, plus the roll button and a PreferencesActivity so I can alter the number of dice.

To get a PreferencesActivity started via the action menu bar I needed a menu layout and a preferences screen layout. I'll leave out the menu xml since it's auto-generated every time you start an android project.

And that other part that auto-generated by Android Studio every time I start a project? That's where the intent goes to open SettingsActivity

Go to the repo and look at the settings activity. It's simply an activity which overrides onCreate which is going to take the xml file above and make a preference screen with it. But it is also an OnPreferenceChangeListener so when things get changed it tells itself (really) to update the preference summary to the new value. I'll use the listener again in the adapter.

Finally I need an adapter. Adapters are objects that manage data or objects for views that display repetitive structured information, so in this case a GridView. The GridView displays some data in the same way over and over again in specific pattern but the data changes with each grid cell. The adapter is going to make sure the right data get to the right cell.

This adapter is an extension of BaseAdapter. Basically the GridView, as it attempts to draw itself, tells the adapter, "Give me what I need to draw for cell 0." By calling the adapter's getView method and passing the position number to it. I override the getView method so it returns an ImageView with the correct configuration and image. In this case an ImageView displaying the face of a die.

Another important part for this implementation is the array that the adapter uses called mArray. This is not a standard feature of BaseAdapter, but necessary for this case. I made the adapter into a listener for preference changes. Every time the preference for dice count is changed I reset the array to one of the new size filled with all -1.

Finally back in the MainActivity class whenever you roll the dice, change the array in adapter to the new number. I do this by making it public but you could also use getItem if you're using a reference to an actual object. When the number's changed call mAdapter.notifyDataSetChanged and that will call getView again and redraw the views, thus setting them to the correct face image.

I hope this was educational. Good night.

No comments:

Post a Comment