Android Studio – Importing Library Projects

So Recently I moved to using Android Studio as my primary development environment for Android of course. The switch was simple and Studio has some really nice productivity feature to help you write code quickly. However I did find that importing library projects a little tricky initially especially having little to no knowledge of Gradle and how it works. So I thought I would write up a short post describing how.

Steps to Import Android Library to your Project

  1. Create folder in top level called libraries (same level as target,.idea)
  2. copy the library project into this folder
  3. Open Project Structure (Right-Click on Top Level Project)
  4. Click + icon towards top left
  5. Import Module
  6. Import the module you copied into libraries
  7. Click on the library name (left hand nav bar)
  8. If the library you are using has any dependencies that your project uses you can remove these on dependency tab (i.e Support Libs)
  9. Click on your project in the left hand nav bar
  10. Select dependency tab and add the new library module to your project, Apply and close

Thats the basic setting to apply a module to your project running the project will probably result in Gradle errors at this stage, because Gradle cant build the project or even find it. Edit the following files

settings.gradle 

include ':libraries:library-name',':project_name'

project_name/project_name/build.gradle

add in

    compile project (':libraries:view-pager')

Finally

If building the code at this point still gives you gradle errors your library project probably cant be built because it doesnt have an appropriate build.gradle using this template build file should help you get the project building.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android-library'

dependencies {
    compile 'com.android.support:support-v4:13.0.+'
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 16
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            res.srcDirs = ['res']
        }
    }
}

Hopefully this short guide will help anyone that faced the same problems I had at the beginning

CSS3 – Animating the DOM – Part 2

Have a look at this JSFiddle to see what we will be creating in this section JS Fiddle with all 4 effects. So last post (see here) we spoke about basic transitions using ease-in-out. In this post we will look at other transitions, transitional properties and maybe some transformations too.

Last time we used ease-in-out to create some basic transformations using the opacity levels of an image to fade it out. Lets start by looking at other kinds of basic transitions available to use.

Basic Transitions

ease-in-out is considered a timing function this states how the animation will play out. Here are some other stock functions you can play with.

  • ease – steady pace of animation
  • ease-in  – slowly build up
  • ease-out – start fast and slow towards the end
  • ease-in-out – slowly build up and slowly come to end
  • linear – same momentum throughout time

You can use these timing functions to modify the execution of your animation based on the time you have specified. Playing around with these alone allows you to create animations and interactivity that most websites today cant offer. You can however build more advanced timing functions using this tool Ceaser Transition Creator however use advanced animations with caution.

TIP – Avoid Motion Sickness in your app.

A tip I have found useful when creating web apps. Once you are comfortable with animation in CSS/HTML the overwhelming urge is to animate everything in your application. You start to look at the static DOM elements as boring because they have no life or activity. Depending on the context of your application start by picking one element that you think “That would be really cool if that moved like this when I done this … that would be impressive”. Take that element and animate it, spend time getting the animation fluid and in keeping with the app i.e no photoshop style sliding text with car engines sounding as it speeds across the screen. If you do this you will find clients and users of your application will notice that one singular animation, and it stands out rather than drowned in a sea of flying divs.

I hope this section has covered the basic concept around transitions and how they work. I could have went into more detail around timings and delays but feel they are pretty self explanatory if there are any gaps let me know im happy to add some detail in. To see a list of all properties that can be animated look here

Transforms

So now you should be comfortable with transitions lets add some transformations to the mix. There are commonly 2 type of transforms 2D and 3D lets start with 2D.

4 Examples of 2D transforms

Skew

Code:

#div1 {
margin:100px;
height:100px;
width:100px;
transition:all 1s ease-in;
perspective: 400px;
perspective-origin: 50% 100px;
background:red;
color:white;
}
#div1:hover {
-webkit-transform:skew(180deg);
}

Result

Skew a square with CSS
Skew a square with CSS

Rotate

Code: change the hover code to match below

#div1:hover {
-webkit-transform:rotate(180deg);
}

css3-rotate

Scale

Code: change the hover code to match below

#div1:hover {
-webkit-transform:scale(180deg);
}

The following link will show all 3 effects in action with code side by side

http://jsfiddle.net/cmac458/FraRU/2/

Hopefully this give you an insight into how to add transforms to you html elements and you can now link these to the transitions as explained in part 1 to create some interesting layouts and effects.

Responsive Web Development

I have been struggling recently to find anytime to work on any pet projects due to work commitments. As you may have picked up from previous blog posts my first choice framework for web apps is usually bootstrap, Bootstrap is a framework for rapidly prototyping web applications created by the Twitter team. Over the last year or so Bootstrap has grown in popularity and many sites can be easily recognisable by the default theme.

Twitter Bootstrap Default
Twitter Bootstrap Default

Recently I wanted to try out the responsive functionality of Bootstrap, as expected it is easy and quick to create a simple application that can be scaled across devices without any great need to write any additional CSS media queries. By chance I came across Foundation by Zurb, a framework similar to bootstrap in many respects but maybe for more experienced developers, it also has a great range of templates and mobile specific responsive functionality built in. I decided to take a look and at first I wasn’t so keen but the framework forces you to create more custom elements rather than reusing the standard to death so in practice you will usually end up with a unique looking application. Features like off canvas elements and mobile CSS classes make creating mobile web experiences much easier in Foundation.

Foundation by Zurb Template
Foundation by Zurb Template

I hope to get back to doing some more work on my Dart projects soon but due to work I have been focusing on more traditional technologies. Hope to try update this blog a lot more often this year starting …. Now.

Dart Canvas

I entered the Github GameOff at the start of the month and forgot all about it, The GameOff is a hackathon for the month of November that requires participants to create web based game. Seeing as I would like to learn some of the principles of game design I thought I would proceed anyway in my spare time with my entry. Since I have been experimenting with Dart I decided that it would be a good place to start.

 

GitHub GameOff 2012 – Theres still time !

The Basics 

I have never used canvas in anger and decided this would be my start point for my Game/Application (of which I still have no idea what it will be). There are a lot of tutorials available for canvas and HTML5, however most of them will be in Javascript they can be easily ported to DART. Check out the Mozilla Developer Network for some really good tutorials. I like to write about the work Iv done on my blog especially when its new to me, as I find it helps secure the new concepts by writing about them and also hope to share my experiences.

Getting Started 

canvas.html

Ok. So your ready to start and you have created a new DART project. Open the .html page and add a canvas element to the document (see example)

<canvas id='canvas' width='450' height='450'> </canvas>

You can add a fallback element below incase the browser of the user doesn’t support canvas. However this should be bare minimum to run in chromium.

canvas.dart

Open the DART file. I created a new class for my application called Game. Feel free to name your class whatever you wish

It is important to understand the two main elements we will be working with.

CanvasElement – This is the element in which all the drawing data will be rendered. This correlates to the element you specified in your html.

CanvasRenderingContext2D –  Implementation of CanvasRenderingContext this is the class that will allow you to draw the shapes onto the #canvas surface.

Declare both of these variables at the top of your class like so

CanvasElement canvas;
CanvasRenderingContext2D ctx;
int WIDTH;
int HEIGHT;

Now its time to set these, you can do this in the initialisation of your class, However I put this logic in an init() method

canvas = document.query('#canvas');
ctx = canvas.getContext('2d');
WIDTH = canvas.width;
HEIGHT = canvas.height;
player = new Player(ctx);
requestRedraw();

The observant will notice that the code above calls request redraw this will be vital in maintaining an animation loop later in the tutorial. The only logic in this method for a basic implementation will be

window.requestAnimationFrame(draw);

In this call to requestAnimationFrame you pass in the method that you wish to use to draw your scene. In my example this is called simply draw. For now create an empty method

void draw(num _){
//Logic will be added later
}

You now have the canvas element and drawing context for your app available for use. Lets start drawing.

Drawing on Canvas 

Now you have set up the structure for you application, Lets look at how you can draw basic shapes onto the canvas.

Again place this logic wherever you prefer in your application as long as its execution comes after the above steps. I created a new method called createCanvasBg()

void drawCanvasBg(){

ctx.fillStyle = ‘black’;

ctx.fillRect(0, 0, WIDTH , HEIGHT);

}

Now in the draw method you implemented as part of the set up, add a call to drawCavasBg() in your method body. Run the application making sure you have kicked off the initialisation code in the main execution block. If successful you should see that you now have a black box on your screen. Not very exciting I know !

Create a new method(createSquare) or add logic to your execution block that will create the new square on the screen. Follow the implementation below


ctx.fillStyle = 'red';

// ctx.fillRect(x,y,height,width)
ctx.fillRect(100, 100, 50 , 50);

In order to draw a circle add the following instead of fillRect use the arc function.

context.arc(x, y, radius, 0 , 2 * Math.PI, false);

Run your application again and you should see a nice red square added to the canvas.

What you should have at this point

Conclusion

I hoped to provide a very very basic tutorial of canvas with dart as often drawing and graphics in the browser can intimidate people. This is how I got started and I was able to see what’s possible, I am currently contemplating making a simple platform game with a similar structure. Time allowing I hope to update this tutorial series as I go sharing my new experiences in the area. Next we will look at adding a player to the canvas that we can control using the arrow keys. This will be the hero for our game. I have also started looking at Dart Box2D a popular Javascript physics engine that has been ported to Dart, which I would suggest looking at if you havent already Seth Ladd from Google Dart Team has a good series of tutorials on his blog for this also.

Dart is a great language I am really enjoying developing with it and hoping to get more involved in the open source development of the language working on a few bugs at the moment. Just trying to find time out with work can be very difficult. I hope  you find this series useful I will continue to update my progress of my Github GameOff submission as it evolves (if it evolves :S)

Dart Touch

For those of you that have been following my blog you will know I have been experimenting with Dart and the DOM. I have made a couple of simple example applications as learning aids such as PicsAPuzzle and more recently the Conundrum word game.

During these experiments I battled with touch interactions on tablet/mobile devices, so I decided to make a library that allows you to easily add User Interactions to any html element on your page.

What is Dart Touch ?

The idea behind dart touch is that it will apply vey basic styling and actions to any html element, thus meaning you have to write less code and be generally more productive when creating interactive content

How to use it ?

dart touch is designed to be very easy to use and very flexible in terms of implementation. Previously to create a touch compatible drag n drop element would require you to map these event handlers and code each of the related methods.

 tile.on.dragStart.add(_onDragStart);
 tile.on.dragEnd.add(_onDragEnd);
 tile.on.dragEnter.add(_onDragEnter);
 tile.on.dragOver.add(_onDragOver);
 tile.on.dragLeave.add(_onDragLeave);
 tile.on.drop.add(_onDrop);
 tile.on.touchStart.add(_onTouchStart);
 tile.on.touchMove.add(_onTouchMove);
 tile.on.touchEnd.add(_onTouchEnd);
 tile.on.touchLeave.add(_onTouchLeave);
void _onDragStart(MouseEvent event) {
 }
void _onDragEnd(MouseEvent event) {
 }
void _onDragEnter(MouseEvent event) {
}
void _onDragOver(MouseEvent event) {
}
void _onDragLeave(MouseEvent event) {
}
void _onTouchStart(TouchEvent event){
 }
void _onTouchEnd(TouchEvent event){
 }
void _onTouchMove(TouchEvent event){
 }
void _onTouchLeave(TouchEvent event){
 }
void _onDrop(MouseEvent event) {
}

This requires 9 methods to be individually coded to do very simple and basic actions to allow elements to be dragged and dropped with other items. With dart touch all you require is to add the css from the base.css file to your own projects css file and set the interaction you require via the setMethod from dart touch. example below

touch.setDragNDropTouch(element);

Passing this element into the set method will set all those interactions we looked at earlier for you, this only provides a basic implementation of all interactions if you want to further customise the Event Handlers you can create you own and add it to the basic implementation. Example

card.on.drop.add(_onDropCheck);

This doesn’t overwrite the functionality of onDrop it simply adds further functionality.

Conundrum 

My latest Dart experiment Conundrum is an extremely difficult word game, simply as there are no hint’s yet. But basically rearrange the letters to spell the 9 letter word. Conundrum is made with dart_touch to show how the interactions can be used and extended. You can view the demo here

Conundrum Example

Conclusion 

Dart Touch is very young at the time of reading exactly one day old !!! It currently only supports drag n drop actions, I plan on adding more in the future when time allows out with my day job. The code is fully open source and I would love people to contribute, fix bugs and help me out.

Source Code – https://github.com/cmac458/dart_touch

If you want to chat about it please get in contact on Google Plus or Twitter @cmac457

Thanks for reading, hope you find dart touch helpful !

 

DART – MergeSort

Since I have started using DART many people have asked why I like it so much. As a Java developer at my roots I appreciate being able to code in an environment I am comfortable in, I believe this also makes us more efficient as programmers. As proof to some colleagues I decided to take one of the main sorting algorithms in a CS Grads tool belt the classic Merge Sort and code it in Dart as an experiment to show how similar it is.

class Sorting {

var unsorted ;
List placeholder;

var length;

List sort(List values) {
this.unsorted = values;
length = values.length.toInt();
placeholder = new List(length);
mergeSort(0, length-1);
return unsorted;

}

void mergeSort(low,high){

if(low < high) {
var middle = ((low+high)/2).toInt();
mergeSort(low,middle);
mergeSort((middle+1), high);

merge(low,middle,high);
}
}

void merge(int low, int middle, int high){

for (int i = low; i <= high; i++){
placeholder[i] = unsorted[i];
}
int i = low;
int j = middle+1;
int k = low;

while (i <= middle && j <= high){
if (placeholder[i] <= placeholder[j]){
unsorted[k] = placeholder[i];
i ++;
}else{
unsorted[k] = placeholder[j];
j++;
}
k++;
}

while (i <= middle){
unsorted[k] = placeholder[i];
k++;
i++;
}
}

}

As you can see the above code looks very similar to the Java equivalent. The next step was to create a test package to test the logic of the merge sort. Dart has the very handy unittest.dart package that helps us create JUnit style tests that can be run via the editor or via the command line.

import '../packages/unittest/unittest.dart';
import '/C:/Users/O325882/dart/Sorting/web/Sorting.dart';

void main(){
Sorting sorter = new Sorting();
test('Merge_Worst', () => expect(sorter.sort([5,4,3,2,1]),orderedEquals([1,2,3,4,5])));
test('Merge_Best', () => expect(sorter.sort([1,2,3,4,5]),orderedEquals([1,2,3,4,5])));

}

As everyone can see there are many similarities between DART and more OO focused languages specifically Java. Making it very easier for Java devs to move into doing funky things with the browser and embrace HTML5 technologies.

Touch Events HTML5 – Drag n Drop (DART)

My last post focused on my simple app PicsAPuzzle which can be viewed here (picture below)

PicsAPuzzle
Iteration 1 of PicsAPuzzle

The purpose of the app was a quick learning project for me become more comfortable with Dart. The biggest criticism I had with the project was that I couldn’t play it on my mobile device or iPad. This entered me into find out how to add interactivity via touch events to the html web app.

HTML5 Touch Events 

The HTML5 specification may be huge and still growing but there is a lot of handy features that you may not know exist. Touch Events are one. I wanted to implement Drag and Drop the same way I could with a mouse but using my finger instead. HTML offers onDrag and onDrop event handlers for this. However with touch these do not exist. The three basic touch events are

  • touchStart
  • touchEnd
  • touchMove

There are more such as touchLeave but these 3 are all you need for most tasks. A touch event has 3 list each that contain the number of touches ie fingers on the screen at the time of firing the event.

  • touches
  • targetTouches
  • changedTouches

You set touchEvents the same way as any other kind of event (example in Dart)

tile.on.touchStart.add(_onTouchStart);

Points to consider when using TouchEvents

  1. Zooming – On mobile devices moving multiple fingers about the screen can result in the webpage being zoomed in/out. You may want to prevent this. I recommend doing so for drag n drop operations, You can prevent with following meta tag :
    <meta name="viewport" 
      content="width=device-width, initial-scale=1.0, user-scalable=no">
  2. Scrolling – Especially with Drag n Drop interactions moving your finger around a screen is the default way to scroll a page on mobile devices so using the following code in you handler methods will prevent such interactions with the browser
    event.preventDefault();

Implementing Drag n Drop 

So that covers the basics of touch event’s and how best to prepare your application for mobile devices. We will start looking at implementation of Drag n Drop. Code snippets have been commented to describe the logic without writing addition paragraphs on them.

onTouchStart 

This method works very similarly to the onDragStart/onDragEnter methods. You want to capture the element being dragged and apply some style to the element to indicate to the user that the element is selected and draggable.


void _onTouchStart(TouchEvent event){
//stop scrolling by default
event.preventDefault();
//capture drag target
Element dragTarget = event.target;
//add style to element to indicate its moving
dragTarget.classes.add('moving');
_dragSourceEl = dragTarget;
}

onTouchMove

The event is fired when the finger moves across the screen from its starting co ordinates. Tracking the finger until it stops allows us to simulate the mouse moving across the screen. What I did for this was to capture the co ordinates of the first fingers position and find out which element the finger was over, that way when the finger is removed we know the last place it visited.


void _onTouchMove(TouchEvent event){
//indicate to user element is in motion
_dragSourceEl.classes.add('moving');
//prevent all default behaviour ie Scrolling
event.preventDefault();
//Get the current x,y position of the first finger and find the element it is over
_dropTarget = document.elementFromPoint(event.touches[0].pageX,event.touches[0].pageY);
// If the finger is over an element indicate that in the UI
if(_dropTarget != null){
_dropTarget.classes.add('over');
}
}

 

onTouchEnd

The implementation of the onTouchEnd method will be identical to the onDrop method in the last tutorial I wrote – Getting Started : Dart. You are completing the same logic think of lifting your finger off the screen as depressing the mouse button. If you are unsure of the implementation you can look back at the last post here

 

Conclusion 

I still have some work to do in regards to the css styling as we dont have as many transition states with touch events I have to streamline the css to provide a smoother dragging effect. However this should get most people started with implementing their own Drag n Drop HTML5 web app. If you have any questions do post them I will try my best to answer. Im likely to be very busy im working on a new utility library to make creating cross platform interactions much easier, so will post progress on that or anyone interested in helping out can contact me here too.

[Update PicsAPuzzle responsive template is broken at time of writing so please be patient with it]

Thank for reading, Dont forget to check out PicsAPuzzle on Github I aim to create a few more small apps to experiment with different interactions. All constructive feedback is welcome.

Chris