Sunday, July 5, 2009

My first time experience with Android Webkit

As I was trying to play around with WebKit, I tried to load an web page through it in Android. A good starting point for WebKit may be found at

http://developer.apple.com/documentation/Cocoa/Conceptual/DisplayWebContent/DisplayWebContent.html .

The source code of my android application is pretty straight forward.

It goes like this:

public class WebKitExample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

WebView webView;

setContentView(R.layout.main);

webView = (WebView)findViewById(R.id.appView);

webView.getSettings().setJavaScriptEnabled(true);

webView.loadUrl("http://www.google.com");
}
}

We need to add the XML resource in the main.layout as the following:

(WebView android:id="@+id/appView"
android:layout_height="wrap_content"
android:layout_width="fill_parent" /)

We also need to add the permission to the manifest file as the following:

(uses-permission android:name = "android.permission.INTERNET" /)

And the application will look like the following in the emulator.



Although the example shown here is pretty simple but it can be a starting point in learning Webkit in Android. Hope this helps the newbies of Android.

Sunday, June 14, 2009

Parameterized factory design pattern in Android Media Service Framework

As i was going through the Media framework of Android, i have found the implementation of a parameterized factory pattern in the way MediaPlayerService class creates the concrete media players.

Let me give an idea of the parameterized factory implementation as discussed in the GoF book. It goes like this.

class Creator {

public:

virtual Product* CreateProduct( ProductId id);

};

And the implementation will look like the following:

Product* Creator :: CreateProduct (ProductId id)
{

if (id == Product1) return new Product1;

if (id == Product2) return new Product2;

//repeat for the other products

return 0;

}

Product1, Product2 etc are all derived from the base class Product.

Now let us dissect the Media Framework of Android to see how this design pattern has been implemented to create the different Media players.

The base class of all the players are MediaPlayerInterface which is again derived from MediaPlayerBase.

MediaPlayerService has got a static function called

"static sp createPlayer(player_type playerType, void* cookie, notify_callback_f notifyFunc)"

which actually takes care of the creation of the concrete players namely PVPlayer, MidiFile and VorbisPlayer.

Hence the class MediaPlayerService works as the Factory class for creating the Concrete Players besides handling other responsibilities.

The class MediaPlayerService can be found at \base\media\libmediaplayerservice of the Android source code.

The createPlayer function goes like the following :

static sp(MediaPlayerBase) createPlayer(player_type playerType, void* cookie,
notify_callback_f notifyFunc)
{
sp(MediaPlayerBase) p;
switch (playerType) {
#ifndef NO_OPENCORE
case PV_PLAYER:
LOGV(" create PVPlayer");
p = new PVPlayer();
break;
#endif
case SONIVOX_PLAYER:
LOGV(" create MidiFile");
p = new MidiFile();
break;

case VORBIS_PLAYER:
LOGV(" create VorbisPlayer");
p = new VorbisPlayer();
break;
}
if (p != NULL) {
if (p->initCheck() == NO_ERROR) {
p->setNotifyCallback(cookie, notifyFunc);
} else {
p.clear();
}
}
if (p == NULL) {
LOGE("Failed to create player object");
}
return p;
}

As we can see from the above code that MediaPlayerBase here works as the base class Product. And we create different products (different concrete media players) through the function createPlayer which works as the CreateProduct function in the example at the beginning.

The above similarity shows how a Parameterized Factory Pattern has been implemented in the Android Media Framework by MediaService layer to create different Media Players.

Wednesday, June 3, 2009

Composite Design Pattern in Android View and Widget

The Intent of this design pattern is stated in the GoF book as "Compose Objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly".

To explain it in a simpler fashion, let me give the same example as given in the GoF book. Suppose there is an object called Picture, a graphics object. This picture may consist of other pictures recursively as well as primitive objects like line, rectangle objects etc. All of these part objects which make the whole picture conform to the same Graphic interface. Hence to the client, a part object appears same as the whole picture consisted of other part objects. To draw a whole object, the client simply traverses through the whole picture and draws different parts.

The class diagram of the composite design pattern will look like the following:




The following participants take part in this design pattern:

Component -

it declares the interface for the objects ( part as well as whole)
helps in managing the objects (adding, removing)

Leaf -

represents leaf objects which don't have any children
these are the primitive objects

Composite -

defines behavior for components having children
stores the children

Client -

takes help of the Component interface to manipulate different objects

If you want to know more about the Composite Design Pattern, please have a look at

http://som-itsolutions.blogspot.in/2008/12/composite-design-pattern-is-structural.html

Its all about the theoretical side of the Composite Design Pattern. Now let us try to dissect the Android View and the Widget folders (which are available at \\base\core\java\android) to see how this design pattern has been implemented there.

In Android, the View class works as the Component class. However, the child management part (add component, remove component) has been moved to the Composite class which is the ViewGroup class. Actually the Add and Remove of a component has been declared in an interface called ViewManager and the ViewGroup implements that interface. Also the interface for a Composite object is declared as ViewParent interface and the ViewGroup (the Composite object) implements that as well.

The leaf classes like Button, ImageView etc are deduced either by directly subclassing the View (Component) or from the subclasses of the View (for example, the Button class is derived from TextView class which in turn is directly derived fron the View class). The Composite Class (ViewGroup) is deduced by directly subclassing the View and by implementing the two interfaces namely ViewParent (which defines the interface of a composite object) and ViewManager (which defines the interface from adding and removing components).

As expected the getParent function which is needed to get the Parent of a component is put in the View class (the Component).

The Composite object (ViewGroup) has an array to hold its children.

The simplified version of the class diagram of the Android View and Widgets are as follows:



For simplicity i have not shown the two interfaces namely ViewManager and ViewParent.

Now let us consider the class diagram as presented in the beginning of this discussion. There is a function called Operation. In Android implementation, the onDraw function in the Component (View) plays this role. The DispatchDraw function (which is called when the children are to be drawn) in the composite (ViewGroup) object actually traverses through the list of the objects and calls draw on each of the child object.
This becomes clear when we see the android source code of the dispatchDraw function in the andrroid.view.ViewGroup class. The code is as follows:

 @Override
 protected void More dispatchDraw(Canvas canvas) {

......................
.....................
....................

 for (int i = 0; i < count; i++) {
                final View child = children[i];
                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || 
                                              child.getAnimation() != null)
               {
                   more |= drawChild(canvas, child, drawingTime);
               }
         }
......................
......................

For simplicity, in the class diagram it is shown that the dispatchDraw function is directly calling the onDraw function. However it actually takes help of another function called drawChild which is called on each child object of the ViewGroup object.

This way we can say that Android View and Widgets are some sort of implementation of the Composite Design Pattern.

Sunday, May 31, 2009

Observer Pattern in Java

As i was going through the different source code files of the Java Util package, i found the implementation of the Observer Pattern ( see the GoF book for more information on this pattern) in the two classes - namely Observer.java and Observable.java. i would like to throw some lights on these two classes. These two classes can be found in the Java\j2se\src\share\classes\java\util folder of the JDK source code.

But first of all, i need to give you a practical example of why we need observer pattern in the first place.

Suppose, we have a document which can be viewed simultaneously by three different views – say one view represents a line graph chart, another view represents it in a spreadsheet, yet another view represents a pie chart. Now suppose the spreadsheet view makes some modification to the document. If the other two views don't update themselves with this changed state of the document, different views will be in inconsistent states. So we need some mechanism to notify the other two views whenever the spreadsheet view updates the document. This is done through Observer pattern in which whenever the document changes stete, it notifies all of its views. The views in turn updates themselves with the latest data.
The class diagram will look like the following.




And the sequence diagram of this pattern is like this.


What these two diagrams essentially depict is that in the Observer Pattern, we have a Subject, which can attach one or more Observers through its Attach() function. Whenever it changes its state it Notifies all the attached Observers through its Notify function. The observers in turn synchronize their states with that of the Subject through the GetSubjectState function.

Now let me try to dissect the Java observer pattern.

Let us first start with the Observable.java class. As the name suggests it is the class which will implemented functionalities for being observed. Or in other words it is the class which helps in designing the Subject class of the Observer pattern discussion of the GoF book. We need to extend this class to get the Subject class.

Let us try to dissect this class. The following functions are there in this class:

Data Members: It has a vector to hold all the observers that are interested in observing this observable class. It has another boolean data member called "changed" to indicate if anything has changed in the Subject class ( which will be derived from this Observable class).

Constructor : This class has a no argument constructor to construct an empty vector of Observers.

Member Functions :

  • addObserver : To add an observer to its list of Observers.

  • deleteObserver : To delete a particular observer from the list of the observers

  • notifyObservers : there are two overloaded versions of this function. One takes an Object parameter as an argument and the other does not take any argument. The task of this function is to notify all the attached observers when any data of the subject gets changed. To check whether the data is changed it evaluates the boolean "changed" data member. This function also calls the update function of each observer objects to ask them to get in sync with the subject's changed state. The overloaded version that takes an one argument parameter is used to let the observers know about which attribute is changed. And the other version of this function which does not take any argument does not let the observer know about which attribute is changed.
  • deleteObservers : This function removes all the observers attached to this subject.

  • setChanged : This function sets the boolean data member "changed".

  • clearChanged : This function resets the boolean data member "changed".

  • hasChanged : This function helps us to know whether the data of the subject has been changed or not. 

  • countObservers : This function returns the number of observers attached to this subject.
This is all about the Observable class which helps us to define to Subject class.

The Observer.java defines an interface called Observer having just one abstract function called update (Observable o, Object arg). As the name suggests, the Observer class that will implement this interface will override the update function to set the attribute passed as an argument (arg) from the Subject class. This method is called whenever any attribute in the Subject class gets changed.

Now let us try to see an example to understand how this Observer Pattern is used.

Let us first extend the Observable class to create the Subject class.

package com.somitsolutions.training.java.observerpattern;

import java.util.Observable;

public class Subject extends Observable {

private String name;
private float price;

public Subject(String name, float price) {
this.name = name;
this.price = price;
}

public String getName() {
return name;
}
public float getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers(name);
}

public void setPrice(float price) {
this.price = price;
setChanged();
notifyObservers(new Float(price));
}
}

As this is clear from the implementation of the Subject class, that whenever we call the setter function to change the attributes of the Subject's object, we call the notifyObservers and pass that attribute as a parameter.


Now let us see how we create two different observers namely NameObserver and PriceObserver to observe these two attributes of the Subject class.

// An observer of name changes.
package com.somitsolutions.training.java.observerpattern;

import java.util.Observable;
import java.util.Observer;

public class NameObserver implements Observer {

private String name;
public NameObserver() {
name = null;
System.out.println("NameObserver created: Name is " + name);
}
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
if (arg instanceof String) {
name = (String)arg;
System.out.println("NameObserver: Name changed to " + name);
}
}
}


// An observer of price changes.
package com.somitsolutions.training.java.observerpattern;

import java.util.Observable;
import java.util.Observer;

public class PriceObserver implements Observer {

private float price; public PriceObserver() {
price = 0;
System.out.println("PriceObserver created: Price is " + price);
}
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
if (arg instanceof Float) {
price = ((Float)arg).floatValue();
System.out.println("PriceObserver: Price changed to " + price);
}
}

}

As it has become clear from the above two implementations that the update function actually helps in synchronizing the state of the concrete observers with that of the Subject.

Now the client of the Observer framework will look like the following :

package com.somitsolutions.training.java.observerpattern;

public class Main {

public static void main(String args[]) {

// Create the Subject and Observers.
Subject s = new Subject("Kheer Kadam", 20.5f);

NameObserver nameObs = new NameObserver();
PriceObserver priceObs = new PriceObserver();

// Add those Observers!
s.addObserver(nameObs);
s.addObserver(priceObs);

//Initial Subject States
System.out.println("Initial states of Subject");
System.out.println("Name : " + s.getName());
System.out.println("Price : " + Float.toString(s.getPrice()));

// Make changes to the Subject.
s.setName("Gulabjamun"); // It prints NameObserver: Name changed to Gulabjamun

s.setPrice(15.0f); //It prints PriceObserver: Price changed to 15.0

s.setPrice(30.5f); //It prints PriceObserver: Price changed to 30.5

s.setName("Rasgulla"); // It prints NameObserver: Name changed to Rasgulla
}
}

Hope the above discussion will help people understand of how the Java supports implementing the Observer pattern.

Thursday, March 12, 2009

Bridge Pattern in C++



When I studied almost all of the Gang of Four Design Patterns in 2005 or 2006, I knew only one language: C++.

Now I am proficient in multiple software languages and my viewpoint about Design Patterns has also matured...

So, here we go.

Here's the source code of the Bridge Pattern, the code is extracted from the presentation.

//Coord.h

#ifndef COORD_H

#define COORD_H


struct Coord {

int x, y;

Coord(int x = 0, int y = 0) : x(x), y(y) {}

};


#endif


// Window.h


#ifndef WINDOW_H

#define WINDOW_H


#include "Coord.h"

#include "WindowImp.h"


class Window {

public:

Window();

virtual ~Window();


void GetWindowImp(int typeOfImplementation); // Attaches implementation

void DrawLine(const Coord& begin, const Coord& end);

void DrawRect(const Coord& topLeft, const Coord& bottomRight);


protected:

WindowImp* imp = nullptr;

};


class IconWindow : public Window {

public:

void DrawBorder(const Coord& topLeft, const Coord& bottomRight);

};


class TransientWindow : public Window {

// Can add specific behavior if needed

};


#endif



// Window.cpp


#include "Window.h"

#include "WindowSystemFactory.h"

#include <iostream>


Window::Window() {}


Window::~Window() {

delete imp;

}


void Window::GetWindowImp(int typeOfImplementation) {

imp = WindowSystemFactory::Instance()->MakeWindowImp(typeOfImplementation);

}


void Window::DrawLine(const Coord& begin, const Coord& end) {

if (imp) imp->DeviceLine(begin, end);

}


void Window::DrawRect(const Coord& topLeft, const Coord& bottomRight) {

if (imp) imp->DeviceRect(topLeft, bottomRight);

}


void IconWindow::DrawBorder(const Coord& topLeft, const Coord& bottomRight) {

DrawRect(topLeft, bottomRight); // Uses bridged implementation

}


// WindowImp.h

#ifndef WINDOWIMP_H

#define WINDOWIMP_H


#include "Coord.h"


class WindowImp {

public:

virtual ~WindowImp() = default;

virtual void DeviceLine(const Coord& begin, const Coord& end) = 0;

virtual void DeviceRect(const Coord& topLeft, const Coord& bottomRight) = 0;

};


class XWindowImp : public WindowImp {

public:

void DeviceLine(const Coord& begin, const Coord& end) override;

void DeviceRect(const Coord& topLeft, const Coord& bottomRight) override;

};


class PMWindowImp : public WindowImp {

public:

void DeviceLine(const Coord& begin, const Coord& end) override;

void DeviceRect(const Coord& topLeft, const Coord& bottomRight) override;

};


#endif


// WindowImp.cpp


#include "WindowImp.h"

#include <iostream>


void XWindowImp::DeviceLine(const Coord&, const Coord&) {

std::cout << "XWindow: Drawing Line\n";

}


void XWindowImp::DeviceRect(const Coord&, const Coord&) {

std::cout << "XWindow: Drawing Rectangle\n";

}


void PMWindowImp::DeviceLine(const Coord&, const Coord&) {

std::cout << "PMWindow: Drawing Line\n";

}


void PMWindowImp::DeviceRect(const Coord&, const Coord&) {

std::cout << "PMWindow: Drawing Rectangle\n";

}



// WindowSystemFactory.h

#ifndef WINDOWSYSTEMFACTORY_H

#define WINDOWSYSTEMFACTORY_H


class WindowImp;


enum WindowImplementation {

XWindowImplementation,

PMWindowImplementation

};


class WindowSystemFactory {

public:

static WindowSystemFactory* Instance();

WindowImp* MakeWindowImp(int type);


private:

WindowSystemFactory() = default;

static WindowSystemFactory* instance;

};


#endif


// WindowSystemFactory.cpp

#include "WindowSystemFactory.h"

#include "WindowImp.h"


WindowSystemFactory* WindowSystemFactory::instance = nullptr;


WindowSystemFactory* WindowSystemFactory::Instance() {

if (!instance) {

instance = new WindowSystemFactory();

}

return instance;

}


WindowImp* WindowSystemFactory::MakeWindowImp(int type) {

if (type == XWindowImplementation) return new XWindowImp();

if (type == PMWindowImplementation) return new PMWindowImp();

return nullptr;

}



//============================================================================

// Name : BridgePattern.cpp

// Author : Som

// Version :

// Copyright : som-itsolutions

// Description : Hello World in C++, Ansi-style

//============================================================================


#include "Window.h"

#include "Coord.h"

#include "WindowSystemFactory.h"

#include <iostream>


int main() {

const Coord pt0(1, 2);

const Coord pt1(7, 8);


// X-based Icon Window

IconWindow* xIcon = new IconWindow();

xIcon->GetWindowImp(XWindowImplementation);

xIcon->DrawBorder(pt0, pt1);


// PM-based Transient Window

TransientWindow* pmTransient = new TransientWindow();

pmTransient->GetWindowImp(PMWindowImplementation);

pmTransient->DrawRect(pt0, pt1);


// PM-based Icon Window

IconWindow* pmIcon = new IconWindow();

pmIcon->GetWindowImp(PMWindowImplementation);

pmIcon->DrawLine(pt0, pt1);


delete xIcon;

delete pmTransient;

delete pmIcon;


return 0;

}

Sunday, January 25, 2009

Android Widget - through Java Code

There are two ways to create android resources/view - either through the XML layout or through pure java code. In this article I have tried to implement the android view through the second method - i.e. through Java code. I have implemented a Table Layout and few widgets like static text, edit box and slider bar. There are three sets of all these widgets - namely Red, Green and Blue. These three are the percentage of the RGB color code. For example if we make Red as 100, and Green and Blue as 0, it will paint the background of the device with Red. It has also shown how to create a prompt dialog when you enter a value more than 100 in any of the edit boxes.

The application will look like the following:



The code for this application is as follow -

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class Widget extends Activity implements View.OnClickListener /*, View.OnKeyListener */{
/** Called when the activity is first created. */

private final static int idLayout = 1;
private final static int idTitle = 2;

private final static int idTextRed = 3;
private final static int idTextGreen = 4;
private final static int idTextBlue = 5;

private final static int idEditRedText = 6;
private final static int idEditGreenText = 7;
private final static int idEditBlueText = 8;

private final static int idSeekBarRed = 9;
private final static int idSeekBarGreen = 10;
private final static int idSeekBarBlue =11;

private final static int idButtonOK = 12;

private final static int MaxColorValue = 255;

private int RedProgress = 0;
private int GreenProgress = 0;
private int BlueProgress = 0;

private int RedValue = 0;
private int GreenValue = 0;
private int BlueValue = 0;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

TableLayout layout = new TableLayout(this);
layout.setId(idLayout);
layout.setLayoutParams(
new LayoutParams(LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.FILL_PARENT));
layout.setFocusable(true);

TextView title = new TextView(this);
title.setText(R.string.title);
title.setLayoutParams(
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
//title.s(Alignment.ALIGN_CENTER);
title.setId(idTitle);
layout.addView(title,0);


//For Item 1
TextView ItemRed = new TextView(this);
ItemRed.setFocusable(true);
ItemRed.setText("% RED");
ItemRed.setTextColor(Color.LTGRAY);
ItemRed.setLayoutParams(
new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));

//Give the menu item an ID for tracking reasons.
//The ID is a static int defined locally to the class
ItemRed.setId(idTextRed);
//Add it to our linear layout
layout.addView(ItemRed, 1);

EditText EditTextRed = new EditText(this);
EditTextRed.setFocusable(true);
EditTextRed.setLayoutParams(
new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
EditTextRed.setId(idEditRedText);

layout.addView(EditTextRed, 2);

SeekBar SeekBarRed = new SeekBar(this);
SeekBarRed.setFocusable(true);
SeekBarRed.setLayoutParams(
new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
SeekBarRed.setMax(MaxColorValue);
SeekBarRed.setId(idSeekBarRed);


layout.addView(SeekBarRed, 3);


//For item 2
TextView ItemGreen = new TextView(this);
ItemGreen.setFocusable(true);
ItemGreen.setText("% GREEN");
ItemGreen.setTextColor(Color.LTGRAY);
ItemGreen.setLayoutParams(
new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));


//Give the menu item an ID for tracking reasons.
//The ID is a static int defined locally to the class
ItemGreen.setId(idTextGreen);
//Add it to our linear layout
layout.addView(ItemGreen, 4);

EditText EditTextGreen = new EditText(this);
EditTextGreen.setFocusable(true);
EditTextGreen.setLayoutParams(
new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
EditTextRed.setId(idEditGreenText);

layout.addView(EditTextGreen, 5);

SeekBar SeekBarGreen = new SeekBar(this);
SeekBarGreen.setFocusable(true);
SeekBarGreen.setLayoutParams(
new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
SeekBarGreen.setMax(MaxColorValue);
SeekBarGreen.setId(idSeekBarGreen);
layout.addView(SeekBarGreen, 6);


TextView ItemBlue = new TextView(this);
ItemBlue.setFocusable(true);
ItemBlue.setText("% BLUE");
ItemBlue.setTextColor(Color.LTGRAY);
ItemBlue.setLayoutParams(
new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));


//Give the menu item an ID for tracking reasons.
//The ID is a static int defined locally to the class
ItemBlue.setId(idTextBlue);
//Add it to our linear layout
layout.addView(ItemBlue, 7);


EditText EditTextBlue = new EditText(this);
EditTextBlue.setFocusable(true);
EditTextBlue.setLayoutParams(
new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
EditTextBlue.setId(idEditBlueText);

layout.addView(EditTextBlue, 8);

SeekBar SeekBarBlue = new SeekBar(this);
SeekBarBlue.setFocusable(true);
SeekBarBlue.setLayoutParams(
new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
SeekBarBlue.setMax(MaxColorValue);
SeekBarBlue.setId(idSeekBarBlue);
layout.addView(SeekBarBlue, 9);

Button OKBtn = new Button(this);
OKBtn.setFocusable(true);
OKBtn.setLayoutParams(
new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
OKBtn.setId(idButtonOK);
OKBtn.setText("OK");
layout.addView(OKBtn,10);


setContentView(layout);

OKBtn.setOnClickListener(this);

SeekBarRed.setOnSeekBarChangeListener(OnSeekBarProgress);
SeekBarGreen.setOnSeekBarChangeListener(OnSeekBarProgress);
SeekBarBlue.setOnSeekBarChangeListener(OnSeekBarProgress);
}

OnSeekBarChangeListener OnSeekBarProgress =
new OnSeekBarChangeListener() {

public void onProgressChanged(SeekBar s, int progress, boolean touch){

if(touch){
TableLayout layout = (TableLayout)s.getParent();

EditText Red = (EditText)layout.getChildAt(2);
EditText Green = (EditText)layout.getChildAt(5);
EditText Blue = (EditText)layout.getChildAt(8);

if(s.getId()== idSeekBarRed ){
RedProgress = progress;
Red.setText(Integer.toString(RedProgress*100/254));
}

if(s.getId()== idSeekBarGreen ){

GreenProgress = progress;
Green.setText(Integer.toString(GreenProgress*100/254));
}


if(s.getId()== idSeekBarBlue ){

BlueProgress = progress;
Blue.setText(Integer.toString(BlueProgress*100/254));
}

int color = Color.rgb(RedProgress, GreenProgress, BlueProgress);
layout.setBackgroundColor(color);

}
}

public void onStartTrackingTouch(SeekBar s){

}

public void onStopTrackingTouch(SeekBar s){

}
};


public void onClick(View v){

Button b = (Button)v;

if(b.getId() == idButtonOK){

TableLayout layout = (TableLayout)(v.getParent());

EditText Red = (EditText)layout.getChildAt(2);
EditText Green = (EditText)layout.getChildAt(5);
EditText Blue = (EditText)layout.getChildAt(8);

SeekBar SeekBarRed = (SeekBar)layout.getChildAt(3);
SeekBar SeekBarGreen = (SeekBar)layout.getChildAt(6);
SeekBar SeekBarBlue = (SeekBar)layout.getChildAt(9);


String RedText = Red.getText().toString();
String GreenText = Green.getText().toString();
String BlueText = Blue.getText().toString();


if(!("".equals(RedText))) {
try {
RedValue = Integer.parseInt(RedText);
}
catch (NumberFormatException e) {
}
}
else
RedValue = 0;


if(!("".equals(GreenText))) {
try {
GreenValue = Integer.parseInt(GreenText);
}
catch (NumberFormatException e) {
}
}
else
GreenValue = 0;

if(!("".equals(BlueText))) {
try {
BlueValue = Integer.parseInt(BlueText);
}
catch (NumberFormatException e) {
}
}
else
BlueValue = 0;


if( RedValue>=0 && RedValue<=100) {
RedProgress = 254*RedValue/100;
SeekBarRed.setProgress(RedProgress);
}

else {
new AlertDialog.Builder(this)
.setTitle("Alert!")
.setMessage("Please enter a value between 0 and 100 for RED...")
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing – it will close on its own
}
})
.show();
}

if( GreenValue>=0 && GreenValue<=100) {
GreenProgress = 254*GreenValue/100;
SeekBarGreen.setProgress(GreenProgress);
}

else {
new AlertDialog.Builder(this)
.setTitle("Alert!")
.setMessage("Please enter a value between 0 and 100 for GREEN...")
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing – it will close on its own
}
})
.show();
}

if(BlueValue>=0 && BlueValue<=100) {
BlueProgress = 254*BlueValue/100;
SeekBarBlue.setProgress(BlueProgress);
}

else {
new AlertDialog.Builder(this)
.setTitle("Alert!")
.setMessage("Please enter a value between 0 and 100 for BLUE...")
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing – it will close on its own
}
})
.show();
}

int color = Color.rgb(RedProgress, GreenProgress, BlueProgress);
layout.setBackgroundColor(color);

}

};
}


Play around with it.

Feel happy to work in Android...