530 likes | 644 Views
Resources and RelativeLayouts. Resources. Android Resources. We’ve already talked about the different types of Android Resources. Using Resources in XML. Three Important Pieces @ resource_type resource_name /id These Three pieces create a path to a resource @string/ app_name.
E N D
Android Resources We’ve already talked about the different types of Android Resources
Using Resources in XML • Three Important Pieces • @ • resource_type • resource_name/id • These Three pieces create a path to a resource • @string/app_name
Using Resources in Code • How to I access the string is Code? • @string/app_name??? • In code, you gain access to the resources via the R class • For each type of resource, there is an R subclass
R subclasses publicfinalclass R { publicstaticfinalclassdimen { publicstaticfinalintactivity_horizontal_margin=0x7f040000; publicstaticfinalintactivity_vertical_margin=0x7f040001; } publicstaticfinalclassdrawable { publicstaticfinalintic_launcher=0x7f020000; } publicstaticfinalclass id { publicstaticfinalintaction_settings=0x7f080006; publicstaticfinalintcanvas=0x7f080004; } publicstaticfinalclass layout { publicstaticfinalintactivity_main=0x7f030000; publicstaticfinalinttest=0x7f030001; } publicstaticfinalclass menu { publicstaticfinalintmain=0x7f070000; } publicstaticfinalclass string { publicstaticfinalintaction_settings=0x7f050001; publicstaticfinalinthello_world=0x7f050002; publicstaticfinalintred=0x7f050005; } } Dimen subclass for all dimensions Drawble subclass for all images ID subclass for all ids specified in layout
What does the static keyword mean? publicfinalclass R { publicstaticfinalclassdimen { publicstaticfinalintactivity_horizontal_margin=0x7f040000; publicstaticfinalintactivity_vertical_margin=0x7f040001; } publicstaticfinalclassdrawable { publicstaticfinalintic_launcher=0x7f020000; } publicstaticfinalclass id { publicstaticfinalintaction_settings=0x7f080006; publicstaticfinalintcanvas=0x7f080004; } publicstaticfinalclass layout { publicstaticfinalintactivity_main=0x7f030000; publicstaticfinalinttest=0x7f030001; } publicstaticfinalclass menu { publicstaticfinalintmain=0x7f070000; } publicstaticfinalclass string { publicstaticfinalintaction_settings=0x7f050001; publicstaticfinalinthello_world=0x7f050002; publicstaticfinalintred=0x7f050005; } }
Static Keyword • Static variables are associated with the class, rather than with any object. Every instance of the class shares a class variable. • Since static variables are associated with the class, we don’t need an instance of the object to access the static vars.
Static Keyword • To access static variables all you need to know is the class name. • If the static variable is public, you can easily get the variable.
The R file only contains integers publicfinalclass R { publicstaticfinalclassdimen { publicstaticfinalintactivity_horizontal_margin=0x7f040000; publicstaticfinalintactivity_vertical_margin=0x7f040001; } publicstaticfinalclassdrawable { publicstaticfinalintic_launcher=0x7f020000; } publicstaticfinalclass id { publicstaticfinalintaction_settings=0x7f080006; publicstaticfinalintcanvas=0x7f080004; } publicstaticfinalclass layout { publicstaticfinalintactivity_main=0x7f030000; publicstaticfinalinttest=0x7f030001; } publicstaticfinalclass menu { publicstaticfinalintmain=0x7f070000; } publicstaticfinalclass string { publicstaticfinalintaction_settings=0x7f050001; publicstaticfinalinthello_world=0x7f050002; publicstaticfinalintred=0x7f050005; } }
The R file only contains integers • The R class by itself won’t get you the resource you want. • Instead you’ll have to • use methods which take resource ids to get the resource you’re interested in. • Use the Resources Object to obtain the real resource
Common methods that take Resource Ids • findViewById() • TextView.setText() – This method has two signatures, one for a String and another for Resource Id • View.setBackgroundResource()
Using the ResourcesObject • The Activity provides a method getResources(). • getResources() returns an instance of the Resources class that is specific to your application. That means you only have access to your resources not resources in another application.
Resources Class • The Resources class provides getter methods to retrieve any type of resource available to your app. • String • String Array • Integer • Integer Array • Color • Drawable • Dimension • Animation • Etc.
How to get a color value from resources //getResources() is a method provided by the Activity Resources res = getResources(); //res.getColor(id) takes a resource identifier and returns a color or 0 if id not found //We must use the R class to access the color subclass to access the identifier for the color blue intblueColor = res.getColor(R.color.blue);
How to get a string value from resources //getResources() is a method provided by the Activity Resources res = getResources(); //res.getString(id) takes a resource identifier and returns a string or throw an exception if the id not found //We must use the R class to access the string subclass to access the identifier for the string app_name String appName = res.getString(R.string.app_name);
Screen Support Key Terms • Screen Density • Resolution • Orientation • Density-independent pixel
Screen Density • The quantity of pixels within a physical area of the screen. • Usually referred to as dpi • Android groups screen densities by: low, medium, high, extra high • A low density screen has fewer pixels within a given physical area than a “normal” or “high” density screen.
Resolution • The total number of pixels on a screen • Use the resolution to manage layouts for your application based on available screen width/height. • Create layouts that are configured for • Smallest width • Available screen width • Available screen height
Resolution • If you want to create layouts for specific resolutions, find more information here.
Orientation • The orientation of the screen from the user’s point of view • Either landscape or portrait • You can create specific layouts catered to your devices orientation
Density Independent Pixel (dp) • A virtual pixel unit • Should be used for defining UI layout that can be reused for multiple screen sizes.
How big is a dp? • See my Android Display Metric Cheat Sheet.
Creating an emulator for a specific device • Use this article
Handling UI Events Topics • Overview of UI Events • Implementing UI Event Listeners
UI Events • Key • Touch • Click • Long Click • Focus Change • Track ball • Drag and Drop
Key Events Called when a hardware key is dispatched to focuseda view. Event Listener Interface: View.OnKeyListener Callback Method: onKey()
Touch Events This is called when the user performs an action qualified as a touch event: • Press • Release • Movement (within the bounds of a view). Event Listener Interface: View.OnTouchListener Callback Method: onTouch()
onTouch(View v, MotionEvent event) • Takes 2 parameters • Returnstrue if the listener consumed the event, false otherwise.
MotionEvent • Used to report movement for • Mouse • Pen • Finger (Touch) • Trackball
MotionEvent for touch • Contains data about “pointers” aka active touch points on the device’s screen. • For each pointer you can receive • X/Y coordinates • Size • Pressure • Value describing what kind of motion occurred.
MotionEvent for single pointer • getAction() – return the action being performed (action_down/move/up/cancel). • getX() - returns the X coordinate of this event for a single pointer. • getY() - returns the Y coordinate of this event for the given pointer
getAction() • ACTION_DOWN - A touch gesture has started. • ACTION_MOVE - A change has occurred between touch down and release. • ACTION_UP – A touch gesture has finished. • ACTION_CANCEL – A touch gesture has been aborted.
@Override publicbooleanonTouchEvent(MotionEventev){ finalint action =ev.getAction(); switch(action){ caseMotionEvent.ACTION_DOWN:{ finalfloat x =ev.getX(); finalfloat y =ev.getY(); // Remember where we started mLastTouchX= x; mLastTouchY= y; break; } caseMotionEvent.ACTION_MOVE:{ finalfloat x =ev.getX(); finalfloat y =ev.getY(); // Calculate the distance moved finalfloat dx = x -mLastTouchX; finalfloatdy= y -mLastTouchY; // Move the object mPosX+= dx; mPosY+=dy; // Remember this touch position for the next move event mLastTouchX= x; mLastTouchY= y; // Invalidate to request a redraw invalidate(); break; } } returntrue; }
MotionEvent for multiple pointers The MotionEvent class provides many methods to query the position and other properties of pointers: • getX(int) – returns X pos for given pointer index. • getY(int) – returns Y pos for given pointer index. • getPointerCount() – The number of pointers for this event
MotionEvent for multiple pointers • getPointerId(int) – pointer id associated with the pointer index for this event • findPointerIndex(int) – given a pointer id, find the index of its data.
New getAction() values • ACTION_POINTER_DOWN – fired when a secondary pointer goes down. • ACTION_POINTER_UP – fired when a secondary pointer goes up.
Pointer index • Each pointer index corresponds to a finger for the event. • The pointer index ranges from 0 to one less than the returned value of getPointerCount(). • The order in which individual pointers appear is undefined; therefore you can’t rely on the pointer index to map to the same finger across touch events.
Multiple Pointers are hard! • When working with multiple pointers, android provides many methods that use the pointer index. • Pointer indices can change across events; therefore, we need another way to identify pointers.
Pointer ID • The pointer id of a finger is guaranteed to remain constant as long as the pointer remains active (until it ACTION_UPs) • When you want to keep track of a finger, save its ID on action down. • Retrieve the saved finger’s pointer index for the current event with findPointerIndex(int).
Multiple Pointers Example @OverridepublicbooleanonTouchEvent(MotionEventev){finalint action =ev.getAction();switch(action &MotionEvent.ACTION_MASK){caseMotionEvent.ACTION_DOWN:{finalfloat x =ev.getX();finalfloat y =ev.getY();mLastTouchX= x;mLastTouchY= y;// Save the ID of this pointermActivePointerId=ev.getPointerId(0);break;}caseMotionEvent.ACTION_MOVE:{// Find the index of the active pointer and fetch its positionfinalintpointerIndex=ev.findPointerIndex(mActivePointerId);finalfloat x =ev.getX(pointerIndex);finalfloat y =ev.getY(pointerIndex);finalfloat dx = x -mLastTouchX;finalfloatdy= y -mLastTouchY;mPosX+= dx;mPosY+=dy;mLastTouchX= x;mLastTouchY= y; invalidate();break;}caseMotionEvent.ACTION_UP:{mActivePointerId= INVALID_POINTER_ID;break;}caseMotionEvent.ACTION_CANCEL:{mActivePointerId= INVALID_POINTER_ID;break;}caseMotionEvent.ACTION_POINTER_UP:{// Extract the index of the pointer that left the touch sensorfinalintpointerIndex=(action &MotionEvent.ACTION_POINTER_INDEX_MASK)>>MotionEvent.ACTION_POINTER_INDEX_SHIFT;finalintpointerId=ev.getPointerId(pointerIndex);if(pointerId==mActivePointerId){// This was our active pointer going up. Choose a new// active pointer and adjust accordingly.finalintnewPointerIndex=pointerIndex==0?1:0;mLastTouchX=ev.getX(newPointerIndex);mLastTouchY=ev.getY(newPointerIndex);mActivePointerId=ev.getPointerId(newPointerIndex);}break;}}returntrue;}
Additional Info on Multitouch • http://android-developers.blogspot.com/2010/06/making-sense-of-multitouch.html
Click Events • A Click is a pair of down/up events performed either with the keyboard, trackball, or touch screen. • If the view receives a down event but does not receive a following up event, then the click event does not occur.
Click Events Event Listener Interface: View.OnClickListener Callback Method: onClick() Parameters: v The view that has been clicked
Long Click Events • Happens when a item is pressed and held (for one second). • Applies to touch, trackball, hard keys.
Long Click Events Event Listener Interface: View.OnLongClickListener Callback Method: onLongClick() Parameters: v The view that has been clicked and held
Trackball events • To my knowledge, trackballs on devices have completely disappeared. • So don’t worry about them.
Focus Change events • Focus Change applies to physical keyboards. • There are still a few devices that support a physical QWERTY keyboard. • However, BlueTooth keyboards are becoming more popular and will work with any BlueTooth enabled device.