1 / 50

Java OOP for Android

Java OOP for Android. Part 1: OOP Introduction Part 2: OOP for Android. Part 1: OOP Introduction. Java OOP. Java with Android API is a Object-oriented programming(OOP) language for Android based mobile application development.

Télécharger la présentation

Java OOP for Android

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java OOP for Android Part 1: OOP Introduction Part 2: OOP for Android

  2. Part 1: OOP Introduction

  3. Java OOP • Java with Android API is a Object-oriented programming(OOP) language for Android based mobile application development. • An object-Oriented Programming encapsulates attributes and behaviors in objects. • In addition, OOP also support inheritance and polymorphism.

  4. Encapsulation of Class and Object Objects and Classes • Object-oriented language describes a entity/objects binding its data(state), and operations(behavior) on that data. • The data is encapsulated by its operations, i.e the data can only be accessed by the methods of this object of the class. • A class is a kind of type which defines the template of fields (data) and methods (operation) t from which a instance(object) is constructed. • Here is the definition of a very, very simple class with one field, count, and one method, inc()

  5. Encapsulation of Class and Object publicclassCounter { /** a field: its scope is the entire class */ privatelongcount; /** Modify the field. */ publicvoid inc() { count++; } }

  6. Object Creation • A new object, an instance of some class, is created by using the new keyword: Counter counter1 = new Counter(); • On the left side of the assignment operator “=”, this statement defines a reference variable, named counter1. • This reference variable has a type, Counter, so it can only point to a object of Counter. • The right side of the assignment, the class Counter default constructor allocates memory for a new instance of the Counter class and initializes the instance. • The assignment operator assigns a reference to the newly created object to the variable.

  7. Inheritance • A type may inherit from other types. A class that inherits from another is said to subtype/subclass of its parent type/class. • The parent class is called the supertype/superclass. A superclass may have several different subclasses and it is called the base type for those subclasses. • Both methods and fields within the superclass may be visible from its subclass unless they have private visibility scope. • The relation from a subclass to its superclass is a “is a” relationship (specialization/generalization) just as a graduate is a student and a undergraduate student is a student. • Both under- or graduate students have a common properties of a student, and in addition, they have their own special features.

  8. Inheritance • Inheritance represents such hierarchical relationship between classes(entities) in which one class inherits attributes and behaviors from at least one other category. • More examples, dog/cat inherits from animal (dog or cat is a kind of animal), car/track inherits from vehicle (car/track is a kind of vehicle), and circle/triangle/square inherits from shape (they are kinds of shape). • Animal, vehicle, and shape are more generic class; and tiger, car, and circle are more specific class.

  9. Interface Inheritance • Java provides the reserved word extends for specifying a hierarchical relationship between two classes. • For example, suppose you have a Student class and want to introduce a undergraduate student class as a kind of Student. • Relating two classes via extends

  10. Interface Inheritance class Student { // member declarations } classUnderGraduateStudentextends Student { // member declarations }

  11. Interface Inheritance • Explanation: – UnderGraduateStudent is the class being defined – extendsindicates that UnderGraduateStudent is an extension of another class – Student is the name of the pre-defined class being extended by UnderGraduateStudent

  12. Polymorphism • Polymorphism is the ability to have behavior at runtime. • Polymorphism is implemented by late binding at run time in Java. • Two major forms of Polymorphism are • Parametric • Subtype

  13. Parametric • Parametric: Parametric polymorphism in Java is supported by generic which allows a function or a data type to be written generically, so that it can handle values identically without depending on their type. • Collection classes are written using Generic Type which allows Collections to hold any type of object in run time without any change in code and this has been achieved by passing actual Type as parameter. • The following example shows a parametrized list data type and two parametrically polymorphic functions on them:

  14. Parametric class List<T> { class Node<T> { T elem; Node<T> next; } Node<T> head; int length() { … } }

  15. Parametric • Any parametrically polymorph function is necessarily restricted in what it can do, working on the shape of the data instead of its value, leading to the concept of parametricity.

  16. Subtype • Objects of a same type can have different behavior when subtypes of a given class are assigned to a variable of the base class type. • When a subclass instance is used in a superclass context, executing a supertype method on the subclass instance will actually execute the subclass’s version of that operation. • For example, suppose that Dog and Cat are subclass of class Animal, and that both classes contain a eat() method inherited from class Animal.

  17. Subtype • Assigning a Dog instance to a variable of type Animal, Animal myAnimal = new Dog(); myAnimal.eat(); //eat method of Dog class Animal myAnimal = new Cat(); myAnimal.eat();//eat method of Cat class • You can see the statements in line 2 and 4 above that the same statement results in different methods executions at run time. • The following example shows three classes – Shape <- Rectangle <- RoundedRectangle – with linear inheritance relationship:

  18. Interfaces • An interface in Java is a protocol or contract. • A class can implement multiple interfaces and override the abstract methods declared in the interface. • A interface is a kind of abstract class type without implementation.

  19. Interfaces • An interface’s fields are constant and must be initialized. • An interface’s methods are implicitly declared public and abstract. • The Handler identifies a type that specifies what to do (act something) but not how to do it. • Implementation details are left up to classes that implement this interface. • Instances of such classes should know how to act themselves.

  20. Declaring Interfaces • Declaring a Handler interface publicinterface Handler { inttimeout=60; void action(int x); }

  21. Implementing the Handler interface classMyhandlerimplements Handler { privateintx; voidMyHandler(int x) { this.x = x; } intgetX() { returnx; } @Overridepublicvoid action(int x) { x++; System.out.println("new x is" + x ); } }

  22. Part 2: OOP for Android

  23. Introduction to Android • Android is a software stack for mobile devices that includes an operating system, middleware and key applications. • The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

  24. Directories and Files •Project ◦src ◦gen ◦Android [Version] ◦assets ◦res ▪drawable-hdpi ▪drawable-ldpi ▪drawable-mdpi ▪layout ▪menu ▪values

  25. File: AndroidManifest.xml Configure the application: Versioning, icon, initialize activities, configure permissions <?xmlversion="1.0"encoding="utf-8"?> <manifestxmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0"package="android.dodgeball"> <uses-sdkandroid:minSdkVersion="8"/> <applicationandroid:icon="@drawable/icon"android:label="@string/app_name"> <activityandroid:name="android.dodgeball.DodgeBallActivity" android:label="@string/app_name"> <intent-filter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>

  26. File: AndroidManifest.xml Setup w/o coding Manifest Application Permissions Instrumentation

  27. Directory: src Application source code

  28. Directory: res/drawable-* • Image files • Drawable-hdpi: high resolution • Drawable-mdpi: medium resolution • Drawable-ldpi: low resolution • Coding in .java file: • Setup in .xml file: mBitmap = BitmapFactory.decodeResource(res, R.drawable.icon); canvas.drawBitmap(mBitmap, mX, mY, null); <ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/icon"android:id="@+id/imageView1"></ImageView>

  29. Directory: res/layout • UI definitions • Layouts • Widgets <?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent"android:layout_height="fill_parent" android:orientation="vertical"> <Buttonandroid:onClick="startgame"android:id="@+id/button1"android:layout_height="wrap_content"android:layout_width="wrap_content"android:text="Start Game"></Button> </LinearLayout>

  30. Directory: res/layout • Setup w/o coding • Drag and drop

  31. Directory: res/menu Define menus accessible to the user Setup w/o coding

  32. Directory: res/values • Constants, supports internationalization Value types: Setup w/o coding

  33. APK Package APK Package APK Package Application and Activities Task Process Process Process Activity Activity Activity Activity Activity Activity ContentProvider ContentProvider ContentProvider Process Service Service Service

  34. Android Architecture

  35. Implementing the lifecycle callbacks publicclassExampleActivityextendsActivity{@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);// The activity is being created.}@OverrideprotectedvoidonStart(){super.onStart();// The activity is about to become visible.}@OverrideprotectedvoidonResume(){super.onResume();// The activity has become visible (it is now "resumed").}@OverrideprotectedvoidonPause(){super.onPause();// Another activity is taking focus (this activity is about to be "paused").}@OverrideprotectedvoidonStop(){super.onStop();// The activity is no longer visible (it is now "stopped")}@OverrideprotectedvoidonDestroy(){super.onDestroy();// The activity is about to be destroyed.}}

  36. onCreate(Bundle savedState) Activity instance creation Set content view Initializations @Override publicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1=(Button)findViewById(R.id.button1); b1.setVisibility(0); }

  37. Activity Lifecycle

  38. UI View

  39. UI View <?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent"android:layout_height="fill_parent" android:orientation="vertical"> <TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello in help.xml"></TextView> <Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Submit1"></Button> <Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Submit2"></Button> <Buttonandroid:id="@+id/button3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Submit3"></Button> </LinearLayout> help.xml

  40. UI View publicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.help); b1=(Button)findViewById(R.id.button1); b2=(Button)findViewById(R.id.button2); b3=(Button)findViewById(R.id.button3); b3.setVisibility(100); }

  41. Classic Inheritance in Android The code defines a class called Hello_worldActivity as an extension of Activity publicclassDodgeBallActivityextends Activity { /** Called when the activity is first created. */ publicstatic Button b1; @Override publicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1=(Button)findViewById(R.id.button1); } publicvoidstartgame(View v){ Panel p=new Panel(this); WindowManagerwindowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); p.screenWidth = display.getWidth(); p.screenHeight = display.getHeight(); setContentView(p); } }

  42. OOP Instance for Android • The following code is an instance by using encapsulation, inheritance, and polymorphism in Android program. • It is creating a class named “Element”, it contains several functions and variables with the declarations of public, protected, and private

  43. Encapsulation class Element { protectedintmX; protectedintmY; protectedintwspeed=0; protectedinthspeed=0; publicintscreenWidth; publicintscreenHeight; public Element() { } privatevoidcheckedge(){…… } //private method, others can't see or use publicvoid move(){…… } publicvoid build(){ } publicvoid draw(Canvas canvas,intX,intY,Paint paint){ paint.setColor(Color.GREEN); canvas.drawCircle(X,Y,15,paint); paint.setColor(Color.RED); canvas.drawCircle(X,Y,10,paint); paint.setColor(Color.BLUE); canvas.drawCircle(X,Y,5,paint); } publicvoid draw(Canvas canvas, Paint paint) { } }

  44. Inheritance • The following code is for defining a class “MyRectangle” to inherit the class “Element” with syntax extends • In this class, it declares a new public value rect , and override the method “build” and “draw” classMyRectangleextends Element{ publicMyRectangle() { mX=50; mY=50; } publicRectFrect; @Override publicvoid build(){ rect= newRectF(mX, mY, mX+20, mY+20); } publicvoid draw(Canvas canvas,intX,intY,Paint paint){ this.build(); this.move(); paint.setColor(Color.RED); canvas.drawRect(rect, paint); } }

  45. The following code is for defining a class “MyTriangal” to inherit the class “Element” • In this class, it declares a new public value path, and override the method “build” and “draw” classMyTriangalextends Element{ publicMyTriangal() { mX=80; mY=80; } public Path path = new Path(); @Override publicvoid build(){ path.reset(); path.moveTo(mX, mY-8); path.lineTo(mX-7,mY+7); path.lineTo(mX+8, mY+7); path.lineTo(mX, mY-8); path.close(); } publicvoid draw(Canvas canvas,intX,intY,Paint paint){ this.build(); this.move(); paint.setColor(Color.BLUE); canvas.drawPath(path, paint); } }

  46. The following code is for defining a class “MyCircle” to inherit the class “Element” • In this class, it declares a new public value radius, and classMyCircleextends Element{ publicMyCircle() { mX=120; mY=120; } privateintradius=10; publicvoid move(intX,int Y){ if((X-mX)*wspeed<0){ wspeed=-wspeed; } if((Y-mY)*hspeed<0){ hspeed=-hspeed; } mX+=wspeed; mY+=hspeed; } publicvoid draw(Canvas canvas, intX,intY,Paint paint){ paint.setColor(Color.YELLOW); canvas.drawCircle(mX,mY,radius,paint); this.move(X,Y); } }

  47. Polymorphism • The following code is for creating new instances from the classes public Element e[]=new Element[4]; e[0]=new Element(); e[1]=newMyRectangle(); e[2]=newMyTriangal(); e[3]=newMyCircle(); • The following code is for initializing and running the new instances e[1].wspeed=1; e[1].hspeed=1; e[2].wspeed=3; e[2].hspeed=-2; e[3].wspeed=1; e[3].hspeed=1; ……for(inti=0;i<4;i++){ …… e[i].draw(canvas, mX, mY, paint); }

  48. Sample Code Demo Results:

  49. UI Input • Typical input sources • Keyboard • Touch Screen • Event-based Paradigm • Register to listen for device events

  50. onTouchEvent() Example @Override publicbooleanonTouchEvent(MotionEvent event) { int action = event.getAction(); switch (action) { caseMotionEvent.ACTION_DOWN: if(!paused){ if((int) event.getX()>mX){…… } elseif((int) event.getX()<mX){…… } if((int) event.getY()>mY){…… } elseif((int) event.getY()<mY){…… } } else{…… } break; caseMotionEvent.ACTION_MOVE: …… break; caseMotionEvent.ACTION_UP: …… break; } returntrue; }

More Related