Custom Views in Android Tutorial

Similar documents
package import import import import import import import public class extends public void super new this class extends public super public void new

GATAV 5. Animations Using a Game Loop

ANDROID (4) 2D Graphics and Animation, Handling Screen Rotation. Marek Piasecki

INTRODUCTION TO ANDROID

Android Apps Development for Mobile Game Lesson Create a simple paint brush that allows user to draw something (Page 11 13)

Programming Mobile Applications with Android Lab2

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

Database Development In Android Applications

Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ]

OPTIMIZING ANDROID UI PRO TIPS FOR CREATING SMOOTH AND RESPONSIVE APPS

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

EECS 4443 Mobile User Interfaces. More About Layouts. Scott MacKenzie. York University. Overview (Review)

Mobile Application (Design and) Development

EECS 4443 Mobile User Interfaces. More About Layouts. Scott MacKenzie. York University

ELET4133: Embedded Systems. Topic 15 Sensors

Android HelloWorld - Example. Tushar B. Kute,

Programming of Mobile Services, Spring 2012

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

Mobile App Design Project Doodle App. Description:

Lab 3. Accessing GSM Functions on an Android Smartphone

Spring Lecture 7 Lecturer: Omid Jafarinezhad

Embedded Systems Programming - PA8001

Practical 1.ListView example

User Interface Development. CSE 5236: Mobile Application Development Instructor: Adam C. Champion Course Coordinator: Dr.

CSE 331 Software Design & Implementation

ELET4133: Embedded Systems. Topic 3 Eclipse Tour & Building a First App

An Android Studio SQLite Database Tutorial

CS260 Intro to Java & Android 09.AndroidAdvUI (Part I)

ICS 4U. Introduction to Programming in Java. Chapter 10 Notes

Inheritance, and Polymorphism.

Assistant Professor Computer Science. Introduction to Human-Computer Interaction

Chapter 3: Inheritance and Polymorphism

Vienos veiklos būsena. Theory

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment

Chapter 1: Object-Oriented Programming Using C++

Programming with Android: Introduction. Layouts. Dipartimento di Informatica: Scienza e Ingegneria Università di Bologna

Java for Non Majors Spring 2018

Agenda. Overview of Xamarin and Xamarin.Android Xamarin.Android fundamentals Creating a detail screen

Mastering Android Drawables

Java Object Oriented Design. CSC207 Fall 2014

ANDROID USER INTERFACE

Android Development Tutorial

Stanislav Rost CSAIL, MIT

ANDROID APPS (NOW WITH JELLY BEANS!) Jordan Jozwiak November 11, 2012

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

CMSC 132: Object-Oriented Programming II

User Interface: Layout. Asst. Prof. Dr. Kanda Runapongsa Saikaew Computer Engineering Khon Kaen University

Topic 7: Algebraic Data Types

Android Application Development. By : Shibaji Debnath

Creating a User Interface

Object-Oriented Programming Concepts

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Contents at a Glance. iii.

Chapter 10 Classes Continued. Fundamentals of Java

Android development. Outline. Android Studio. Setting up Android Studio. 1. Set up Android Studio. Tiberiu Vilcu. 2.

Android Application Development Instructions

CS260 Intro to Java & Android 05.Android UI(Part I)

GUI Design for Android Applications

Chapter 14 Abstract Classes and Interfaces

CS260 Intro to Java & Android 05.Android UI(Part I)

ITI Introduction to Computing II

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

Introduction to Programming Using Java (98-388)

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL II)

Building User Interface for Android Mobile Applications II

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Creating a Custom ListView

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Contents. Orientation SearchBar and Gallery List Advanced Multiple Form Multi Touch Animations Layout Designing UI using UI Builder

Programming: You will have 6 files all need to be located in the dir. named PA4:

EMBEDDED SYSTEMS PROGRAMMING UI Specification: Approaches

Android/Java Lightning Tutorial JULY 30, 2018

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Theme 2 Program Design. MVC and MVP

ITI Introduction to Computing II

Interaction with Android

Android Basics. Android UI Architecture. Android UI 1

ListView Containers. Resources. Creating a ListView

Developing Android Applications Introduction to Software Engineering Fall Updated 1st November 2015

A Crash Course to Android Mobile Platform

Implementing Graphical User Interfaces

PROGRAMMING APPLICATIONS DECLARATIVE GUIS

Declarations and Access Control SCJP tips

5.6.1 The Special Variable this

Intents. Your first app assignment

CS/ENGRD 2110 SPRING 2018

F I N A L E X A M I N A T I O N

Java Programming Tutorial 1

COP 3330 Final Exam Review

Android - Widgets Tutorial

XML Tutorial. NOTE: This course is for basic concepts of XML in line with our existing Android Studio project.

Introduction to Android Development

Object Oriented Programming. Java-Lecture 11 Polymorphism

Eventually, you'll be returned to the AVD Manager. From there, you'll see your new device.

CIS 110: Introduction to computer programming

Android Beginners Workshop

TWO-DIMENSIONAL FIGURES

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Transcription:

Custom Views in Android Tutorial The Android platform provides an extensive range of user interface items that are sufficient for the needs of most apps. However, there may be occasions on which you feel the need to implement a custom user interface for a project you are working on. In this tutorial we will work through the process of creating a custom View. To create and use our custom View, we will extend the View class, define and specify some custom attributes, add the View to our layout XML, override the ondraw method to tailor the View appearance and manipulate it from our app s main Activity. Step 1: Create an Android Project Create a new Android project in Eclipse. You can choose whatever settings you like as long as your app has a main Activity class and a layout file for it. We do not need any amendments to the Manifest file. Step 2: Create a View Class Our custom View can extend any of the existing Android View classes such as Button or TextView. However, we will create a direct subclass of View. Extending an existing class allows you to use the existing functionality and styling associated with that class, while providing processing to suit your own additional needs. Create a new class in your application by selecting the app s main package in Eclipse and choosing File, New, Class. Enter a name of your choice (good one to use: GoodView) and click Finish. Make your new class extend View by adding to its opening declaration line as follows: public class GoodView extends View { Add the following import statements above this: import android.content.context;

import android.content.res.typedarray; import android.graphics.canvas; import android.graphics.paint; import android.graphics.paint.style; import android.util.attributeset; import android.view.view; Step 3: Create Attribute Resources In order to use our custom View as we would use a standard View (i.e. set its attributes in layout XML and refer to them in our Java code), we will declare attribute resources. In Eclipse, create a new file in your project res/values folder by selecting it and choosing File, New, Other, Android XML Values File. Enter attrs as the file name and click Finish as the following screen shots show:

In the attributes file we first need to indicate that we are listing resources, so add the following parent element: <resources> </resources> Inside this element, we are going to declare three attributes for the View that will allow us to style it. Let s keep things relatively simple the View is going to display a circle with some text in the middle. The three attributes will be the circle color, the text String, and the text color. Add the following inside your resources element: <declare-styleable name="goodview"> <attr name="circlecolor" format="color" /> <attr name="circlelabel" format="string"></attr> <attr name="labelcolor" format="color"></attr> </declare-styleable> The declare-styleable element specifies the View name. Each attribute has a name and format. We will be able to specify these attributes in the layout XML when we add the custom View and also retrieve them in the View class. We will also be able to retrieve and set the attributes from our Java Activity class. The values provided for each attribute will need to be of the type listed here as format.

Step 4: Add the View to the Layout Let s add an instance of the custom View to our app s main layout file. In order to specify the custom View and its attributes, we need to add an attribute to the parent layout element. In the default project, it is a RelativeLayout but you can use whichever type you prefer. Add the following attribute to your layout s parent element: xmlns:custom="http://schemas.android.com/apk/res/edu.itu.customvi ew" Alter the package name to reflect the package your app is in. This specifies the namespace for our app, allowing us to use the attributes we defined within it. Now we can add an instance of the new View. Inside the layout, add it as follows: <edu.itu.customview.goodview android:id="@+id/custview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_margin="5dp" custom:circlecolor="#ff0099" custom:circlelabel="hello" custom:labelcolor="#ffff66" /> Again, alter the package name to suit your own, and the class name if necessary. We will use the ID to refer to the View in our Activity code. Notice that the element lists standard View attributes alongside custom attributes. The custom attributes are preceded by custom: and use the names we specified in our attributes XML file. Note also that we have specified values of the types we indicated using the format attributes in the attrs.xml file. We will retrieve and interpret these values in our View class. Step 5: Retrieve the Attributes Now let s turn back to the View class we created. Inside the class declaration, add some instance variables as follows: //circle and text colors private int circlecol, labelcol;

//label text private String circletext; //paint for drawing custom view private Paint circlepaint; We will use the first three of these to keep track of the current settings for color and text. The Paint object is for when we draw the View. After these variables, add a constructor method for your class: public GoodView (Context context, AttributeSet attrs) { super(context, attrs); As we are extending the View class, the first thing we do is call the superclass method. After the super call, let s extend the method to setup the View. Still in the constructor method, first instantiate the Paint object: //paint object for drawing in ondraw circlepaint = new Paint(); Now let s retrieve the attribute values we set in XML: //get the attributes specified in attrs.xml using the name we included TypedArray a = context.gettheme().obtainstyledattributes(attrs, R.styleable.GoodView, 0, 0); This typed array will provide access to the attribute values. Notice that we use the resource name we specified in the attrs.xml file. Let s now attempt to retrieve the attribute values, using a try block in case anything goes wrong: try { //get the text and colors specified using the names in attrs.xml circletext = a.getstring(r.styleable.goodview_circlelabel); circlecol = a.getinteger(r.styleable.goodview_circlecolor, 0); //0 is default labelcol = a.getinteger(r.styleable.goodview_labelcolor, 0);

finally { a.recycle(); We read the attributes into our instance variables. Notice that we use the names we listed for each in attrs.xml again. The colors are retrieved as integer values and the text label as a String. That s the constructor method complete by the time it has executed, the class should have retrieved the selected View attributes we defined in the attribute resources file and set values for in the layout XML. Step 6: Draw the View Now we have our View attributes in the class, so we can go ahead and draw it. To do this, we need to override the ondraw method. Add its outline after your constructor method as follows: @Override protected void ondraw(canvas canvas) { //draw the View Since we re going to draw a circle, let s get some information about the available space, inside the ondraw method: //get half of the width and height as we are working with a circle int viewwidthhalf = this.getmeasuredwidth()/2; int viewheighthalf = this.getmeasuredheight()/2; Now we can calculate the circle radius: //get the radius as half of the width or height, whichever is smaller //subtract ten so that it has some space around it int radius = 0; if(viewwidthhalf>viewheighthalf) radius=viewheighthalf-10; else

radius=viewwidthhalf-10; Now let s set some properties for painting with: circlepaint.setstyle(style.fill); circlepaint.setantialias(true); Now we will use the selected circle color as stored in our instance variable: //set the paint color using the circle color specified circlepaint.setcolor(circlecol); This means that the circle will be drawn with whatever color we listed in the layout XML. Let s draw it now using these details: canvas.drawcircle(viewwidthhalf, viewheighthalf, radius, circlepaint); Now let s add the text. First set the color using the value retrieved from the layout XML: //set the text color using the color specified circlepaint.setcolor(labelcol); Now set some more properties: //set text properties circlepaint.settextalign(paint.align.center); circlepaint.settextsize(50); Finally we can draw the text, using the text string retrieved: //draw the text using the string attribute and chosen properties canvas.drawtext(circletext, viewwidthhalf, viewheighthalf, circlepaint); That s ondraw complete. Run the program now and make sure you see the following output:

Step 7: Provide Get and Set Methods When you create a custom View with your own attributes, it is recommended that you also provide get and set methods for them in your View class. After the ondraw method, first add the get methods for the three customizable attributes: public int getcirclecolor(){ return circlecol; public int getlabelcolor(){ return labelcol; public String getlabeltext(){ return circletext;

Each method simply returns the value requested. Now add the set methods for the color attributes: public void setcirclecolor(int newcolor){ //update the instance variable circlecol=newcolor; //redraw the view invalidate(); requestlayout(); public void setlabelcolor(int newcolor){ //update the instance variable labelcol=newcolor; //redraw the view invalidate(); requestlayout(); These methods accept int parameters representing the color to set. In both cases we update the instance variable in question, then prompt the View to be redrawn. This will make the ondraw method execute again, so that the new values affect the View displayed to the user. Now add the set method for the text: public void setlabeltext(string newlabel){ //update the instance variable circletext=newlabel; //redraw the view invalidate(); requestlayout(); This is the same as the other two set methods except for the String parameter. We will call on these methods in our Activity class next. Step 8: Manipulate the View from the Activity

Now we have the basics of our custom View in place, let s demonstrate using the methods within our Activity class. In the app s main Activity class, add the following import statements: import android.graphics.color; import android.view.view; Before the oncreate method, inside the class declaration, add an instance variable representing the instance of the custom View displayed: private GoodView myview; Inside the oncreate method, after the existing code, retrieve this using its ID as included in the XML layout file: myview = (GoodView)findViewById(R.id.custView); To demonstrate setting the View attribute values from the Activity, we will add a simple button. Open your layout file and add it after the custom View element: <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:onclick="btnpressed" android:text="@string/btn_label" /> We specify a method to execute on user clicks we will add this to the Activity class. First add the String to your res/values/strings XML file: <string name="btn_label">press Me</string> Check to make sure the button shows by running your app again.

Now go back to the Activity class and add the method listed for clicks on the button. Let s use the set methods we defined to update the custom View appearance: public void btnpressed(view view){ myview.setcirclecolor(color.green); myview.setlabelcolor(color.magenta); myview.setlabeltext("help"); This is of course just to demonstrate how you can interact with a custom View within your Activity code. When the user clicks the button, the appearance of the custom View will change.

Conclusion In general, it s advisable to use existing Android View classes where possible. However, if you do feel that you need a level of customization beyond the default settings, creating your own custom Views is typically straightforward. What we have covered in this tutorial is really just the beginning when it comes to creating tailored Android user interfaces.