According to my reasearch which I was doing in past few months I got to some conclusions on how to structure your application for best code reusability.
Several patterns come to my mind, Module, Namespace, immediate functions, returning objects, using subobjects, using capitalized letters for functions/variables as "Constants", function scope and making accessor methods, JS constructors, using Yuidoc and Jasmine for better code quality.
Download the code from here: https://github.com/bluePlayer/practices/tree/master/AppStructure
Here is roughly what I am thinking about:
var externalJSLibrary = {},
jquery = {},
extJS = {},
expressJS;
window.APP = window.APP || (function (wdo, lib1, lib2, lib3) {'use strict';
var version = "1.0.0",
config = {},
parent = null,
jqueryObj = lib1,
extJSObj = lib2,
expressJsObj = lib3,
windowDocumentObject = wdo,
MY_APP_NAME = "MyJSApplication",
MY_EXCEPTION_MESSAGE = "My exception message",
MY_APP_CONSTANT = "some message";
return {
Exceptions: {
MyFirstException: function () {
return {
message: MY_EXCEPTION_MESSAGE,
name: "MyFirstException"
};
}
},
Constants: {
MY_APP_NAME: function () {
return MY_APP_NAME;
},
MY_APP_CONSTANT: function () {
return MY_APP_CONSTANT;
}
},
Events: {
keyDownEvent: function (event) {
// do some stuff when some key is pressed down on 'keydown' event.
},
keyUpEvent: function (event) {
// do some stuff when some key is released on 'keyup' event
},
keyPressEvent: function (event) {
// do some stuff when 'keypress' event was detected
}
},
initApp: function (someObject, config) {
var i;
for (i in someObject) {
if (someObject[i] !== null && typeof someObject[i] === 'object') {
if (someObject[i].hasOwnProperty('init')) {
someObject[i].init(config);
}
parent.initApp(someObject[i], config);
}
}
},
namespace: function (nsString, newObjectDefinition) {
var parts = nsString.split('.'),
helperObject = {},
that = this,
i = 0,
field = {};
if (parts[0] === that.Constants.MY_APP_NAME()) {
parts = parts.slice(1);
}
for (i = 0; i < parts.length; i += 1) {
if (that[parts[i]] === undefined) {
for (field in newObjectDefinition) {
if (newObjectDefinition.hasOwnProperty(field)) {
helperObject[field] = newObjectDefinition[field];
}
}
that[parts[i]] = helperObject;
}
that = that[parts[i]];
}
return that;
},
customFunction: function (a, b) {
if (b < 0) {
throw new parent.Exceptions.MyFirstException();
} else {
return 0;// do some stuff with a and b
}
},
doSomeStuffWithJquery: function (someUrl) {
jqueryObj.ajax({
url: someUrl,
xhrFields: {
withCredentials: true
}
});
},
doSomeStuffWithExtJS: function () {
extJSObj.drawGraph();
},
doSomeStuffWithExpressJS: function () {
expressJsObj.connectWithNodeJS();
},
init: function (configObject) {
config = configObject;
parent = this;
parent.initApp(parent, config);
}
};
}(window.document, jquery, extJS, expressJS));
window.APP.namespace('MySubObject', (function (lib) {'use strict';
var config = {},
parent = null,
someLibrary = lib,
MY_CONSTANT = "my constant",
MY_EXCEPTION = "my exception";
return {
Exceptions: {
MyNewException: function () {
return {
message: MY_EXCEPTION,
name: "MyNewException"
};
}
},
Constants: {
MY_CONSTANT: function () {
return MY_CONSTANT;
}
},
name: "MySubObject",
myCustomFunction: function () {
// do some stuff
},
init: function (configObj) {
config = configObj;
parent = this;
}
};
}(externalJSLibrary)));
window.document.addEventListener("DOMContentLoaded", function (event) {'use strict';
var myApp = window.APP;
myApp.init({
"event": event,
otherConfig: {}
});
window.document.addEventListener('keydown', myApp.Events.keyDownEvent);
window.document.addEventListener('keyup', myApp.Events.keyUpEvent);
window.document.addEventListener('keypress', myApp.Events.keyPressEvent);
});
Programming and tech blog. PHP, Java, Android, JavaScript, HTML5
Showing posts with label application. Show all posts
Showing posts with label application. Show all posts
Thursday, February 26, 2015
Wednesday, January 28, 2015
JavaScript "constants"
I did a bit of research about constants in JavaScript. Well guess what, there are no constants in JavaScript. :)
So how do you implement "constants" with JavaScript patterns and syntax?
Note: The next text might require more readings but if will help you learn lot of JavaScript basics. Probably you will never have to use this code, since existing JS librarires have already solved this issue somehow.
Constants are important concept of every programming language and definetelly you should use them whenever possible. For example let just say you have an error message that needs to be printed in the output field from several places in your code. How are you sure that each time you write that string of message is written without missing letters? Sometimes you are tired, sometimes you rush and therefore errors are inevitable. So to prevent this you create a constant that contain that string and use the constant instead of writing the string.
Example constant: CANNOT_DIVIDE_BY_ZERO = "Cannot divide by zero!";
I have been developing a practice application which you can access live here: http://jspractices-blueplayer.rhcloud.com/Calculator/ and the docs are here: http://jspractices-blueplayer.rhcloud.com/Calculator/docs
Also you may preview the HTML/JavaScript code here: https://github.com/bluePlayer/practices/tree/master/CalculatorJS.
The code also passes JSLint test, with only "jslint browser: true" option.
There are two important functions which you should check, Constants() and namespace().
Constants() is a constructor function and namespace() creates subobject of the main application object called window.APP.
Lets start with namespace() function. It recieves two parameters, first the name of the subobject that will be created and second is the configuration object which contains necessary properties and methods that will be contained in this new subobject. namespace() creates new subobject Constants using the new keyword, secondly creates constMap subobject which will contain accessible keys for each of the constants.
Example:
window.APP.namespace('Trigonometry', (function () {
return {
PI: 3.14,
doSomeStuff: function () {
}
}
}()));
This example creates Trigonometry subobject of window.APP and Trigonometry contains two subobjects, Constants with methods, get(), set(), isDefined() and list() and constMap which has one key/value, PI: "PI" and ofcourse the function doSomeStuff() which does nothing.
So with my solution you can create immutable constants by just passing key/value pair (key must be all capitalized letters) and the code will create it for you. Well if we create a PI constant how do we get the value? The solution is straight forward but it looks very ugly and big.
Example:
console.log(window.APP.Trigonometry.Constants.get(window.APP.Trigonometry.constMap.PI));
// prints 3.14
Alternatively you can pass the name of the constant if you know it:
console.log(window.APP.Trigonometry.Constants.get("PI"));
hahah :D
To improve this solution a bit I created an application wide function in APP namespace called getConst(). You send the path of the constant in string format.
Example:
console.log(window.APP.getConst('APP.Trigonometry.PI')); // prints 3.14
What happens in this function is parsing the string parameter and getting to the constant value trough the application tree. But this solution is against the "Constants" concept. Either I should be careful to write that string parameter properly or I should create a variable/property inside APP to contain that string and then use it in the above example, like so:
window.APP = window.APP || (function () {
var TRIGONOMETRY_PI = 'APP.Trigonometry.PI';
return {
getConst: function (constantPath) {
// code
},
doSomeStuff: function () {
console.log(this.getConst(TRIGONOMETRY_PI));
}
}
}()));
window.APP.doSomeStuff(); // prints 3.14
So this brings us to the best solution to the problem, and that is creating variables with capitalized letters in closure and then using capitalized accessor methods for them.
Example: I will create GRAVITY = 9.8 constant in new subobject of APP, called Physics.
window.APP.namespace('Physics', (function () {
var GRAVITY = 9.8;
return {
GRAVITY: function () {
return GRAVITY;
}
};
}()));
console.log(window.APP.Physics.GRAVITY()); // prints 9.8
This will create subobject Physics in window.APP and it will contain constMap object with one key/value pair, GRAVITY which is function(). I changed namespace() function to create function in constMap if the capitalized key contains value of a function instead of a value. If I just send this key/value pair: GRAVITY: 9.8, the namespace() function would have created key/value pair in constMap, like so: GRAVITY: "GRAVITY" and you have to access constant's value using the long statement in the previous examples.
To clear things up, you don't even need to create Constants() constructor in your application, you can use variable with closure and accessor methods with capitalized names to represent constants. I created this constMap subobject just to separate constants from other properties/methods in a given object. You don't even need it.
Note: there are some rummors that ECMAScript 7 or was it 6, will contain const keyword. Until then you can use capitalized variable and methods with closure to represent "constants".
If you have any thoughts on the topic, let me know.
So how do you implement "constants" with JavaScript patterns and syntax?
Note: The next text might require more readings but if will help you learn lot of JavaScript basics. Probably you will never have to use this code, since existing JS librarires have already solved this issue somehow.
Constants are important concept of every programming language and definetelly you should use them whenever possible. For example let just say you have an error message that needs to be printed in the output field from several places in your code. How are you sure that each time you write that string of message is written without missing letters? Sometimes you are tired, sometimes you rush and therefore errors are inevitable. So to prevent this you create a constant that contain that string and use the constant instead of writing the string.
Example constant: CANNOT_DIVIDE_BY_ZERO = "Cannot divide by zero!";
I have been developing a practice application which you can access live here: http://jspractices-blueplayer.rhcloud.com/Calculator/ and the docs are here: http://jspractices-blueplayer.rhcloud.com/Calculator/docs
Also you may preview the HTML/JavaScript code here: https://github.com/bluePlayer/practices/tree/master/CalculatorJS.
The code also passes JSLint test, with only "jslint browser: true" option.
There are two important functions which you should check, Constants() and namespace().
Constants() is a constructor function and namespace() creates subobject of the main application object called window.APP.
Lets start with namespace() function. It recieves two parameters, first the name of the subobject that will be created and second is the configuration object which contains necessary properties and methods that will be contained in this new subobject. namespace() creates new subobject Constants using the new keyword, secondly creates constMap subobject which will contain accessible keys for each of the constants.
Example:
window.APP.namespace('Trigonometry', (function () {
return {
PI: 3.14,
doSomeStuff: function () {
}
}
}()));
This example creates Trigonometry subobject of window.APP and Trigonometry contains two subobjects, Constants with methods, get(), set(), isDefined() and list() and constMap which has one key/value, PI: "PI" and ofcourse the function doSomeStuff() which does nothing.
So with my solution you can create immutable constants by just passing key/value pair (key must be all capitalized letters) and the code will create it for you. Well if we create a PI constant how do we get the value? The solution is straight forward but it looks very ugly and big.
Example:
console.log(window.APP.Trigonometry.Constants.get(window.APP.Trigonometry.constMap.PI));
// prints 3.14
Alternatively you can pass the name of the constant if you know it:
console.log(window.APP.Trigonometry.Constants.get("PI"));
hahah :D
To improve this solution a bit I created an application wide function in APP namespace called getConst(). You send the path of the constant in string format.
Example:
console.log(window.APP.getConst('APP.Trigonometry.PI')); // prints 3.14
What happens in this function is parsing the string parameter and getting to the constant value trough the application tree. But this solution is against the "Constants" concept. Either I should be careful to write that string parameter properly or I should create a variable/property inside APP to contain that string and then use it in the above example, like so:
window.APP = window.APP || (function () {
var TRIGONOMETRY_PI = 'APP.Trigonometry.PI';
return {
getConst: function (constantPath) {
// code
},
doSomeStuff: function () {
console.log(this.getConst(TRIGONOMETRY_PI));
}
}
}()));
window.APP.doSomeStuff(); // prints 3.14
So this brings us to the best solution to the problem, and that is creating variables with capitalized letters in closure and then using capitalized accessor methods for them.
Example: I will create GRAVITY = 9.8 constant in new subobject of APP, called Physics.
window.APP.namespace('Physics', (function () {
var GRAVITY = 9.8;
return {
GRAVITY: function () {
return GRAVITY;
}
};
}()));
console.log(window.APP.Physics.GRAVITY()); // prints 9.8
This will create subobject Physics in window.APP and it will contain constMap object with one key/value pair, GRAVITY which is function(). I changed namespace() function to create function in constMap if the capitalized key contains value of a function instead of a value. If I just send this key/value pair: GRAVITY: 9.8, the namespace() function would have created key/value pair in constMap, like so: GRAVITY: "GRAVITY" and you have to access constant's value using the long statement in the previous examples.
To clear things up, you don't even need to create Constants() constructor in your application, you can use variable with closure and accessor methods with capitalized names to represent constants. I created this constMap subobject just to separate constants from other properties/methods in a given object. You don't even need it.
Note: there are some rummors that ECMAScript 7 or was it 6, will contain const keyword. Until then you can use capitalized variable and methods with closure to represent "constants".
If you have any thoughts on the topic, let me know.
Labels:
application,
browser,
calculator,
constants,
github,
html5,
javascript,
patterns,
rhcloud
Monday, December 8, 2014
Geometric Photo Filter - Web browser application
I run this application in Opera 26.0 on my Asus middle class laptop. It was run on 100 steps per frame and it performs well, not overloading the processor. Give it a day maybe it will redraw the complete image.
You can run this application on Firefox, Chrome and Opera perfectly. I have Firefox 34, Chrome 40, and Opera 26.0 I also tried on Safari 5.1.7 and Internet Explorer 9. Turns out they do not support File API and Filereader.
![]() |
Safari 5.1.7 |
![]() |
IE 9 |
Labels:
application,
asus,
browser,
bugatti,
chrome,
filter,
firefox,
geometric,
html5,
internet explorer,
javascript,
laptop,
opera,
opera 26.0,
photo,
safari,
web
Thursday, July 25, 2013
Simple Gallery App in Android
I have recently worked on a simple Gallery application in Android.
It has one ImageView component, two buttons, previous and next and one TextView for description. It is a gallery application for European cars. Actually I have 27 car brands and one model (image) for each brand. I added 27 images which are all 640 x 480 pixels (You can download images from Google) into CarTestApp/res/drawable-mdpi folder.
I was testing my app on Nexus 7 AVD emmulator.
Here is how you application should look like.
I will show you some tricks I used in this small app, like how to access all drawable objects.
Ok so here is my layout file:
My strings.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">CartTestApp</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="image_view">Image description</string>
<string name="prev_btn">prev</string>
<string name="next_btn">next</string>
<string name="car_name_text_view">Car Name</string>
</resources>
I added Utils.java file for a helper function. It is only one function but I guess I will expand the application future.
Utils.java:
package com.testpkg.carttestapp;
public class Utils {
public static String formatFirstLetterOfString(String str) {
String result = "";
result = str.substring(0, 1).toUpperCase()
+ str.substring(1).toLowerCase();
return result;
}
}
Next class I added is called CarNames.java. It has many static functions so that I don't need to instantiate an object of this class. No need to.
Here it is:
Check these lines:
public static Field[] nativeDrawables = android.R.drawable.class
.getFields();
public static Field[] drawables = com.testpkg.carttestapp.R.drawable.class
.getFields();
Function getFields() returns the fields in a given resource from our application.
For example android.R.drawable contains native android drawable resources while com.testpkg.cartestapp.R.drawable contains drawable resources that we have added to our application.
So actually we can search our resources with code.
I have two ArrayList objects, one for drawable ids and one for drawable string names. I also have a hash map with drawable id as a key and car string name as a value.
Here is the reset() function in which I fill my lists and the hash map:
public static void reset() {
for (Field field : drawables) {
try {
if (!field.getName().equals("ic_launcher")) {
carIdsList.add(field.getInt(field.getName()));
carStringsList.add(formatCarFieldName(field.getName()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 0; i < carStringsList.size(); i += 1) {
carNamesList.put(carIdsList.get(i), carStringsList.get(i));
}
}
You may noticed this function formatCarFieldName(); I can use java function toUpperCase() but that will make all letters upper case. I don't want that, I wan only the first letter upper cased. Strings are immutable values so I make a concatenation trick like this one:
result = str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
which will upper case only the first letter. You can find this in the Utils class.
Some screen shots:
It has one ImageView component, two buttons, previous and next and one TextView for description. It is a gallery application for European cars. Actually I have 27 car brands and one model (image) for each brand. I added 27 images which are all 640 x 480 pixels (You can download images from Google) into CarTestApp/res/drawable-mdpi folder.
I was testing my app on Nexus 7 AVD emmulator.
Here is how you application should look like.
I will show you some tricks I used in this small app, like how to access all drawable objects.
Ok so here is my layout file:
My strings.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">CartTestApp</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="image_view">Image description</string>
<string name="prev_btn">prev</string>
<string name="next_btn">next</string>
<string name="car_name_text_view">Car Name</string>
</resources>
I added Utils.java file for a helper function. It is only one function but I guess I will expand the application future.
Utils.java:
package com.testpkg.carttestapp;
public class Utils {
public static String formatFirstLetterOfString(String str) {
String result = "";
result = str.substring(0, 1).toUpperCase()
+ str.substring(1).toLowerCase();
return result;
}
}
Next class I added is called CarNames.java. It has many static functions so that I don't need to instantiate an object of this class. No need to.
Here it is:
Check these lines:
public static Field[] nativeDrawables = android.R.drawable.class
.getFields();
public static Field[] drawables = com.testpkg.carttestapp.R.drawable.class
.getFields();
Function getFields() returns the fields in a given resource from our application.
For example android.R.drawable contains native android drawable resources while com.testpkg.cartestapp.R.drawable contains drawable resources that we have added to our application.
So actually we can search our resources with code.
I have two ArrayList objects, one for drawable ids and one for drawable string names. I also have a hash map with drawable id as a key and car string name as a value.
Here is the reset() function in which I fill my lists and the hash map:
public static void reset() {
for (Field field : drawables) {
try {
if (!field.getName().equals("ic_launcher")) {
carIdsList.add(field.getInt(field.getName()));
carStringsList.add(formatCarFieldName(field.getName()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 0; i < carStringsList.size(); i += 1) {
carNamesList.put(carIdsList.get(i), carStringsList.get(i));
}
}
You may noticed this function formatCarFieldName(); I can use java function toUpperCase() but that will make all letters upper case. I don't want that, I wan only the first letter upper cased. Strings are immutable values so I make a concatenation trick like this one:
result = str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
which will upper case only the first letter. You can find this in the Utils class.
Some screen shots:
Tuesday, July 2, 2013
Playing around with Android
After some playing with my code on CheckerBoard application, I got to some interesting results.
I wanted to cover all colors from the visible spectre but didn't had the real success . Anyway here is what I achieved so far :)
I used some settings in Android manifest like:
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
in the activity tag. The first one makes sure your app always runs in portrait mode. The second removes the title bar with the battery and notifictaions area.
I wanted to cover all colors from the visible spectre but didn't had the real success . Anyway here is what I achieved so far :)
I used some settings in Android manifest like:
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
in the activity tag. The first one makes sure your app always runs in portrait mode. The second removes the title bar with the battery and notifictaions area.
For publishing an update to the same application you should export your application with changed version code number in AndroidManifest.xml like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="2"
If your version code was 1, make it 2, if it was 2 make it 3 and so on...
Labels:
android,
application,
first,
nexus,
nexus7
Sunday, June 30, 2013
Signing and publishing your app on Google play
In this post I will explain how to self sign your application and how to publish it on Google Play store.
First you must signup for a developers account here .It is a fee of $25 that you pay only once and your account will exist as long as it is not closed i.e for a lifetime. After you finish registration, you will be redirected to a screen for uploading new application. But before you upload your app you must be sure that it is signed and zip aligned apk package.
Using Eclipse it is very easy to sign and zip align your application. There are two types of signing: debug and release.
Debug signing:
When installing Android plugin for eclipse, one debug keystore (debug.keystore) is generated for you and it is located in Users/username/.android folder on Windows. You cannot run your apps even on AVD unless they are signed. But since there is debug keystore trough eclipse, you can test your apps without problems. Note that you can use keytool in java sdk bin folder to generate key for you manually.
Release signing:
About release signing you can again use Eclipse to generate new keystore and your key with your password and therefore sign you application for publishing. Just follow the instructions in Eclipse after clicking right click on the app project node in Package explorer and then selectiong Export menu item. In the next window select Android -> Export Android application.
Once you have signed your app it is ready for publishing.
Publishing your application
Go to this page for publishing. Click add new application to create your Google play application. Choose language and call it MyTestApp. Press upload APK. Give the new app a description, add two bigger images for the specific device that you plan your app to work on and also don't forget app icon 512x512 size. Choose App type, Category and Content rating. Add your website and email and click save. You are one step closer to publishing. Now on the left menu click Pricing and Distribution.
Select all countries and choose below options as you like. I choosed only the last two. Click save.
Now go up and on the right click publish button. You are done, now several hours are necesary before your app becomes available on Google Play.
Cheers :)))
First you must signup for a developers account here .It is a fee of $25 that you pay only once and your account will exist as long as it is not closed i.e for a lifetime. After you finish registration, you will be redirected to a screen for uploading new application. But before you upload your app you must be sure that it is signed and zip aligned apk package.
Using Eclipse it is very easy to sign and zip align your application. There are two types of signing: debug and release.
Debug signing:
When installing Android plugin for eclipse, one debug keystore (debug.keystore) is generated for you and it is located in Users/username/.android folder on Windows. You cannot run your apps even on AVD unless they are signed. But since there is debug keystore trough eclipse, you can test your apps without problems. Note that you can use keytool in java sdk bin folder to generate key for you manually.
Release signing:
About release signing you can again use Eclipse to generate new keystore and your key with your password and therefore sign you application for publishing. Just follow the instructions in Eclipse after clicking right click on the app project node in Package explorer and then selectiong Export menu item. In the next window select Android -> Export Android application.
Once you have signed your app it is ready for publishing.
Publishing your application
Go to this page for publishing. Click add new application to create your Google play application. Choose language and call it MyTestApp. Press upload APK. Give the new app a description, add two bigger images for the specific device that you plan your app to work on and also don't forget app icon 512x512 size. Choose App type, Category and Content rating. Add your website and email and click save. You are one step closer to publishing. Now on the left menu click Pricing and Distribution.
Select all countries and choose below options as you like. I choosed only the last two. Click save.
Now go up and on the right click publish button. You are done, now several hours are necesary before your app becomes available on Google Play.
Cheers :)))
Labels:
android,
application,
nexus,
nexus7,
tutorial
First Android Application
In this short tutorial I will show you how to convert the screen of your Nexus 7 into checker board.
I assume you have installed java 1.6 or 1.7, Eclipse classic (Juno) with plugin for Android and these Android packages: Android 4.2.2, 4.0.3 and 2.3.3 with SDK, Documentation, Google APIs, ARM EABI, Samples for SDK and Tools all 3 packages.
First create Android application in Eclipse and call it CheckerBoardApp. Leave everything default except when creating the project set Theme to none. You can also rename the java package from example to... lets say CheckerBoardPkg or you can leave it default.For publishing your app on Google Play you must change the package name to something different than example because it will not be accepted
Once you have the new application generated add new java class in the main src folder and call it CheckerBoard.
Add this code in it and save:
package com.checkerboardpkg.checkerboardapp;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class CheckerBoard extends View {
private final int TILE_WIDTH_HEIGHT = 160;
private Paint currentPaint = null;
public CheckerBoard(Context context) {
super(context);
currentPaint = new Paint();
setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
int currentColor = 0;
for (int i = 0; i < 8; i += 1) {
for (int j = 0; j < 5; j += 1) {
// set up color and Paint object
if ((i + j) % 2 == 0) {
currentColor = Color.WHITE;
} else {
currentColor = Color.BLACK;
}
currentPaint.setAntiAlias(true);
currentPaint.setColor(currentColor);
// draw rectangles to form checker board
canvas.drawRect(j * this.TILE_WIDTH_HEIGHT, i
* this.TILE_WIDTH_HEIGHT, (j + 1)
* this.TILE_WIDTH_HEIGHT, (i + 1)
* this.TILE_WIDTH_HEIGHT, currentPaint);
}
}
}
}
Basically what we do here is we create 8 rows and 5 columns of rectangles into the Canvas. We check the counters i and j if their sum is even or odd number and we change the color to white and than black appropriatelly. Each rectangle is 160x160 pixels so we get exactly 800x1280 screen which is the exact size of Nexus 7 screen resolution.
Now you must set the content of main acitivity to be the CheckerBoard view. We do that by adding this line
setContentView(new CheckerBoard(this));
as last statement in
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(new CheckerBoard(this));
}
function in MainActivity.java class.
Now the code is ready but to see it in action you must create Android Virtual Machine to run it on.
In Eclipse press Window -> Android Virtual Device Manager and that click New. Name it Nexus7AVD, Device: Nexus 7, target: Android 4.2.2, and set RAM to 512. It is 1024 by default but it may not start up if on Windows with low memory. Set SD card to 100 MB. Click OK.
Then press start and then launch. Wait some time while the AVD is not started. After you see the batery icon on top, your AVD is ready to run so go to Eclipse and right click on the project node in package explorer and click Run as -> Android Application.
Here is what you should see:
Mine app was called TileGame, but you should see CheckerBoardApp instead
I assume you have installed java 1.6 or 1.7, Eclipse classic (Juno) with plugin for Android and these Android packages: Android 4.2.2, 4.0.3 and 2.3.3 with SDK, Documentation, Google APIs, ARM EABI, Samples for SDK and Tools all 3 packages.
First create Android application in Eclipse and call it CheckerBoardApp. Leave everything default except when creating the project set Theme to none. You can also rename the java package from example to... lets say CheckerBoardPkg or you can leave it default.For publishing your app on Google Play you must change the package name to something different than example because it will not be accepted
Once you have the new application generated add new java class in the main src folder and call it CheckerBoard.
Add this code in it and save:
package com.checkerboardpkg.checkerboardapp;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class CheckerBoard extends View {
private final int TILE_WIDTH_HEIGHT = 160;
private Paint currentPaint = null;
public CheckerBoard(Context context) {
super(context);
currentPaint = new Paint();
setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
int currentColor = 0;
for (int i = 0; i < 8; i += 1) {
for (int j = 0; j < 5; j += 1) {
// set up color and Paint object
if ((i + j) % 2 == 0) {
currentColor = Color.WHITE;
} else {
currentColor = Color.BLACK;
}
currentPaint.setAntiAlias(true);
currentPaint.setColor(currentColor);
// draw rectangles to form checker board
canvas.drawRect(j * this.TILE_WIDTH_HEIGHT, i
* this.TILE_WIDTH_HEIGHT, (j + 1)
* this.TILE_WIDTH_HEIGHT, (i + 1)
* this.TILE_WIDTH_HEIGHT, currentPaint);
}
}
}
}
Basically what we do here is we create 8 rows and 5 columns of rectangles into the Canvas. We check the counters i and j if their sum is even or odd number and we change the color to white and than black appropriatelly. Each rectangle is 160x160 pixels so we get exactly 800x1280 screen which is the exact size of Nexus 7 screen resolution.
Now you must set the content of main acitivity to be the CheckerBoard view. We do that by adding this line
setContentView(new CheckerBoard(this));
as last statement in
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(new CheckerBoard(this));
}
function in MainActivity.java class.
Now the code is ready but to see it in action you must create Android Virtual Machine to run it on.
In Eclipse press Window -> Android Virtual Device Manager and that click New. Name it Nexus7AVD, Device: Nexus 7, target: Android 4.2.2, and set RAM to 512. It is 1024 by default but it may not start up if on Windows with low memory. Set SD card to 100 MB. Click OK.
Then press start and then launch. Wait some time while the AVD is not started. After you see the batery icon on top, your AVD is ready to run so go to Eclipse and right click on the project node in package explorer and click Run as -> Android Application.
Here is what you should see:
Subscribe to:
Posts (Atom)