Ilham on Android: Developing The Functions (Part 2)
— posted on January 20, 2015 10:00 AM
Share this to
We will continue from what we learnt and developed in the previous post. We already have the app running, with a simple interface, but yet to perform the BMI calculations.
Main ActivityOpen up the MainActivity.java file, which will contain the codes to control our interface. The file, which was generated by the wizard, currently contains three methods:
- onCreate: This function will be called when the activity is first created. We usually will initialise things, setup variables, or bind views here.
- onCreateOptionMenu: This function will be called to setup the settings menu. This menu is opened when the setting button is pressed, or the three-dots "overflow" button is pressed.
- onOptionsItemSelected: This function will be called when the items in the menu is pressed.
The BMI FormulaLet prepare the BMI formula as a function. https://gist.github.com/i906/4ef0798b87d09a86cb04 Now we need to get inputs and show the results. Typically, there would be a "Calculate" button. To make it simple, I want the results is automatically shown the users as the input is keyed in. So, we need to know when the EditText contents changes. To do this, we need to add a text change listener to both of the weight and height inputs. https://gist.github.com/i906/7dff9d6ecded61f33812 In the performCalculations method, I've put the codes to retrieve the inputs' contents using getText function. Also there are Log functions for logging purposes. You will and should utilise this throughout any Android developments. All error, messages pertaining to the app will appear in the LogCat panel. Sometimes there are users feel cumbersome trying to convert between meters and centimeters. The phone is powerful enough to calculate that, allow the app to that for the users. The tallest man in the world is around 2.5 meters, so lets assume if the user's input is more than 3 meters, it might be in centimeters. If it is less than that, it should be in meters. There will be sometime the BMI results will be unrealistic since it is always updated upon input. To make this nicer, we simply put the results as "less than 15" or "more than 40", as the numbers in the other ranges are probably not useful anyway. Finally, we put appropriate messages depending on the BMI results.
Conclusion[caption id="attachment_5957" align="aligncenter" width="400"] We can see that someone with that height and weight is underweight. :/[/caption] We should have a fully functional BMI calculator app upon completing this tutorial. In the next post, we can try out some libraries and store the BMI results. The codes for this part also can be found in this repository. As always, thanks for reading. Feel free to leave comments or questions!
Share this to