440 likes | 452 Views
Learn about building UI interfaces using View and ViewGroup objects and understand the lifecycle of an Android activity.
E N D
User Interface • The UI for an Android app is built using a hierarchy of View and ViewGroup objects. • View objects are usually UI widgets such as buttons or textfields • ViewGroup objects are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.
Activity • An Activity is the main object in an Android app. • Lifecycle:
Activity Created • Redefine onCreate() • Good time to • Define the interface with setContentView() • Initialize any parts of the interface, including callback assignments • Start any necessary threads/services (more on this later)
Activity Started • Created activities are also started • Redefine onStart() • Good time to • Read preferences • Probe resources
Resume an Activity • This means the activity has been pulled to the foreground and the user can interact with it. • New activities are also resumed. • Define onResume() to do something if necessary • Good time to • Check any indicators (e.g. email) and refresh user interface items • Obtain system resources (e.g. camera)
Activity Paused • Redefine onPause() • Activity is obscured • Good time to • Reset user interface indicators • Pause any realtime actions • Release system resources (e.g. camera)
Activity Stopped • Redefine onStop() • Activity is completely hidden and considered to be in the background • onPause() is called first • Good time to act as if process terminated • Write user data • Write preferences • Act like the app is shut down
Activity Restarted • Redefine onRestart() • Activity is resurrected • Good time to act as if process were created • Refresh user data and preferences • Refresh the interface
Activity Destroyed • Redefine onDestroy() • Activity is completely removed from the system • Good time to • Reset system components
Example: Rotation • Rotation causes a number of events to take place: • App is stopped: pause, then stop(save state) • App is restarted: restart, then resumed(reinstate state)
Dialogs • To display dialog boxes, do two things: • Define onCreateDialog() and pay attention to the parameter. Create a dialog box and return it. • Call showDialog() with an integer to indicate which dialog you want.
Menus • Override the onCreateOptions() call • Example: public booleanonCreateOptionsMenu(Menu menu) { MenuInflaterinflater = getMenuInflater(); inflater.inflate(R.menu.opening_menu, menu); return true; }
Menus • Define your menu in XML spec file <menu> <item android:id="@+id/opening_menu_new_item" android:icon="@drawable/ic_menu_sun" android:title="New" /> <item android:id="@+id/opening_menu_import_item" android:icon="@drawable/ic_menu_filter" android:title="Import"> </item>
Response to Menu Events • Redefine onOptionsItemSelected() publicbooleanonOptionsItemSelected(MenuItem item){ switch (item.getItemId()) { case R.id.item1: return true; case R.id.item2: startActivity(new Intent(getApplicationContext(),ActivityTwo.class)); return true; default: return super.onContextItemSelected(item); 12: } 13: }
Other Programmable Events • Examples • onPrepareDialog() before onCreateDialog() • onCreateContextMenu() for popup menus • onContextItemSelected() for popup menu items selected • onCreateOptionsMenu() to create menus • onOptionsItemSelected() from other menus • Etc…etc…etc…
Starting New Activities • A common action for an activity is to start another activity. • When another activity is started, the current activity is stopped and the new activity is created/started/resumed.
Starting New Activities: Intents • Intents are communications about classes or executables or data • Example: communicate which activity to start by creating an intent that indicates the class to use
Starting New Activities • Two ways to start an activity • To start an independent activity that will run, use startActivity() • To start an activity that will return information to the current activity, use startActivityForResult() • Both calls use intents to indicate which activity should start up
startActivity() Uri smsUri = Uri.parse("tel:"+grades.getStudent(itemPosition). getMobilePhoneNumber()); Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsUri); sendIntent.putExtra("address", grades.getStudent(itemPosition).getMobilePhoneNumber()); sendIntent.putExtra("sms_body", "type message here"); sendIntent.setType("vnd.android-dir/mms-sms"); startActivity(sendIntent);
startActivityForResult() • Using this call, one gives the intent AND a returning value that identifies the activity. • When the Activity is completed, the method onActivityResult() is called.
startActivityForResult() Intent gameIntent = new Intent(this, GameDisplay.class); startActivityForResult( gameIntent, R.id.class_display_games);
startActivityForResult() protected void onActivityResult( int requestCode, int resultCode, Intent intent) { super.onActivityResult( requestCode, resultCode, intent); if (resultCode != RESULT_OK) return; if (intent != null) { if (requestCode == R.id.class_display_games) { … } } }
Returning From an Activity • To halt an Activity, call finish() • To return to the Activity that created the current Activity, call setResult():setResult(RESULT_OK, result); • This means automatic return with the ID that it was created with.
Information in Intents • You can insert information into an intent to communicate with the activity that is being started. • The typical way is to • Create a Bundle • Put things into the Bundle • Add the Bundle to the Intent through putExtras()
Retrieving Information • Use the getIntent() call to retrieve the Intent • Use the get…() call to get the extra you are looking for
Better Ways to Organize the Code • There are several times when the code is organized around an integer return value. • onCreateDialog() • onOptionsItemSelected() • onActivityResult() • This results in a string of “if…then…else” code that just stinks.
Better Ways to Organize the Code • Use a table of classes. Do a table lookup of the code and Java reflection to call the right class.
Files • Files are done "normally" from the Java perspective • The location of files is not normal • Because of security, "file space" is buried deep in the Android file system.
Open local file FileInputStream classFile = openFileInput("ClassLocations"); … classFile.close(); FileOutputStream file = openFileOutput("ClassLocations"); … file.close();
Open Local File • Do not open an absolute path name unless you know where your app is stored. • Can get the path asString f = getFilesDir().getAbsolutePath();
Open online file DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httppost = new HttpGet("http://www.urlOfThePageYouWantToRead.nl/text.txt"); HttpResponse response = httpclient.execute(httppost); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); InputStream is = buf.getContent(); BufferedReader r = new BufferedReader(new InputStreamReader(is));