The document provides information about an Android application development training tutorial. It discusses how to create custom buttons, color pickers, and dialog boxes in Android applications. The training covers programatically drawing custom buttons with different states, creating a color picker dialog to select colors, and using different types of dialog boxes like alerts, yes/no dialogs, and lists in apps.
Android Application Development Training Tutorial - Learn How to Develop Android Apps
1. Android Application Development Training Tutorial
For more info visit
http://www.zybotech.in
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
2. Applications
Color Picker
MainActivity.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements
ColorPickerDialog.OnColorChangedListener {
/** Called when the activity is first created. */
private static final String BRIGHTNESS_PREFERENCE_KEY = "brightness";
private static final String COLOR_PREFERENCE_KEY = "color";
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
Button btn = (Button) findViewById(R.id.Button01);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int color = PreferenceManager.getDefaultSharedPreferences(
MainActivity.this).getInt(COLOR_PREFERENCE_KEY,
Color.WHITE);
new ColorPickerDialog(MainActivity.this, MainActivity.this,
color).show();
}
});
}
@Override
public void colorChanged(int color) {
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(
COLOR_PREFERENCE_KEY, color).commit();
tv.setTextColor(color);
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
3. }
}
ColorPicker.java
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
public class ColorPickerDialog extends Dialog {
public interface OnColorChangedListener {
void colorChanged(int color);
}
private final OnColorChangedListener mListener;
private final int mInitialColor;
private static class ColorPickerView extends View {
private final Paint mPaint;
private final Paint mCenterPaint;
private final int[] mColors;
private final OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color) {
super(c);
mListener = l;
mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF,
0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 };
Shader s = new SweepGradient(0, 0, mColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
4. mPaint.setStrokeWidth(32);
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
private boolean mTrackingCenter;
private boolean mHighlightCenter;
protected void onDraw(Canvas canvas) {
float r = CENTER_X - mPaint.getStrokeWidth() * 0.5f;
canvas.translate(CENTER_X, CENTER_X);
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
if (mTrackingCenter) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if (mHighlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else {
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0, CENTER_RADIUS
+ mCenterPaint.getStrokeWidth(), mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(CENTER_X * 2, CENTER_Y * 2);
}
private static final int CENTER_X = 100;
private static final int CENTER_Y = 100;
private static final int CENTER_RADIUS = 32;
private int floatToByte(float x) {
int n = java.lang.Math.round(x);
return n;
}
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
5. private int pinToByte(int n) {
if (n < 0) {
n = 0;
} else if (n > 255) {
n = 255;
}
return n;
}
private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
private int interpColor(int colors[], float unit) {
if (unit <= 0)
return colors[0];
if (unit >= 1)
return colors[colors.length - 1];
float p = unit * (colors.length - 1);
int i = (int) p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
private int rotateColor(int color, float rad) {
float deg = rad * 180 / 3.1415927f;
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
ColorMatrix cm = new ColorMatrix();
ColorMatrix tmp = new ColorMatrix();
cm.setRGB2YUV();
tmp.setRotate(0, deg);
cm.postConcat(tmp);
tmp.setYUV2RGB();
cm.postConcat(tmp);
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
6. final float[] a = cm.getArray();
int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b);
int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b);
int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);
return Color.argb(Color.alpha(color), pinToByte(ir), pinToByte(ig),
pinToByte(ib));
}
private static final float PI = 3.1415926f;
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if (inCenter) {
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if (mTrackingCenter) {
if (mHighlightCenter != inCenter) {
mHighlightCenter = inCenter;
invalidate();
}
} else {
float angle = (float) java.lang.Math.atan2(y, x);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle / (2 * PI);
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (mTrackingCenter) {
if (inCenter) {
mListener.colorChanged(mCenterPaint.getColor());
}
mTrackingCenter = false; // so we draw w/o halo
invalidate();
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
8. import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.Paint.Style;
import android.graphics.Path.Direction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
/*
* Sample CustomImageButton
* Programatic draw a own Button, whit different States
* default, focused and pressed
*
* 14.02.2008 by Mauri for anddev.org
*/
public class CustomImageButton extends Activity {
private TextView mDebug;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// prepare the Layout
// two Buttons
// Debug-TextView Below
LinearLayout linLayoutMain = new LinearLayout(this);
linLayoutMain.setOrientation(LinearLayout.VERTICAL);
LinearLayout linLayoutButtons = new LinearLayout(this);
linLayoutButtons.setOrientation(LinearLayout.HORIZONTAL);
// buttons
MyCustomButton btn1 = new MyCustomButton(this, "btn1");
MyCustomButton btn2 = new MyCustomButton(this, "btn2");
// a TextView for debugging output
mDebug = new TextView(this);
// add button to the layout
linLayoutButtons.addView(btn1,
new LinearLayout.LayoutParams(100, 100));
linLayoutButtons.addView(btn2,
new LinearLayout.LayoutParams(100, 100));
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
9. // add buttons layout and Text view to the Main Layout
linLayoutMain.addView(linLayoutButtons,
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
linLayoutMain.addView(mDebug,
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
setContentView(linLayoutMain);
}
// Custom Button Class must extends Button,
// because drawableStateChanged() is needed
public class MyCustomButton extends Button {
static final int StateDefault = 0;
static final int StateFocused = 1;
static final int StatePressed = 2;
private int mState = StateDefault;
private Bitmap mBitmapDefault;
private Bitmap mBitmapFocused;
private Bitmap mBitmapPressed;
private String mCaption;
public MyCustomButton(Context context, String caption) {
super(context);
mCaption = caption;
setClickable(true);
// black Background on the View
setBackgroundColor(0xff000000);
// create for each State a Bitmap
// white Image
mBitmapDefault = Bitmap.createBitmap(100, 100, Config.RGB_565);
// Blue Image
mBitmapFocused = Bitmap.createBitmap(100, 100, Config.RGB_565);
// Green Image
mBitmapPressed = Bitmap.createBitmap(100, 100, Config.RGB_565);
// create the Canvas
Canvas canvas = new Canvas();
// define on witch Bitmap should the Canvas draw
// default Bitmap
canvas.setBitmap(mBitmapDefault);
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
10. // create the Drawing Tool (Brush)
Paint paint = new Paint();
paint.setAntiAlias(true); // for a nicer paint
// draw a rectangle with rounded edges
// white Line
paint.setColor(0xffffffff);
// 3px line width
paint.setStrokeWidth(3);
// just the line, not filled
paint.setStyle(Style.STROKE);
// create the Path
Path path = new Path();
// rectangle with 10 px Radius
path.addRoundRect(new RectF(10, 10, 90, 90),
10, 10, Direction.CCW);
// draw path on Canvas with the defined "brush"
canvas.drawPath(path, paint);
// prepare the "brush" for the Text
Paint paintText = new Paint();
paintText.setAntiAlias(true);
paintText.setTextSize(20);
paintText.setColor(0xffffffff); // white
// draw Text
canvas.drawText(caption, 30, 55, paintText);
// do some more drawing stuff here...
// for the Pressed Image
canvas.setBitmap(mBitmapPressed);
// Greed Color
paint.setColor(0xff00ff00);
paintText.setColor(0xff00ff00); // white Line
canvas.drawPath(path, paint);
canvas.drawText(caption, 30, 55, paintText);
// do some more drawing stuff here...
// for the Pressed Image
canvas.setBitmap(mBitmapFocused);
// Blue Color
paint.setColor(0xff0000ff);
paintText.setColor(0xff0000ff); // white Line
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
11. canvas.drawPath(path, paint);
canvas.drawText(caption, 30, 55, paintText);
// do some more drawing stuff here...
// define OnClickListener for the Button
setOnClickListener(onClickListener);
}
@Override
protected void onDraw(Canvas canvas) {
switch (mState) {
case StateDefault:
canvas.drawBitmap(mBitmapDefault, 0, 0, null);
mDebug.append(mCaption + ":defaultn");
break;
case StateFocused:
canvas.drawBitmap(mBitmapFocused, 0, 0, null);
mDebug.append(mCaption + ":focusedn");
break;
case StatePressed:
canvas.drawBitmap(mBitmapPressed, 0, 0, null);
mDebug.append(mCaption + ":pressedn");
break;
}
}
@Override
protected void drawableStateChanged() {
if (isPressed()) {
mState = StatePressed;
} else if (hasFocus()) {
mState = StateFocused;
} else {
mState = StateDefault;
}
// force the redraw of the Image
// onDraw will be called!
invalidate();
}
private OnClickListener onClickListener =
new OnClickListener() {
public void onClick(View arg0) {
mDebug.append(mCaption + ":clickn");
}
};
}
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
12. }
DialogBox
Dialog.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class DialogBox extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** We need to set up a click listener on the alert button */
Button alert = (Button) findViewById(R.id.showalert);
alert.setOnClickListener(this);
/** We need to set up a click listener on the yesno button */
Button yesno = (Button) findViewById(R.id.showyesorno);
yesno.setOnClickListener(this);
/** We need to set up a click listener on the selectlist button */
Button selectlist = (Button) findViewById(R.id.list);
selectlist.setOnClickListener(this);
/** We need to set up a click listener on the selectlistwithcheckbox button */
Button selectlistwithcheckbox = (Button) findViewById(R.id. listwithcheck);
selectlistwithcheckbox.setOnClickListener(this);
}
public void onClick(View view) {
/** check whether the alert button has been clicked */
if (view == findViewById(R.id.showalert)) {
// Create the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set the message to display
alertbox.setMessage("This is an alert box.");
// Add a neutral button to the alert box and assign a click listener
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
13. alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
// Click listener on the neutral button of alert box
public void onClick(DialogInterface arg0, int arg1) {
// The neutral button was clicked
Toast.makeText(getApplicationContext(), "'OK' button clicked",
Toast.LENGTH_LONG).show();
}
});
// show the alert box
alertbox.show();
}
/** check whether the yesno button has been clicked */
if (view == findViewById(R.id.showyesorno)) {
// Create the dialog box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set the message to display
alertbox.setMessage("This is a dialog box with two buttons");
// Set a positive/yes button and create a listener
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'Yes' button clicked",
Toast.LENGTH_SHORT).show();
}
});
// Set a negative/no button and create a listener
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked",
Toast.LENGTH_SHORT).show();
}
});
// display box
alertbox.show();
}
/** check whether the selectlist button has been clicked */
if (view == findViewById(R.id.list)) {
//List items
final CharSequence[] items = {"Milk", "Butter", "Cheese"};
//Prepare the list dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Set its title
builder.setTitle("Pick an item");
//Set the list items and assign with the click listener
builder.setItems(items, new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
14. // Toast.makeText(getApplicationContext(), items[item],
Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface arg0, int item) {
Toast.makeText(getApplicationContext(), items[item],
Toast.LENGTH_SHORT).show();
}
});
// Set a negative/no button and create a listener
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked",
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
//display dialog box
alert.show();
}
/** check whether the selectlistwithcheckbox button has been clicked */
if (view == findViewById(R.id.listwithcheck)) {
//List items
final CharSequence[] items = {"Milk", "Butter", "Cheese"};
//Prepare the list dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Set its title
builder.setTitle("Pick an item");
//Set the list items along with checkbox and assign with the click listener
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item],
Toast.LENGTH_SHORT).show();
//If the Cheese item is chosen close the dialog box
if(items[item]=="Cheese")
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
//display dialog box
alert.show();
}
}
}
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi