SlideShare a Scribd company logo
1 of 20
Android Application Development Training Tutorial




                      For more info visit

                   http://www.zybotech.in




        A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
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
}

}




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
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
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
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
}
              break;
            }
            return true;
        }
    }

    public ColorPickerDialog(Context context, OnColorChangedListener listener,
         int initialColor) {
      super(context);

        mListener = listener;
        mInitialColor = initialColor;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      OnColorChangedListener l = new OnColorChangedListener() {
         public void colorChanged(int color) {
           mListener.colorChanged(color);
           dismiss();
         }
      };

        LinearLayout layout = new LinearLayout(getContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setGravity(Gravity.CENTER);
        layout.setPadding(10, 10, 10, 10);
        layout.addView(new ColorPickerView(getContext(), l, mInitialColor),
             new LinearLayout.LayoutParams(
                  LinearLayout.LayoutParams.WRAP_CONTENT,
                  LinearLayout.LayoutParams.WRAP_CONTENT));

        setContentView(layout);
        setTitle("Pick a Color");
    }
}


CustomImageButton
Costumimagebutton.java

import android.app.Activity;
      import android.content.Context;
      import android.graphics.Bitmap;
      import android.graphics.Canvas;
      import android.graphics.Paint;

                             A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
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
// 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
// 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
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
}




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
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
// 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
Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Dialogs"
   />
   <Button
       android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Show Alert"
   android:id="@+id/showalert"
   />
    <Button
       android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Show Yes/No"
   android:id="@+id/showyesorno"
   />
    <Button
       android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Show List"
   android:id="@+id/list"
   />
    <Button
       android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Show List with CheckBoxes"
   android:id="@+id/listwithcheck"
   />
</LinearLayout>




DynamicListView
DynamicListView.java

import java.util.ArrayList;


                         A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
import   android.app.Activity;
import   android.app.ListActivity;
import   android.content.Context;
import   android.graphics.Bitmap;
import   android.graphics.BitmapFactory;
import   android.os.Bundle;
import   android.view.LayoutInflater;
import   android.view.View;
import   android.view.ViewGroup;
import   android.view.View.OnClickListener;
import   android.widget.BaseAdapter;
import   android.widget.Button;
import   android.widget.EditText;
import   android.widget.ImageView;
import   android.widget.ListView;
import   android.widget.TextView;

public class dynamicListView extends ListActivity implements OnClickListener {

  EditText textContent;
  Button submit;
  ListView mainListview;

  private static class ListViewAdapter extends BaseAdapter {
     private LayoutInflater mInflater;



  public ListViewAdapter(Context context) {

    mInflater = LayoutInflater.from(context);




  }
  public int getCount() {
    return ListviewContent.size();
  }
  public Object getItem(int position) {
    return position;
  }
  public long getItemId(int position) {
    return position;
  }
  public View getView(int position, View convertView, ViewGroup parent) {

    ListContent holder;




                          A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
if (convertView == null) {
            convertView = mInflater.inflate(R.layout.listviewinflate, null);

                holder = new ListContent();
                holder.text = (TextView) convertView.findViewById(R.id.TextView01);

holder.text.setCompoundDrawables(convertView.getResources().getDrawable(R.drawable. icon),
null, null, null);

           convertView.setTag(holder);
        } else {

                holder = (ListContent) convertView.getTag();
        }



        holder.text.setText(ListviewContent.get(position));
            return convertView;
    }

    static class ListContent {
      TextView text;

    }
}

        @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      ListviewContent.add("Androidpeople.com");ListviewContent.add("Android FROYO");

        textContent=(EditText)findViewById(R.id.EditText01);
        submit=(Button)findViewById(R.id.Button01);
        submit.setOnClickListener(this);
        setListAdapter(new ListViewAdapter(this));
    }
            private static final ArrayList<String> ListviewContent = new ArrayList<String>();
            @Override
            public void onClick(View v) {
                   if(v==submit)
                   {
                          ListviewContent.add(textContent.getText().toString());
                          setListAdapter(new ListViewAdapter(this));
                   }



            }
}


                                A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:id="@+id/LinearLayout01"
       android:layout_width="fill_parent" android:layout_height="fill_parent"
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical">
       <LinearLayout android:id="@+id/LinearLayout02"
              android:layout_height="wrap_content" android:layout_width="fill_parent">
              <EditText android:id="@+id/EditText01" android:layout_width="wrap_content"
                    android:layout_height="wrap_content" android:layout_weight="1"></EditText>
              <Button android:id="@+id/Button01" android:layout_width="wrap_content"
                    android:layout_height="wrap_content" android:text="Add to
Listview"></Button>
       </LinearLayout>

       <ListView android:layout_height="wrap_content" android:id="@android:id/list"
             android:layout_width="fill_parent"></ListView>
</LinearLayout>


Listviewinflate.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:paddingLeft="5px">
<LinearLayout
android:id="@+id/LinearLayout02"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:text="@+id/TextView01"
android:id="@+id/TextView01"
android:layout_height="wrap_content"
android:textColor="#000"
android:layout_width="fill_parent"
android:layout_weight="1">
</TextView>
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

                        A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
android:background="@drawable/arrow">
</TextView>
</LinearLayout>
</LinearLayout>


AlertDialog with RadioButton
import   android.app.Activity;
import   android.app.AlertDialog;
import   android.content.DialogInterface;
import   android.os.Bundle;
import   android.widget.Toast;

public class Example1 extends Activity {
  /** Called when the activity is first created. */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     final CharSequence[] PhoneModels = {"iPhone", "Nokia", "Android"};
     AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
     alt_bld.setIcon(R.drawable.icon);
     alt_bld.setTitle("Select a Phone Model");
     alt_bld.setSingleChoiceItems(PhoneModels, -1, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int item) {
           Toast.makeText(getApplicationContext(), "Phone Model = "+PhoneModels[item],
Toast.LENGTH_SHORT).show();
         }
     });
     AlertDialog alert = alt_bld.create();
     alert.show();

    }
}


Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />


                         A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
<Gallery
    android:id="@+id/gallery1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
  <ImageView
    android:id="@+id/image1"
    android:layout_width="320px"
    android:layout_height="250px"
    android:scaleType="fitXY" />

</LinearLayout>




With Ok and Cancel Button

import   android.app.Activity;
import   android.app.AlertDialog;
import   android.content.DialogInterface;
import   android.os.Bundle;

public class ExampleApp extends Activity {
  /** Called when the activity is first created. */
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

                 final String items[] = {"item1","item2","item3"};

                 AlertDialog.Builder ab=new AlertDialog.Builder(ExampleApp.this);
                            ab.setTitle("Title");
                            ab.setSingleChoiceItems(items, 0,new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int whichButton) {
                        // onClick Action
                     }
                 })
                 .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int whichButton) {
                          // on Ok button action
                                    }
                 })
                 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int whichButton) {
                            // on cancel button action
                     }
                 });
                 ab.show();
             }
         }

                              A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

More Related Content

What's hot

Java applet handouts
Java applet handoutsJava applet handouts
Java applet handouts
iamkim
 

What's hot (20)

Introduction to graphics programming in c
Introduction to graphics programming in cIntroduction to graphics programming in c
Introduction to graphics programming in c
 
Circles graphic
Circles graphicCircles graphic
Circles graphic
 
Lecture on graphics
Lecture on graphicsLecture on graphics
Lecture on graphics
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
 
Cgm Lab Manual
Cgm Lab ManualCgm Lab Manual
Cgm Lab Manual
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
 
Nonlinear analysis of frame with hinge by hinge method in c programming
Nonlinear analysis of frame with hinge by hinge method in c programmingNonlinear analysis of frame with hinge by hinge method in c programming
Nonlinear analysis of frame with hinge by hinge method in c programming
 
Computer graphics lab assignment
Computer graphics lab assignmentComputer graphics lab assignment
Computer graphics lab assignment
 
Advance java
Advance javaAdvance java
Advance java
 
Property Based Testing
Property Based TestingProperty Based Testing
Property Based Testing
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manual
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Java applet handouts
Java applet handoutsJava applet handouts
Java applet handouts
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad Transformers
 
Computer Graphics Lab
Computer Graphics LabComputer Graphics Lab
Computer Graphics Lab
 
Applets
AppletsApplets
Applets
 
C graphics programs file
C graphics programs fileC graphics programs file
C graphics programs file
 
SE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneSE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of Pune
 

Viewers also liked

Viewers also liked (16)

Sd1 uva (1)
Sd1 uva (1)Sd1 uva (1)
Sd1 uva (1)
 
Pinschersandschnauzersetcslideshow
PinschersandschnauzersetcslideshowPinschersandschnauzersetcslideshow
Pinschersandschnauzersetcslideshow
 
Ela's 18th birthday
Ela's 18th birthdayEla's 18th birthday
Ela's 18th birthday
 
Basic dos commands
Basic dos commandsBasic dos commands
Basic dos commands
 
How to make land use inventories meaningful
How to make land use inventories meaningfulHow to make land use inventories meaningful
How to make land use inventories meaningful
 
Павел Богданов
Павел БогдановПавел Богданов
Павел Богданов
 
Hudilaisenesitys
HudilaisenesitysHudilaisenesitys
Hudilaisenesitys
 
La història de la informàtica
La història de la informàticaLa història de la informàtica
La història de la informàtica
 
Mitotic Phases
Mitotic PhasesMitotic Phases
Mitotic Phases
 
Meredith Hill | Sample Work
Meredith Hill | Sample WorkMeredith Hill | Sample Work
Meredith Hill | Sample Work
 
Narrative Essay Intro
Narrative Essay IntroNarrative Essay Intro
Narrative Essay Intro
 
Tendencias
TendenciasTendencias
Tendencias
 
Presentació grup 4
Presentació grup 4Presentació grup 4
Presentació grup 4
 
Foods that Provides You Sustainable Energy
Foods that Provides You Sustainable EnergyFoods that Provides You Sustainable Energy
Foods that Provides You Sustainable Energy
 
Publication plan
Publication planPublication plan
Publication plan
 
Carlos Erasto Romero Martinez
Carlos Erasto Romero MartinezCarlos Erasto Romero Martinez
Carlos Erasto Romero Martinez
 

Similar to Applications

I wanna add the shape creator like rectangular , square , circle etc.pdf
I wanna add the shape creator like rectangular , square , circle etc.pdfI wanna add the shape creator like rectangular , square , circle etc.pdf
I wanna add the shape creator like rectangular , square , circle etc.pdf
herminaherman
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
package chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdfpackage chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdf
KARTIKINDIA
 
Mashup caravan android-talks
Mashup caravan android-talksMashup caravan android-talks
Mashup caravan android-talks
honjo2
 
Create a java project that - Draw a circle with three random init.pdf
Create a java project that - Draw a circle with three random init.pdfCreate a java project that - Draw a circle with three random init.pdf
Create a java project that - Draw a circle with three random init.pdf
arihantmobileselepun
 
Please help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdfPlease help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdf
JUSTSTYLISH3B2MOHALI
 
Android Studio (Java)The SimplePaint app (full code given below).docx
Android Studio (Java)The SimplePaint app (full code given below).docxAndroid Studio (Java)The SimplePaint app (full code given below).docx
Android Studio (Java)The SimplePaint app (full code given below).docx
amrit47
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
Kris Kowal
 

Similar to Applications (20)

I wanna add the shape creator like rectangular , square , circle etc.pdf
I wanna add the shape creator like rectangular , square , circle etc.pdfI wanna add the shape creator like rectangular , square , circle etc.pdf
I wanna add the shape creator like rectangular , square , circle etc.pdf
 
662305 11
662305 11662305 11
662305 11
 
The Noland national flag is a square showing the following pattern. .docx
 The Noland national flag is a square showing the following pattern.  .docx The Noland national flag is a square showing the following pattern.  .docx
The Noland national flag is a square showing the following pattern. .docx
 
662305 10
662305 10662305 10
662305 10
 
662305 LAB13
662305 LAB13662305 LAB13
662305 LAB13
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
package chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdfpackage chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdf
 
Creating an Uber Clone - Part IX.pdf
Creating an Uber Clone - Part IX.pdfCreating an Uber Clone - Part IX.pdf
Creating an Uber Clone - Part IX.pdf
 
Mashup caravan android-talks
Mashup caravan android-talksMashup caravan android-talks
Mashup caravan android-talks
 
662305 LAB12
662305 LAB12662305 LAB12
662305 LAB12
 
J slider
J sliderJ slider
J slider
 
Creating an Uber Clone - Part XIX - Transcript.pdf
Creating an Uber Clone - Part XIX - Transcript.pdfCreating an Uber Clone - Part XIX - Transcript.pdf
Creating an Uber Clone - Part XIX - Transcript.pdf
 
Create a java project that - Draw a circle with three random init.pdf
Create a java project that - Draw a circle with three random init.pdfCreate a java project that - Draw a circle with three random init.pdf
Create a java project that - Draw a circle with three random init.pdf
 
Java awt
Java awtJava awt
Java awt
 
Please help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdfPlease help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdf
 
Android Studio (Java)The SimplePaint app (full code given below).docx
Android Studio (Java)The SimplePaint app (full code given below).docxAndroid Studio (Java)The SimplePaint app (full code given below).docx
Android Studio (Java)The SimplePaint app (full code given below).docx
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
 
React native tour
React native tourReact native tour
React native tour
 
Model View Intent on Android
Model View Intent on AndroidModel View Intent on Android
Model View Intent on Android
 

More from info_zybotech (8)

Android basics – dialogs and floating activities
Android basics – dialogs and floating activitiesAndroid basics – dialogs and floating activities
Android basics – dialogs and floating activities
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Notepad tutorial
Notepad tutorialNotepad tutorial
Notepad tutorial
 
Java and xml
Java and xmlJava and xml
Java and xml
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid draw
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Android accelerometer sensor tutorial
Android accelerometer sensor tutorialAndroid accelerometer sensor tutorial
Android accelerometer sensor tutorial
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Applications

  • 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
  • 7. } break; } return true; } } public ColorPickerDialog(Context context, OnColorChangedListener listener, int initialColor) { super(context); mListener = listener; mInitialColor = initialColor; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OnColorChangedListener l = new OnColorChangedListener() { public void colorChanged(int color) { mListener.colorChanged(color); dismiss(); } }; LinearLayout layout = new LinearLayout(getContext()); layout.setOrientation(LinearLayout.VERTICAL); layout.setGravity(Gravity.CENTER); layout.setPadding(10, 10, 10, 10); layout.addView(new ColorPickerView(getContext(), l, mInitialColor), new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); setContentView(layout); setTitle("Pick a Color"); } } CustomImageButton Costumimagebutton.java import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; 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
  • 15. Main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Dialogs" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Show Alert" android:id="@+id/showalert" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Show Yes/No" android:id="@+id/showyesorno" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Show List" android:id="@+id/list" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Show List with CheckBoxes" android:id="@+id/listwithcheck" /> </LinearLayout> DynamicListView DynamicListView.java import java.util.ArrayList; A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 16. import android.app.Activity; import android.app.ListActivity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class dynamicListView extends ListActivity implements OnClickListener { EditText textContent; Button submit; ListView mainListview; private static class ListViewAdapter extends BaseAdapter { private LayoutInflater mInflater; public ListViewAdapter(Context context) { mInflater = LayoutInflater.from(context); } public int getCount() { return ListviewContent.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ListContent holder; A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 17. if (convertView == null) { convertView = mInflater.inflate(R.layout.listviewinflate, null); holder = new ListContent(); holder.text = (TextView) convertView.findViewById(R.id.TextView01); holder.text.setCompoundDrawables(convertView.getResources().getDrawable(R.drawable. icon), null, null, null); convertView.setTag(holder); } else { holder = (ListContent) convertView.getTag(); } holder.text.setText(ListviewContent.get(position)); return convertView; } static class ListContent { TextView text; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListviewContent.add("Androidpeople.com");ListviewContent.add("Android FROYO"); textContent=(EditText)findViewById(R.id.EditText01); submit=(Button)findViewById(R.id.Button01); submit.setOnClickListener(this); setListAdapter(new ListViewAdapter(this)); } private static final ArrayList<String> ListviewContent = new ArrayList<String>(); @Override public void onClick(View v) { if(v==submit) { ListviewContent.add(textContent.getText().toString()); setListAdapter(new ListViewAdapter(this)); } } } A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 18. Main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"> <LinearLayout android:id="@+id/LinearLayout02" android:layout_height="wrap_content" android:layout_width="fill_parent"> <EditText android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1"></EditText> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add to Listview"></Button> </LinearLayout> <ListView android:layout_height="wrap_content" android:id="@android:id/list" android:layout_width="fill_parent"></ListView> </LinearLayout> Listviewinflate.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_height="wrap_content" android:background="#FFFFFF" android:paddingLeft="5px"> <LinearLayout android:id="@+id/LinearLayout02" android:layout_height="wrap_content" android:layout_width="fill_parent"> <TextView android:text="@+id/TextView01" android:id="@+id/TextView01" android:layout_height="wrap_content" android:textColor="#000" android:layout_width="fill_parent" android:layout_weight="1"> </TextView> <TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 19. android:background="@drawable/arrow"> </TextView> </LinearLayout> </LinearLayout> AlertDialog with RadioButton import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.widget.Toast; public class Example1 extends Activity { /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final CharSequence[] PhoneModels = {"iPhone", "Nokia", "Android"}; AlertDialog.Builder alt_bld = new AlertDialog.Builder(this); alt_bld.setIcon(R.drawable.icon); alt_bld.setTitle("Select a Phone Model"); alt_bld.setSingleChoiceItems(PhoneModels, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), "Phone Model = "+PhoneModels[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = alt_bld.create(); alert.show(); } } Main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 20. <Gallery android:id="@+id/gallery1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/image1" android:layout_width="320px" android:layout_height="250px" android:scaleType="fitXY" /> </LinearLayout> With Ok and Cancel Button import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; public class ExampleApp extends Activity { /** Called when the activity is first created. */ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final String items[] = {"item1","item2","item3"}; AlertDialog.Builder ab=new AlertDialog.Builder(ExampleApp.this); ab.setTitle("Title"); ab.setSingleChoiceItems(items, 0,new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // onClick Action } }) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // on Ok button action } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // on cancel button action } }); ab.show(); } } A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi