Presentation is loading. Please wait.

Presentation is loading. Please wait.

Cosc 4730 Android GUI. Activity Lifecycle An activity has essentially four states: – If an activity in the foreground of the screen (at the top of the.

Similar presentations


Presentation on theme: "Cosc 4730 Android GUI. Activity Lifecycle An activity has essentially four states: – If an activity in the foreground of the screen (at the top of the."— Presentation transcript:

1 cosc 4730 Android GUI

2 Activity Lifecycle An activity has essentially four states: – If an activity in the foreground of the screen (at the top of the stack), it is active or running. – If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations. – If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere. – If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

3 Activities Android OS keeps track of all the Activity objects running by placing them on a Activity Stack. – When a new Activity starts, it is placed on top of the stack. – The previous Activity is now in background. If only partially obscured (say dialog box), only onpause() is called – onResume() called when the user can interact with it again if invisible to the user, then onpause() call, followed by onStop() – OnRestart() called, then onStart() when it becomes visible to the user – Or onDestroy() if the Activity is destroyed

4 GUI and layout To display anything on a android screen, it needs a layout. – This is a basic axiom of a android. An Exception can be a single widget displayed – All of this created in their xml (using eclipse or another xml editor for android). Note this can be done completely in java, but it is very tedious.

5 DroidDraw User Interface (UI) designer/editor for programming the Android Cell Phone Platform DroidDraw standalone executable available: (Mac OS X, Windows, Linux) http://www.droiddraw.org/ – Remember, this a UI designer. It creates the xml file, then add them to the project.

6 Activity and xml The activity “inflates” the xml (the screen layout) and then display it to the screen. The activity is in java and setups all the rest of the pieces of the screen objects Event listeners. – It can also change/modify the screen objects.

7 Hello world example HelloWorld.java package edu.cs4755.HelloWorld; import android.app.Activity; import android.os.Bundle; public class HelloWorld extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } main.xml <LinearLayout xmlns:android="http://schemas.android.co m/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World!" /> App displays:

8 xml Basic xml layout (one button displayed) <Button android:text="" android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="fill_parent"> fill_parent uses all available space, wrap_content uses only as much space as is needed. id is what we need to find it with the java later. text would be the default text, in this case, nothing.

9 xml picture example <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/phone"> src access the drawable directory for a static picture, named phone. – Note this will only use as much of the screen as needed, because of wrap_content.

10 xml and widgets. Most widgets can be almost completely configured via xml instead of using java. This means the java can in many ways, be used only for the events, instead of dealing with display issues. Example: EditText – android:autoText boolean, use automatic spelling – android:capitalize boolean, Cap the first letter of the text entered – android:digits, accept only digits – android:singleLine, allow multi or single line input.

11 Layout "managers" Most of the time you need more then one widget. So you use a layout to control how the widgets are shown on the screen. LinearLayout is very simple <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> Orientation controls placement of the next widget: – vertical: next line – horizontal: to the right of the previous widget Normally you use several layouts to control how everything is displayed.

12 multiple Layout example For presentation reasons lots of info was left off. <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">

13 Layout Settings Weight – If using Fill_parent, then each Widget can use Layout_Weight – This determines, which gets more space – Setting them all to 1, means they share the space equally. – Setting widget1 to 1 and widget2 to 2, means widget2 gets twice as much space as widget1

14 Layout Settings (2) Gravity – A nice way of saying alignment, which is flush on the left side of the screen – Layout_gravity: (Vertical) left (default) flush on the left side of the screen center_horizontal center right is flush on the right side of the screen. – Horizontal layout Center_vertical Center vertical, instead of on the "baseline" (bottom).

15 Layout Settings (3) Padding – how much in pixels space between the widget and the side of the screen/next widget – android:padding="15dp" is about 15 “pixels” all around – Also paddingLeft, paddingRight, paddingTop, and paddingBottom

16 Relative Layout More complex and widgets placed based on the previously placed widgets – Except the first one (no other widget yet) – layout_above, layout_below, layout_toLeftOf, layout_toRightOf – With the above, these can be used layout_alignTop, layout_alignBottom, layout_alignLeft, layout_alignRight, layout_alignBaseline Or placed relative to the container itself – layout_alignParentTop, layout_ParentBottom, layout_alignParentLeft, layout_parentRight, layout_centerHorizontal, layout_centerVertical, layout_CenterInParent Settings are placed in the Widgets

17 Relative Example <TextView android:text="Some Text " android:id="@+id/TextView01" android:layout_alignParentBottom="true" > <Button android:text="alert" android:id="@+id/Button01" android:layout_above="@id/TextView01" > NOTE : Button uses @id/TextView01, no + sign. + sign only needed for the id, when referencing it somewhere, just @id/name

18 Other Layouts TableLayout works like html tables (with all the complications like spanning rows) – TableRow is used with it for row layouts Scrollwork is just like linearLayout, except you get a scrollbars as needed. absoluteLayout every is placed on the screen by setting the x and y pixels position

19 Screen Size and layouts. In the android directories, there is a res/ – drawable/ This deals with the screen density of pixels. – The configuration qualifiers you can use for density-specific resources are ldpi (low), mdpi (medium which is the baseline), hdpi (high), and xhdpi (extra high). For example, bitmaps for high-density screens should go in drawable-hdpi/.

20 Screen Size and layouts. Scaling: medium is the baseline – Small = mdpi*.75, high=mdpi*1.5 and xhigh=mdpi*2.0 Pixels: Small=36, medium=48, high=72, and xhigh=96 For density there are to more – nodpi Resources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen's density. – tvdpi Which is for TVs and google’s own doc’s say not to use it and use xhdpi instead. Except the new Nexus 7” tablet is a tvdpi device. – 1.33*mdpi or 100px image should be 133px

21 Screen Size and layouts. (2) – layout/ This is deals with the screen size. Layout/ is the default and the only one eclipse creates (or understands directly) We can have small (~ 426dp x 320dp), normal (470dp x 320 dp) which is the baseline, large (640dp x 480dp), and xlarge (960dp x 720dp) – We can also add land (landscape) and port (portrait) orientation. res/layout/my_layout.xml // layout for normal screen size ("default") res/layout-small/my_layout.xml // layout for small screen size res/layout-large/my_layout.xml // layout for large screen size res/layout-xlarge/my_layout.xml // layout for extra large screen size res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

22 Screen Size and layouts. (3) In v3.2 (api 13), the size groups are deprecated for a new method. This is the problem: 7” tablet is actually in the 5” phone group, which is the large group. – Provides a smallestWidth (independent of orientation) and Width (which is also takes into account orientation) – layout-sw dp and layout-w dp Where N is the denisty of pixels.

23 Screen Size and layouts. (4) Typical configuration: – 320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc). – 480dp: a tweener tablet like the Streak (480x800 mdpi). – 600dp: a 7” tablet (600x1024 mdpi). – 720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc). Smallest width (no orientation) res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger) res/layout-sw720dp/main_activity.xml # For 10” tablets (720dp wide and bigger) Using just width and taking orientation into account res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-w600dp/main_activity.xml # Multi-pane (any screen with 600dp available width or more) More information: http://developer.android.com/guide/practices/screens_support.html http://developer.android.com/guide/practices/screens_support.html There are two examples ScreenTest1.zip and ScreenTest2.zip to play with.

24 Widgets android.widget – The widget package contains (mostly visual) UI elements to use on your Application screen. Includes the layouts as well. – To create your own widgets, extend or subclass View. package: android.View Examples: – TextView, EditText, ProgressBar and SeekBar, Button, RaidoButton, CheckButton, ImageView, and Spinner This will cover only the basics, since every widget has many attributes. – Listeners will be listed.

25 TextView Displays text to the user and optionally allows them to edit it. – A TextView is a complete text editor, however the basic class is configured to not allow editing see EditText for a subclass that configures the text view for editing.

26 Interacting with the widgets HelloWorld.java package edu.cs4755.HelloWorld; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloWorld extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView myView; myView = (TextView) findViewById( R.id.textview); myView.setText("Hello World 2!"); } main.xml <LinearLayout xmlns:android="http://schemas.android.co m/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World!“ android:id="@+id/textview" /> create a variable and use the id to find it

27 EditText EditText inherits from TextView – This is a method to get input. Has several subclasses, autocompeteTextView and ExtractEditText For a listener, implement the TextWatcher – and use EditText.addTextChangedLister( TextWatcher) – Override three methods void afterTextChanged(Editable s) – This method is called to notify you that, somewhere within s, the text has been changed. void beforeTextChanged(CharSequence s, int start, int count, int after) – This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after. void onTextChanged(CharSequence s, int start, int before, int count) – This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before.

28 Toast A toast is a view containing a quick little message for the user – When the view is shown to the user, appears as a floating view over the application. It will never receive – Also very handy for debugging. Example: – Toast.makeText(getApplicationContext(), “Hi!", Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT or Toast.LENGTH_LONG is how long the message will show on the screen.

29 Button inherits from TextView represents a push-button widget implement Button.OnClickListener to listener for the push/click. – button.setOnClickListener(View.OnClickListener) – Override void onClick(View v) – Called when a view has been clicked.

30 RadioButton Inherits from CompoundButton (which inherits from Button) – RadioButtons are normally used together in a RadioGroup – RadioGroup is used to create multiple-exclusion scope for a set of radio buttons Also a Layout, which uses the same attributes as LinearLayout

31 RadioGroup Listener for RadioGroup – implement RadioGroup.OnCheckedChangeListener radioGroup.setOnCheckedChangeListener( ) – Override void onCheckedChanged(RadioGroup group, int checkedId) Called when the checked radio button has changed. CheckedId is RadioButton that was checked. clearCheck() clear the selection check(int id) sets a selection for the id – example id like R.id.RadioButton02

32 CheckBox A checkbox is a specific type of two-states button – can be either checked or unchecked – if (checkBox.isChecked()) { checkBox.setChecked(false); } – Listener implement CompoundButton.OnCheckedChangeListener CheckBox.setOnCheckedChangeListener(CompoundButton.O nCheckedChangeListener listener) – Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)

33 ToggleButton Like a checkbox or radio button Displays checked/unchecked states as a button with a "light" indicator and by default accompanied with the text "ON" or "OFF". – Two states: On and Off On shows a green button (default behavior) Off shows a grayed out button (default behavior)

34 ImageView To set a static image, this can be setup in xml using – android:src="@drawable/phone" Where phone is the png image in the drawable directory of the project. A bitmap can be setup using SetImageBitmap(Bitmap) method Drawable getDrawable() method gives you access to the image, where you can use the draw(Canvas ) method to change/draw on the image.

35 Graphics: Bitmap and Canvas android.graphics package – A simple way to some animation or “drawing on the screen” is to use a “blank” ImageView ImageView eImage = (ImageView) findViewById(R.id.eImage); Bitmap eBitmap= eBitmap = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888); Canvas eCanvas = new Canvas(eBitmap); //eCanvas has the graphics draw tools to write on the bitmap eCanvas.drawColor(Color.WHITE); //white screen Paint black = new Paint(Color.BLACK); //black paintbrush eCanvas.drawRect(0,0,x, y, black); eImage.setImageBitmap(eBitmap); eImage.invalidate(); //redraw the ImageView with new picture.

36 ImageButton inherits from ImageView In xml can set the images <item android:state_pressed="true" android:drawable="@drawable/button_pressed" /> <item android:state_focused="true" android:drawable="@drawable/button_focused" /> android:drawable="@drawable/button_normal" /> Uses the listener like the button. View.onClickListener

37 Progress Bar A ProgressBar is like a gauge. – The bar can look in one of 4 ways, set in the style tag – android:progressBarStyle This is a medium circular progress bar – android:progressBarStyleHorizontal This is a horizontal progress bar. – android:progressBarStyleLarge This is a large circular progress bar. – android:progressBarStyleSmall This is a large circular progress bar. – The format looks like this: style="?android:attr/progressBarStyleHorizontal">

38 Progress Bar (2) SetMax(int m) uses to set the bar from 0.. m – Need to call this when it is setup in java – No setmin, zero is always the min. setProgress(int p) sets to a specific progress p int getProgress() returns the current level incrementProgressBy(int d) increments the progress by d.

39 SeekBar SeekBar is inherits ProgressBar and is touchable/ interactive. Otherwise it is the same as ProgressBar – Add a listener SeekBar.OnSeekBarChangeListener seekBar.onClickListener to add the listener – Must override 3 methods – public void onStartTrackingTouch (SeekBar seekBar) Use of a touch gesture – public void onStopTrackingTouch (SeekBar seekBar) touch gesture ended – public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) The seekBar has changed and it's progress fromUser is true if a user changed it

40 ArrayAdapter When we lists some type of "list" displayed, it uses an ArrayAdapter, which also needs a simple layout provided by android (don't need to create this layouts, unless you want to) – andriod.R.layout.X for the layouts. http://developer.android.com/intl/zh- CN/reference/android/R.layout.html for the full list. – This can be override to make very fancy views, with say icons and text, clickable ratings and text, etc…

41 Spinner A spinner needs "items" to fill the drop down box. This is done using an ArrayAdapter – Using a string[] items, we can – ArrayAdapter adapter = new ArrayAdapter (this,android.R.layout.simple_spinne r_item, items); – adapter.setDropDownViewResource(android.R.layout.simp le_spinner_dropdown_item); – Then use setAdapter(adapter); //fills the list – Add listener, setOnItemSelectedListener(this) implement AdapterView.OnItemSelectedListener – public void onItemSelected(AdapterView parent, View view, int position, long id) – public void onNothingSelected(AdapterView parent)

42 Spinner (2) If instead, use an xml file with values – res/values/ – Stuff Stuff2 Change Adapter line to – ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.spinnerstuff, android.R.layout.simple_spinner_item);

43 DatePickerDialog DatePicker is a builtin dialog to pick a the date – TimePickerDialog picks the time – Also a ColorPickerDialog in the GraphicsActivity

44 DatePickerDialog (2) Calling the Dialog – constructor DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) – Example: Calendar dateAndTime = Calendar.getInstance(); new DatePickerDialog(FormExample.this, d, //d is the listener dateAndTime.get(Calendar.YEAR), dateAndTime.get(Calendar.MONTH), dateAndTime.get(Calendar.DAY_OF_MONTH) ).show();

45 DatePickerDialog (2) listener: – in previous example assumed a declared listener, – if implemented, change d to this. declared listener d = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { dateAndTime.set(Calendar.YEAR, year); dateAndTime.set(Calendar.MONTH, monthOfYear); dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth); } };

46 Dialog To create your own dialog, you first need a R.layout.name for it. So create an xml file for it dialog = new Dialog(this) dialog.setContentView(R.layout.name); dialog.setTitle("Whatever"); – Deal with any widgets in the dialog as well To show the dialog – dialog.show(); To remove it – dialog.dismiss();

47 Threads and widgets Only the original thread that created a view hierarchy can touch its view. – So you can't change widgets on threads you create! – To get around the problem, you need a handler specially a message handler. import android.os.Handler; import android.os.Message; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0) { tvok.setText("Process done"); //Change the dialog textview. } }; // in the thread, (assuming handler is accessible to it) you can then send a message with handler.sendEmptyMessage(0); //where 0 is a message

48 Rotation To stop the auto rotation edit the AndroidManifest.xml In the <activity section android:screenOrientation= – portrait – landscape – Sensor (use accelerometers) appears to disable keyboard trigger events for slide keyboards This is per activity, so if you have more then 1 activity, it each can have their own orientation.

49 AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cosc4755.TCPclient" android:versionCode="1" android:versionName="1.0"> <activity android:name=".TCPclient" android:label="@string/app_name"> android:screenOrientation="portrait"

50 Launching a new Activity Using startActivity(), which takes a single parameter, an Intent – The new Activity will be placed on top of the Activity stack. – Example: startActivity(new Intent(getApplicationContext(), Next.class)); – To pass data to the activity, use putExtra with the Intent Intent myIntent = new Intent (getApplicationContext(), Next.class); myIntent.putExtra("StringData", "stuff"); myIntent.putExtra("BooleanData", true); startActivity(myIntent); To retrieve the data stored in a Bundle Object keys are prefixed by the package name, like edu.cs4730.ActivityDemo. StringData – Intent intent = getIntent(); – String data = intent.getStringExtra("edu.cs4730.ActivityDemo.StringData");

51 Launching a new Activity (2) AndroidManifest.xml file – Each new Activity must be registered in your manifest file – Inside the section You can also add intent-filter as well if you want specify different types of intents that can launch this Activity

52 Launching Other Activities You can launch Activities that don't belong to you application – Uri number = Uri.parse(tel:5555551212); – Intent dial = new Intent(Intent.ACTION_DIAL, number); – startActivity(dial); – More intents android and 3 rd party can be found here http://developer.android.com/intl/zh-CN/guide/appendix/g- app-intents.html http://www.openintents.org/en/intentstable

53 Services and Broadcast Receivers As you will see in android sms lecture, an Activity can be launched by a using Receivers – With sms, when a new sms message was receive the activity was launched to deal with the message. – The activity can be invisible to the users as it was with sms demo or launch as activity screen.

54 Notification status bar The notification system can also be used to launch a Activity (with user action). – Uses the Intent method again, to choose which Activity in your application is to launched. – See the Status Notification lecture for more details.

55 Get a result from an Activity You can use startActivityForResult(intent, int Request_code) to have an activity return information to call the calling activity. – Request is a integer number. You should attempt to kept the request code to each different activity unique but not required. – You then listen for results via the void onActivityResult(int requestCode, int resultCode, Intent data){ } – The requestCode is use to figure out which Activity has returned. ResultCode will be RESULT_CANCELED, if the activity didn't return anything or crashed.

56 Returning a result Using a intent and finish() the activity can return a result Intent myIntent = new Intent (getApplicationContext(), null); myIntent.putExtra("StringData", "stuff"); myIntent.putExtra("BooleanData", true); setResult(RESULT_OK, myIntent); – setResult( int resultCode, Intent Data) finish();

57 Closing activities There are a number of a ways for an Activity to close. – The primary method for an Activity to close is to call finish() This notifies the OS that this Activity is done (but not necessary the application If an activity called another and wants to be removed from the stack, it should call finish()

58 Closing activities (2) If you launched an Activity with startActivityForResult() and you want to end it, finishActivity(requestCode) will finish any activity with that requestCode

59 More? Android has a number of methods and call backs from activities and child activities – see the developers guide in the class android.app.activity to see more. And there are subclasses of activity as well – AccountAuthenticatorActivity Base class for implementing an Activity that is used to help implement an AbstractAccountAuthenticator. – ActivityGroup A screen that contains and runs multiple embedded activities. – AliasActivity Stub activity that launches another activity (and then finishes itself) based on information in its component's manifest meta-data. – ExpandableListActivity An activity that displays an expandable list of items by binding to a data source implementing the ExpandableListAdapter, and exposes event handlers when the user selects an item. – ListActivity An activity that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item. Known Indirect Subclasses LauncherActivity, PreferenceActivity, TabActivity

60 References See the FormExampleA.zip on the handout pages for source code. For a full list of xml and methods, see the developer guide, because I skipped a lot of information – Some information was also taken from the text Beginning Android 2, Apress, Mark L. Murphy, 2010

61 Q A &


Download ppt "Cosc 4730 Android GUI. Activity Lifecycle An activity has essentially four states: – If an activity in the foreground of the screen (at the top of the."

Similar presentations


Ads by Google