Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lecture 7

Lecture 7

Indrek Kõue

May 26, 2015
Tweet

More Decks by Indrek Kõue

Other Decks in Education

Transcript

  1. VIEW RENDERING • User interface is defined using a hierarchy

    (tree) of View and ViewGroup objects. • Drawing is handled by walking the tree and rendering each View
  2. VIEW RENDERING 1. Measure pass onMeasure(int widthMeasureSpec, int heightMeasureSpec) •

    Each View pushes dimension specifications down the tree • Determines the size requirement for a view • In order to parent to measure itself, needs to measure all children • Start from bottom Result: every View has stored its measurements.
  3. VIEW RENDERING 2. Layout pass onLayout(boolean changed, int left, int

    top, int right, int bottom) • Called only on ViewGroups • ViewGroups let children know how they should be positioned calling “layout(left, top, right, bottom)”. • Lighter than onMeasure • Start from top Result: all child views are positioned using the sizes computed in the measure pass.
  4. VIEW RENDERING 3. Draw pass onDraw(Canvas canvas) • Called when

    the view should render its content. • Parents will be drawn before (i.e., behind) their children • Start from top Result: layout is rendered
  5. VIEW RENDERING Parent ->> Children data transfer = Measurespec onMeasure(int

    widthMeasureSpec, int heightMeasureSpec) Modes: • UNSPECIFIED: Used by a parent to determine the desired dimension of a child View. • EXACTLY: Child must use this size, and guarantee that all of its descendants will fit within this size. • AT MOST: Imposes a maximum size on the child. The child must guarantee that it and all of its descendants will fit within this size.
  6. VIEW RENDERING Children ->> Parent = ViewGroup.Layoutparams XML attributes in

    layout (width, height etc.) Values: • an exact number • MATCH_PARENT, View wants to be as big as its parent (minus padding) • WRAP_CONTENT, View wants to be just big enough to enclose its content (plus padding). Different subclasses of ViewGroup.LayoutParams for different subclasses of ViewGroup.
  7. CUSTOM VIEWS What if built in components are not enough?

    Modify, combine or create new ones 1. Modify existing widget 2. Combine widgets into new one 3. Build from ground up
  8. CUSTOM VIEWS (MODIFY) 1. Modify existing widget Subclass the widget

    and override its methods. Example: TextView with custom font and color, linearlayout with fixed aspect ratio etc
  9. CUSTOM VIEWS (MODIFY) public class FontTextView extends TextView { public

    FontTextView(Context context) { //for creating in Java code ... } public FontTextView(Context context, AttributeSet attrs) { super(context, attrs); Typeface face = Typeface.createFromAsset( context.getAssets(), "Helvetica_Neue.ttf"); this.setTypeface(face); } public FontTextView(Context context, AttributeSet attrs, int defStye) { //for creating from XML with style … }
  10. CUSTOM VIEWS (COMBINE) 2. Combine widgets Combine multiple widgets into

    viewgroup Example: checkbox with textview, edittext with textview etc.
  11. CUSTOM VIEWS (COMBINE) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android. com/apk/res/android" android:layout_width="match_parent"

    android:layout_height="match_parent"> <Button android:layout_width="50dp" android:layout_height=" wrap_content" android:text="-" /> <EditText android:layout_width="75dp" android:layout_height=" wrap_content" /> <Button android:layout_width="50dp" android:layout_height=" wrap_content" android:text="+" /> </LinearLayout>
  12. CUSTOM VIEWS (COMBINE) public class HorizontalNumberPicker extends LinearLayout { public

    HorizontalNumberPicker(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater inflater = LayoutInflater.from(context); layoutInflater.inflate( R.layout.horizontal_number_picke, this); } } <com.example.HorizontalNumberPicker android:id ="@+id/horizontal_number_picker" android:layout_width ="wrap_content" android:layout_height ="wrap_content" />
  13. COMPLETELY CUSTOM VIEW 3. Build from ground up Subclass View

    and override onDraw and onSizeChanged Example: pie chart, heart pulse animated view etc.
  14. COMPLETELY CUSTOM VIEW onDraw(Canvas canvas) Canvas = what to draw

    Paint = How to draw Note: Allocate paint and other objects during initialization
  15. COMPLETELY CUSTOM VIEW Allocating: mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setColor(mTextColor); Drawing:

    protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Draw the label text canvas.drawText(mData.get(mCurrentItem).mLabel, mTextX, mTextY, mTextPaint); // Draw the pointer canvas.drawLine(mTextX, mPointerY, mPointerX, mPointerY, mTextPaint); canvas.drawCircle(mPointerX, mPointerY, mPointerSize, mTextPaint); }
  16. COMPLETELY CUSTOM VIEW onSizeChanged(int w, int h, int oldw, int

    oldh) • Called when the size of this view has changed. • If need more control: override onMeasure // Account for padding float xpad = (float)(getPaddingLeft() + getPaddingRight()); float ypad = (float)(getPaddingTop() + getPaddingBottom()); // Account for the label if (mShowText) xpad += mTextWidth; float ww = (float)w - xpad; float hh = (float)h - ypad; // Figure out how big we can make. float diameter = Math.min(ww, hh);
  17. COMPLETELY CUSTOM VIEW onMeasure(int widthMeasureSpec, int heightMeasureSpec) • How big

    you want your custom view to be dependent the layout constraints provided by the parent • Input values are stored as packed integers (use methods of View.MeasureSpec to unpack the information) • When calculations are done call: setMeasuredDimension(int width, int height) int mode = MeasureSpec.getMode(widthMeasureSpec) int size = MeasureSpec.getSize(widthMeasureSpec)
  18. COMPLETELY CUSTOM VIEW What can you do also: + save

    instance state + add input gestures + add animations
  19. CUSTOM VIEW: ATTRIBUTES //res/values/*.xml <resources> <declare-styleable name="PieChart"> <attr name="showText" format="boolean"

    /> <attr name="labelPosition" format="enum"> <enum name="left" value="0"/> <enum name="right" value="1"/> </attr> </declare-styleable> </resources> ------- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res-auto"> <com.ex.customviews.charting.PieChart custom:showText="true" custom:labelPosition="left" /> </LinearLayout> Note: don’t use package name in custom XML namespace
  20. CUSTOM VIEW: ATTRIBUTES public PieChart(Context context, AttributeSet attrs) { super(context,

    attrs); TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.PieChart, 0, 0); try { mShowText = a.getBoolean(R.styleable.PieChart_showText, false); mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0); } finally { a.recycle(); } }
  21. GRAVITY AND WEIGHT android:gravity Gravity of the content of the

    View it’s used on. android:layout_gravity Gravity of the View or Layout in its parent. Note: everything with layout_ effects the outside. android:layout_weight Size ratio between multiple views. Example: one view takes 3/4 of the screen and other 1/4. Note: You have to set the height or width to 0dp.
  22. CUSTOM PERMISSIONS Applications 1: <permission android:name="com.mypermission"/> //can be used with

    activity,broadcast receiver,content provider <intent-filter> <action android:name="com.permissiontestclient.MyAction" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> Application 2: <uses-permission android:name="com.mypermission"/> Intent in = new Intent(); in.setAction("com. permissiontestclient.MyAction"); in.addCategory("android.intent. category.DEFAULT"); startActivity(in);
  23. PUSH MESSAGES How to deliver messages to user when application

    is not used? long poll HTTP? Create a websocket? Custom background service? Google Cloud Messaging. Enables to send downstream messages (from servers to GCM-enabled client apps) Handles all aspects of queueing of messages and delivery to the target client app.
  24. PUSH MESSAGES TCP socket waiting in accept mode (initiated by

    the Google Play Services). TCP client socket receives message >> data parsed >> packed into an intent >> broadcasted >> broadcast receiver catches the broadcast >> message received Could contain 4kb of payload data
  25. LINT TOOL Static code analysis tool Android Studio: Analyze >

    Inspect Code Checks for: • Missing translations • Layout performance problems • Unused resources • Accessibility (missing contentDescription etc) • Icon problems (missing densities, duplicates etc) • Manifest errors • and many other thing.
  26. PROGUARD Shrinks, optimizes, and obfuscates code Removes unused code and

    renames classes, fields, and methods with semantically obscure names To enable in project: minifyEnabled (Gradle > buildTypes > release)
  27. PROGUARD Default settings: SDK/tools/proguard/proguard-android.txt Custom rules: app/proguard-rules.pro Proguard can’t resolve

    references to: • a class that is referenced only in the AndroidManifest. xml file • a method called from JNI • dynamically referenced fields and methods Note: if you are going to use 3rd party error reporting or want to rely on stacktrace for debugging you need to configure Proguard
  28. SUPPORT LIBRARY Contains libraries that can be included in your

    application so you could use newer features in older versions. Adding to project (Gradle): com.android.support:{name}:22.1.0 v4 Support Library includes the largest set of APIs v7 appcompat library (depends on v4 support) Action Bar, material design (partial)
  29. SUPPORT LIBRARY v7 cardview library CardView widget (lets you show

    information inside cards that have a consistent look) v7 gridlayout library GridLayout class (allows to arrange user interface elements using a grid of rectangular cells) v7 mediarouter library Routing of streams to external screens, speakers, and other destination devices
  30. SUPPORT LIBRARY v7 palette library Palette class (lets you extract

    prominent colors from an image) v7 recyclerview library RecyclerView widget (for displaying large data sets). v13 Support Library Like v4 but with less content v17 Leanback Library Supports building user interfaces on TV devices.
  31. LOGCAT API for displaying log output. Categories: ERROR, WARN, INFO,

    DEBUG, VERBOSE. • Debug logs stripped at runtime. • System.out.println() redirected to Log.i() • Apps can not read each other’s logs (unless a system app or root user). Log.v(TAG, "index=" + i);
  32. TOPICS View rendering Custom views Gravity vs weight Custom permissions

    Push messages 9patch Lint tool Proguard Support library Logcat
  33. ?