A switch statement gives you the option to test for a range of values for your variables. They can be used instead of long, complex if-then-else if statements
2. Add the below code in the onCreate method. The evaluated variable can be an int, short, byte, or char. It can’t be a long or a floating-point type. Starting in JDK 7, strings are allowed to be used with a switch statement. Note: A case ends in a colon (:) not a semi-colon. A break is necessary or the code will continue to fall through the switch and run. The default clause is optional. If a case has a return, then the break is not necessary for that case.
switch(myInteger) {
case 1:
\\Enter code for value1 condition here; To test, you could Add a Toast
break;
case 2:
\\Enter code for value2 condition here; To test, you could Add a Toast
break;
case 3:
\\Enter code for value3 condition here; To test, you could Add a Toast
break;
default:
\\Enter code in the event that that no cases match. To test, you could Add a Toast
}
3. Compile and run!
Resources:
http://lecturesnippets.com/android-switch-case-statements/
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
http://www.homeandlearn.co.uk/java/java_switch_statements.html
Similar to a select case in other languages.
Popular Posts
- Cursor getColumnIndex - Get the Index for a Column Name
- Solution: error: Error parsing XML: unbound prefix
- Save LogCat to a Text File
- android:ellipsize - Add an ellipsis(...) in a TextView
- Intent setType(String type) - How to Set an Explicit MIME data type
- Change the line spacing between lines of text in an TextView/EditText, using lineSpacingMultiplier
- android:ems
- android:alpha - Set the Opacity/Transparency of Text in TextView/EditText
- android:gravity - Move Text inside a EditText (center, top, bottom, right, left, and more)
- setVisibility() - Hide a Button, in Java