Presentation is loading. Please wait.

Presentation is loading. Please wait.

Android Development Grant

Similar presentations


Presentation on theme: "Android Development Grant"— Presentation transcript:

1 Android Development Grant Hutchison @grant_hutchison

2 Agenda Android Studio IDE Android Framework Views Activities Event handling Hands on activity - Create a single question Quiz Game. Additional Tasks - Multiple Questions, Add a Timer, Leaderboard (second screen), Store Top score with Application (Shared Preferences)

3 Excellent Resource

4 Online Android Resources Android Developer Portal http://developer.android.com Design Develop Distribute

5 Android Studio Android Studio is the official IDE for Android Applications built on IntelliJ IDEA http://developer.android.com/tools/studio/index.html Code Editor Android build system is the toolkit you use to build, test, run and package your apps. Android Virtual Device (AVD) Manager - emulator GitHub integration

6 Getting Started Create a new Project

7 Project Naming

8 Target Platform

9 Activity Type

10 Activity Naming An activity represents a single screen with a user interface. It is an instance of Activity.

11 Layouts control the GUI. Design and Text (XML) modes.

12 Widgets - building blocks of User Interfaces RelativeLayout - container for widgets TextView is used to display text to the user (usually read only).

13 Widget Attributes Widget attributes are set within the XML android:layout_width="" android:layout_height="" match_parent - view will be as large as its parent wrap_content - view will be as large as the content needs android:padding="40dp" - used to add padding around the TextView android:textSize="32sp" - used to set the font size

14 Handling Text Strings TextView and Button Widgets always have the text attribute: android:text="Canada Quiz" Above the value is a hard-coded into the application. To enable localization (translated versions of text) of applications any strings should be maintained outside of the layout file and in a resources file. String resources in a separate XML file in res. Reference them using @string/key_value

15 String Resource References "Canada Quiz" should be located in a resource file and not directly in the XML. Update the res/values/strings.xml Canada Quiz Settings Canada Quiz

16 Where is the Java? Activity Class that extends AppCompatActivity. public class QuizActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.quiz_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); }

17 Goal Change the text to Canada Quiz Center the text on the device Set font to a larger 24 pixel size (sp) Canada Quiz - Stage 1

18 Goal Create a single screen application that asks the user a question about Canada and displays whether they are correct or incorrect. Design Goal Stage 2

19 Define the new widgets in the Layout and Resources TextView - Title TextView- Question Text LinearLayout (Horizontal) Buttons (2) True Button False Button Code to respond to the button click event. Test Stage 2 Tasks

20 Linear Layout LinearLayout inherits from a subclass of View named ViewGroup Used to arrange widgets horizontally or vertically BUTTONS

21 Creating Button objects in your Activity public class MainActivity extends AppCompatActivity { private Button mTrueButton; private Button mFalseButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTrueButton = (Button) findViewById(R.id.btnTrue); mFalseButton = (Button) findViewById(R.id.btnFalse);

22 Adding a Button Listener mTrueButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ // coming soon } }); Anonymous Inner Class

23 Make Toast Toast is a short message that informs the user of something but, doesn't require a user action or response. Toast.makeText(MainActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show();

24 Android Development Part 2

25 Agenda MVC - Model View Controller Updating the Quiz game for multiple questions

26 Quiz Game Our current app has a single question Goal is to introduce a Model class that supports multiple questions.

27 MVC Design Pattern ControllerView Model

28 Model - Embedded in Layout (View)

29 Model Model object maintains the data for the application. Quiz Application Model objects would represent a question and the corresponding answers.

30 View View objects represent the user interface. Quiz Application In Android the View class will involve the Layout and corresponding Widgets (Buttons etc…)

31 Controller Controller objects respond to events and manage the updates to the models. Quiz Application In Android, controller objects could be instances of an Activity.

32 Goal Add a Next Button to obtain a new question Link the True / False button to Question specific answers (multiple questions) Starting skelton code can be found in GitHub https://github.com/mrghutchison/android1 Task 3 - Multiple Questions

33 Add the Model Class - Question Instance variables mTextQuestionID - int id used for unique question text from Array mAnswerTrue - Boolean correct response for the question

34 Android Studio Tip - Generate Getters/Setters Purpose Enable auto-generation of getters and setters. How ? Android Studio File > settings > Editor > Java Add prefix m for fields (instance variables) s for static (class variables)

35 Generate

36 public void setAnswerTrue(boolean answerTrue) { mAnswerTrue = answerTrue; } public void setTextQuestionId(int textQuestionId) { mTextQuestionId = textQuestionId; } public boolean isAnswerTrue() { return mAnswerTrue; } public int getTextQuestionId() { return mTextQuestionId; } MODEL Class is now Complete.

37 View needs to be updated Replace with id

38 View needs to be updated FIXED Update the res/layout/content_quiz.xml

39 View - Add a Next Button Update the res/values/strings.xml

40 Create instance variables for TextView, Question array, Question object and index private TextView mQuestionTextView; private Question[] mQuestions = new Question[] { new Question(R.string.question_can, true), new Question(R.string.question_us, false), new Question(R.string.question_fra, true), new Question(R.string.question_gre, true), new Question(R.string.question_eng, false), }; private int mCurrentIndex=0; private Question mCurrentQuestion= mQuestions[mCurrentIndex]; // initial question

41 Private Helper Methods - Change Text and pick new Question private void setCurrentQuestion(int qIndex){ mCurrentQuestion = mQuestions[qIndex]; } private void updateQuestion(){ mQuestionTextView.setText(mCurrentQuestion.getTextQuestionId()); }

42 Implement - Next Button // show initial question mCurrentIndex = (mCurrentIndex+1)%mQuestions.length; setCurrentQuestion(mCurrentIndex); updateQuestion(); mNextButton = (Button) findViewById(R.id.next_button); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCurrentIndex = (mCurrentIndex+1)%mQuestions.length; setCurrentQuestion(mCurrentIndex); updateQuestion(); } });

43 Modify the Event Listener for TrueButton mTrueButton = (Button) findViewById(R.id.true_button); mTrueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // true button response displayMessage(isCorrectAnswer(mCurrentQuestion, true)); } });

44 Private Helper Methods - Answer/Correct private void displayMessage(boolean isCorrect){ if (isCorrect) { Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(QuizActivity.this, R.string.incorrect_toast, Toast.LENGTH_SHORT).show(); } } private boolean isCorrectAnswer(Question question, boolean pressedTrue){ return question.isAnswerTrue()==pressedTrue; }

45 Android Development Part 3 - Timers

46 Agenda Adding a Timer

47 Quiz Game Our current app has an ArrayList of questions As questions are answered correctly they should be removed from the quiz Add a timer so players can time how long it takes to complete the quiz

48 Goal Add a Start Button to time the Quiz Starting skelton code can be found in GitHub https://github.com/mrghutchison/android1 Grab the version3 branch Task 4 - Add a Timer

49 Hander private Handler customHandler = new Handler(); android.os.Handler A Handler allows you to send and process Messages and Runnable objects.

50 Replace the Next Button with a Start Button startTime = SystemClock.uptimeMillis(); customHandler.postDelayed(updateTimerThread, 0); Strategy Store the startTimed when the user clicks the new Start Button Start a thread to display the current time of the clock (likely in a TextView) android.os.SystemClock uptimeMillis() is counted in milliseconds since the system was booted. Method in our Class that will update the timer display.

51 Runnable Thread private Runnable updateTimerThread = new Runnable() { public void run() { timeInMilliseconds = SystemClock.uptimeMillis() - startTime; int secs = (int) (timeInMilliseconds / 1000); int mins = secs / 60; secs = secs % 60; int milliseconds = (int) (timeInMilliseconds % 1000); mTextTimer.setText("" + mins + ":" + String.format("%02d", secs) + ":" + String.format("%03d", milliseconds)); customHandler.postDelayed(this, 0); } }; Post another message.

52 Stopping the Handler customHandler.removeCallbacks(updateTimerThread);

53 Android Development Part 4 - Images, Logging, and States

54 Agenda Adding image resources Android Logging feature State management Starting a second activity

55 Quiz Game Our current app has a single screen with a working timer. We would now like to add a device level high score screen and add an image to our start button.

56 Icons - Android Design Website (http://design.google.com/icons)http://design.google.com/icons

57 Image Resources Android OS will choose the best image file for the specific device running the app. There are multiple directories required under resources (res) medium to extra-extra-high-density screens A resource ID will be assigned for the image file. Once files have been added to the project we can refer to the images in our layout. In this case we want our play arrow to be associated with the start button.

58 Find your image file resources https://design.google.com/icons/ https://design.google.com/icons/ Unzip the files Change to the Project View Copy the files over under res Switch to Android View

59 Update Button Widget in Layout

60 Dynamic changes to image mStartButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_cancel_black_24dp, 0);

61 Activity State Diagram Methods onCreate() onStart() onResume() onPause() onStop() onDestroy()

62 onCreate(Bundle) Typical actions inflating of all widgets using setContentView(int) setup references to widgets setup listeners for user actions create instances of Model objects

63 Debugging Android Apps Android provides a logging utility that can be used to store application messages to assist with debugging. android.util.Log A system level logging utility. Useful static method ( d for debug ) public static int d (String tag, String msg)

64 Use the debug method to capture state changes private static final String Tag = "CanadaQuiz"; @Override public void onStart() { super.onStart(); Log.d(Tag, "onStart() called"); } @Override public void onPause() { super.onPause(); Log.d(Tag, "onPause() called"); } @Override public void onResume() { super.onResume(); Log.d(Tag, "onResume() called"); } @Override public void onStop() { super.onStop(); Log.d(Tag, "onStop() called"); } @Override public void onDestroy() { super.onDestroy(); Log.d(Tag, "onDestroy() called"); }

65 LogCat tool LAUNCH APP STOPAPP

66 States Entire Lifetime onCreate(Bundle) to onDestroy() Visible Lifetime onStart() to onStop() Foreground Lifetime onResume() to onPause()

67 Starting another Activity The ActivityManager must be called to launch another Activity. An Intent object is sent through the ActivityManager to the other Activity. Data can be returned if needed.

68 Intent An intent is an object that a component can use to communicate with Operating System. Constructor public Intent(Context packageContext, Class cls) Activity Class to be StartedNotifies the ActivityManager which application package the activity class can be found

69 Link the High Score Activity mPostScoreButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent (QuizActivity.this, ScoreActivity.class); startActivity(i); } });

70 Passing Data - Extra with Intent An extra is structured as a key-value pair. public Intent putExtra (String name, Varying DataType) KEY NAME

71 Getting Data as the Activity Starts mTimePlayed = getIntent().getLongExtra(EXTRA_HIGH_SCORE,0); KEY DEFAULT (IF NO VALUE FOR KEY)

72 Saving State using a Bundle Override the Activity method protected void onSaveInstancesState(Bundle outstate) The method is called before onPause(), onStop(), and onDestroy() All View object states are stored in Bundle object. A Bundle is an object that maps string keys to values.


Download ppt "Android Development Grant"

Similar presentations


Ads by Google