Android App Development - 04 Views and layouts

Embed Size (px)

Citation preview

  1. 1. Views and Layout
  2. 2. Views and Layout The Android platform provides the developer View and ViewGroup to create graphical interfaces of the Activity. A ViewGroup is a layout object that can contain other Views. A GUI is composed of a hierarchy of ViewGroups and Views. GUIs can be created with xml layout files, but can also be created at runtime because the xml file is a tool to simplify the job of the developer: all xml file are parsed at runtime to create the objects related with the listed attributes. This system is flexible to declare different layouts for different configurations that would otherwise be handled by code. Views and Layout
  3. 3. Views and Layout To indicate to the Activity which xml layout file in the /res folder must be loaded you can use the method: Activity.setContentView(int resourceId) To retrieve an instance of a layout object the following method is available: Activity.findViewById(int resourceId) Pattern: The invocation of setContentView() is free and can be done at any point in the life cycle of the Activity. However, to respect the time of parsing and to make the system to instantiate all classes View contained once it is preferable to invoke it and retrieve all View in onCreate(). UI Handling
  4. 4. Views and Layout Each View or ViewGroup declared in the layout inherites from the superclass attributes and specific attributes. The namespace is always Android and the node is the name of the class you want to instantiate. The difference between View and ViewGroup on a .xml is the ability to insert other View or ViewGroup within the node of a ViewGroup. In general, the attributes that must always be specified are: android:layout_width android:layout_height Attributes
  5. 5. Views and Layout android:layout_width android:layout_height The parameters accepted by these attributes are: wrap_content fill_parent (match_parent) A value with relative units of measurement A reference to a dimen object The id attribute is used to retrieve the instance of the View or ViewGroup at runtime or in other positions of the layout. To indicate to the system that a new entry is to be created in R class for the view to be identified elsewhere you need to use this syntax: android:id=@+id/ Attributes
  6. 6. Views and Layout ViewGroups are: LinearLayout: the view contained are arranged in sequence according to the indicated orientation attribute: android:orientation:"horizontal (default) vertical RelativeLayout: Each view can contain information about the relative position to other already declared View or ViewGroup: layout_below layout_above layout_toRightOf layout_toLeftOf layout_alignParentTop layout_alignParentBottom layout_alignParentRight layout_alignParentLeft Main Layouts
  7. 7. Views and Layout ScrollView: it allows vertical scrolling content. To do this it accepts one only View or ViewGroup (which may contain other View and ViewGroup) HorizontalScrollView: it allows horizontal scrolling of the content. To do this it accepts one only View or ViewGroup (which may contain other View and ViewGroup) ListView e GridView: they allow vertical scrolling of View and ViewGroup. Entry must be done at runtime with an Adapter object which must be specified in the id of the layout to be loaded for each element. RadioGroup: it contains RadioButtons of which only one element is checked TableLayout: it contains TableRow for creating a table. Main Layouts
  8. 8. Views and Layout TextView EditText Button ImageView CheckBox ImageButton ProgressView RadioButton RatingBar SeekBar Spinner TextClock TimePicker DatePicker ToggleButton Main View VideoView MediaController CheckedTextView AutoCompleteTextView CalendarView Chronometer DigitalClock ImageSwitcher NumberPicker SlidingDrawer ViewAnimator ViewSwitcher ViewFlipper ViewStub WebView
  9. 9. Views and Layout Events are managed by implementing the interfaces of the classes or superclasses that extends View. The View class provides the following interfaces: View.OnClickListener{onClick(View v)} to handle the simple click. View.onLongClickListener { onLongClick(View v) } o handle a long click. View.onTouchListener { onTouch(View v, MotionEvent e) } to handle a generic touch event The implementation of the interface is passed to the View with the methods: View.setOnClickListener(View.OnClickListener listener) View.setOnLongClickListener(View.OnLongClickListener listener) View.setOnTouchListener(View.OnTouchListener listener) Event Handlers
  10. 10. Views and Layout There are 2 ways to implement the interfaces: Anonymous implementation: private OnClickListener listener = new OnClickListener() { public void onClick(View v) { // ... } }; Implementation as part of the Activity: public class ExampleActivity extends Activity implements OnClickListener { public void onClick(View v) { // ... } } Event handlers
  11. 11. Views and Layout The implementation of anonymous is the most widely used, but it produces overload of classes instantiated and allocation of objects. Pattern: it is preferable to implement the management of the events as an integral part of the Activity not only to the advantages in the management of the memory, but also for the readability of the code (to avoid multiple indentations and to have just one method that handles the events of all the Views). Centralized management is possible by checking if the event was generated by a View through its id: public void onClick(View v) { switch (v.getId()) { case R.id.example: // ... break; } } Event Handlers
  12. 12. Views and Layout All Android Views extend the View class, and then to create a custom view the class must extend View. If you want to implement a new functionality for an existing View you can extended directly that class. Ex. To create a button that changes the background in certain states you can extend Button instead redefine all its methods by extending View To create custom view you need to put the right emphasis on the use of memory and CPU. Custom View
  13. 13. Views and Layout All the custom view created in xml file can be inserted as part of the graphical interface. The node to be specified must contain the complete package in addition to the name of the class in this way: The attributes that you can specify are those inherited from the superclass and custom ones defined by the developer. The definition of the attributes is via custom xml in the res/values folder (in a file usually called attrs.xml) Custom View - Attributes
  14. 14. Views and Layout To insert the custom attributes inside the layout xml file you need to add a namespace: xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews" Or try making the system automatically in case of multiple custom views in the same layout: xmlns:custom="http://schemas.android.com/apk/res-auto" The alias is chosen by the developer. Custom View - Attributes
  15. 15. Views and Layout Each custom view must implement at least one of the three constructors inherited from the superclass View: public CustomView(Context context) { super(context); } public CustomView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } Custom View - Constructor
  16. 16. Views and Layout To retrieve custom attributes defined in the layout you can use a TypedArray object with the AttributeSet passed by the constructor: public CustomView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0); try { showText = a.getBoolean(R.styleable.CustomView_showText, false); textPos = a.getInteger(R.styleable.CustomView_labelPosition, 0); } finally { a.recycle(); } } Custom View Attributes Retrieving
  17. 17. Views and Layout The recovery of custom attributes is static. To make it dynamic fit getter and setter methods for each attribute that you want to manage externally: public boolean isShowText() { return showText; } public void setShowText(boolean showText) { this.showText = showText; invalidate(); requestLayout(); } The View.invalidate() method completely redraws the view in order to apply the change immediately. The View.requestLayout() method notifies the layout that contains the view that you have changed the size of its View. Custom View Attributes management
  18. 18. Views and Layout The View.onDraw() method specifies how to bring up the View. It uses an object: Canvas: to determine what and where to draw; Paint: to determine how to draw. @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (showText) { Paint paint = new Paint(); paint.setColor(Color.BLACK); canvas.drawText(text, x, y, paint); } } Custom View onDraw()
  19. 19. Views and Layout The View.onMeasure() method recovers the size of the View requests from ViewGroup that contains it. In this way you can calculate the correct size for the View in a variety of layouts, configurations, display resolutions of the device. @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth(); int w = resolveSizeAndState(minw, widthMeasureSpec, 1); int minh = MeasureSpec.getSize(w) - (int) mTextWidth + getPaddingBottom() + getPaddingTop(); int h = resolveSizeAndState(MeasureSpec.getSize(w) - (int) mTextWidth, heightMeasureSpec, 0); setMeasuredDimension(w, h); } Custom View onMeasure()
  20. 20. Views and Layout The main aspects to be considered in designing a custom view are: The method of the View that has the greatest load on the Main Thread of the application is the View.onDraw() method. The View.requestLayout() method generates a call to cascade to the entire hierarchy of View contained in the layout. The View.invalidate() method call results in a new View.onDraw() Pattern: so that the view will be seamless and not impact the loading of the other view, It must minimize the call to the methods View.invalidate() and View.requestLayout(). The animations are handled externally with the objects available for the purpose and not in the method View.onDraw(). In order not to overload the method View.onDraw () is necessary not to instantiate objects in its implementation, but only during the creation of the View. Custom View Optimization