Customized Progress Bar

Web Hosting

Actually, I'm just refer this site from this link.

Interface: Custom Progress Bar

Customization interface: Progress Bar
Today we will customize element Spinning Wheel. This article will be covered three ways to change the element.


Practice
For one of the methods of customization require resources. Create an xml file for the color. These resources will set the gradient for our spinning wheel.

Source code (colors.xml)
<resources>
    <color name="color_preloader_start">#000000</color>
    <color name="color_preloader_center">#000000</color>
    <color name="color_preloader_end">#ff56a9c7</color>
</resources>
  • First way. Using Shape
Create forms for the rotation is limited only by your imagination. This article will be examined only two forms: oval and ring.

1. Oval
Customization interface: Progress Bar

Source code (loader_0_1.xml)
<rotatexmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360" >

    <shape android:shape="oval" >
        <gradient
           android:centerColor="@color/color_preloader_center"
            android:centerY="0.50"
            android:endColor="@color/color_preloader_end"
           android:startColor="@color/color_preloader_start"
            android:type="sweep" />
    </shape>

</rotate>

rotate allows our form to rotate from 0 to 360 degrees with a pivot point at the center of the figure. Our figure is filled sweep gradient. The gradient is given by three colors and starts in the center of the figure is painted over.

2. Ring
Customization interface: Progress Bar

Source code (loader_0.xml)
<rotatexmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false" >

        <gradient
           android:centerColor="@color/color_preloader_center"
            android:centerY="0.50"
            android:endColor="@color/color_preloader_end"
           android:startColor="@color/color_preloader_start"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

For the ring you must set the following parameters:
android:innerRadiusRatio – inner radius of the ring
android:thicknessRatio – thickness of the ring
android:useLevel="false" – Indicates whether the drawable's level affects the way the gradient is drawn.
  • Second way: Rotating an image
This method uses a pre-built image to rotate.

Customization interface: Progress Bar
Example images (download):

Source code (loader_1.xml)
<animated-rotatexmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/preloader"
    android:pivotX="50%"
    android:pivotY="50%" />

  • Third way: frame animation

Customization interface: Progress Bar

Example images (download):

In that case, when our spinning wheel can not be animated by a rotation, you can use frame animation.
Note: The size of the element must be equal to or greater than used images.

Source code (loader_2.xml)
<animation-listxmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:drawable="@drawable/progress_1"
        android:duration="200"/>
    <item
        android:drawable="@drawable/progress_2"
        android:duration="200"/>
    <item
        android:drawable="@drawable/progress_3"
        android:duration="200"/>
    <item
        android:drawable="@drawable/progress_4"
        android:duration="200"/>
    <item
        android:drawable="@drawable/progress_5"
        android:duration="200"/>
</animation-list>
android:duration – time display the current frame.

Now we will place all our items on the screen. To customize the ProgressBar, you must use the attribute android:indeterminateDrawable.

Source code (main.xml)
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ProgressBar
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:indeterminateDrawable="@drawable/loader_0" />

    <ProgressBar
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:indeterminateDrawable="@drawable/loader_0_1" />

    <ProgressBar
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:indeterminateDrawable="@drawable/loader_1" />

    <ProgressBar
        android:layout_width="119dp"
        android:layout_height="119dp"
        android:indeterminateDrawable="@drawable/loader_2" />

</LinearLayout>

That's it. Enjoy and happy coding...
Web Hosting

Custom Dialog

Web Hosting
Actually, I refer this tutorial from Custom Dialog. See code below.


How to create iPhone like Custom Dialog / Alert View or Box in Android

Hi,


Its very interesting to create iPhone Like AlertView (Dialog Box) in Android.



Follow the steps to create iPhone Like AlertView (Dialog Box) in Android

Step 1 : Create android Project in Eclipse as shown below






Step 2 : Create New Class for Custom Dialog as given below



After creating CustomizeDialog.java write following code into it.

 package com.sks.dialog.custom;  
 import android.app.Dialog;  
 import android.content.Context;  
 import android.text.method.ScrollingMovementMethod;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.view.Window;  
 import android.widget.Button;  
 import android.widget.TextView;  
 /** Class Must extends with Dialog */  
 /** Implement onClickListener to dismiss dialog when OK Button is pressed */  
 public class CustomizeDialog extends Dialog implements OnClickListener {  
     Button okButton;  
     Context mContext;  
     TextView mTitle = null;  
     TextView mMessage = null;  
     View v = null;  
     public CustomizeDialog(Context context) {  
         super(context);  
         mContext = context;  
         /** 'Window.FEATURE_NO_TITLE' - Used to hide the mTitle */  
         requestWindowFeature(Window.FEATURE_NO_TITLE);  
         /** Design the dialog in main.xml file */  
         setContentView(R.layout.main);  
         v = getWindow().getDecorView();  
         v.setBackgroundResource(android.R.color.transparent);  
         mTitle = (TextView) findViewById(R.id.dialogTitle);  
         mMessage = (TextView) findViewById(R.id.dialogMessage);  
         okButton = (Button) findViewById(R.id.OkButton);  
         okButton.setOnClickListener(this);  
     }  
     @Override  
     public void onClick(View v) {  
         /** When OK Button is clicked, dismiss the dialog */  
         if (v == okButton)  
             dismiss();  
     }  
     @Override  
     public void setTitle(CharSequence title) {  
         super.setTitle(title);  
         mTitle.setText(title);  
     }  
     @Override  
     public void setTitle(int titleId) {  
         super.setTitle(titleId);  
         mTitle.setText(mContext.getResources().getString(titleId));  
     }  
     /**  
      * Set the message text for this dialog's window.  
      *   
      * @param message  
      *      - The new message to display in the title.  
      */  
     public void setMessage(CharSequence message) {  
         mMessage.setText(message);  
         mMessage.setMovementMethod(ScrollingMovementMethod.getInstance());  
     }  
     /**  
      * Set the message text for this dialog's window. The text is retrieved from the resources with the supplied  
      * identifier.  
      *   
      * @param messageId  
      *      - the message's text resource identifier <br>  
      * @see <b>Note : if resourceID wrong application may get crash.</b><br>  
      *   Exception has not handle.  
      */  
     public void setMessage(int messageId) {  
         mMessage.setText(mContext.getResources().getString(messageId));  
         mMessage.setMovementMethod(ScrollingMovementMethod.getInstance());  
     }  
 }  


Very Important part to hide dialog default background.
below code is used to set transparant background of dialog.


v = getWindow().getDecorView();  
v.setBackgroundResource(android.R.color.transparent);



Step 3 : Now We have to create custom Layout for Dialog. 
edit main.xml (you can select layout file name as per your specifications)


 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:id="@+id/LinearLayout"  
   android:layout_width="fill_parent"  
   android:layout_height="wrap_content"  
   android:layout_gravity="center"  
   android:layout_margin="0dip"  
   android:background="@drawable/alert_bg"  
   android:orientation="vertical"  
   android:paddingBottom="15dip"  
   android:paddingLeft="0dip"  
   android:paddingRight="0dip"  
   android:paddingTop="0dip" >  
   <TextView  
     android:id="@+id/dialogTitle"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_marginTop="20dip"  
     android:background="#00000000"  
     android:gravity="center"  
     android:text=""  
     android:textColor="#fff"  
     android:textSize="22sp"  
     android:textStyle="bold" >  
   </TextView>  
   <TextView  
     android:id="@+id/dialogMessage"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_below="@+id/dialogTitle"  
     android:focusable="true"  
     android:focusableInTouchMode="true"  
     android:gravity="center"  
     android:maxLines="10"  
     android:padding="10dip"  
     android:scrollbars="vertical"  
     android:text=""  
     android:textColor="#fff"  
     android:textSize="18sp" >  
   </TextView>  
   <Button  
     android:id="@+id/OkButton"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_below="@+id/dialogMessage"  
     android:layout_centerHorizontal="true"  
     android:layout_marginLeft="10dip"  
     android:layout_marginRight="10dip"  
     android:background="@drawable/button"  
     android:text="OK"  
     android:textColor="#FFFFFF" >  
   </Button>  
 </RelativeLayout>  


Step 4 : Add 9 patch image in res->drawable folder given below. You can modify image.
alert_bg.9.png
  
button_bg_normal.9.png

button_bg_pressed.9


titlebg.png
Note : this image transparency is 90% that's why invisible
Step 5 : For adding Focus Effect on Dialog Button create button.xml in drawable folder as given below
 <?xml version="1.0" encoding="utf-8"?>  
 <selector xmlns:android="http://schemas.android.com/apk/res/android">  
     <item android:state_pressed="true" android:drawable="@drawable/button_bg_pressed" /> <!-- pressed -->  
     <item android:state_focused="true" android:drawable="@drawable/button_bg_pressed" /> <!-- focused -->  
     <item android:drawable="@drawable/button_bg_normal" /> <!-- default -->  
 </selector>  


Step 6 : Now Come to our First Activity i.e. CustomDialogExample.java and Modify file as given Below
 package com.sks.dialog.custom;  
 import android.app.Activity;  
 import android.content.Context;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 public class CustomDialogExample extends Activity {  
     Context context;  
     CustomizeDialog customizeDialog = null;  
     /** Called when the activity is first created. */  
     @Override  
     public void onCreate(Bundle savedInstanceState) {  
         super.onCreate(savedInstanceState);  
         /** Display Custom Dialog */  
         context = this;  
         setContentView(R.layout.home);  
         Button btn1 = (Button) findViewById(R.id.btnDialog1);  
         btn1.setOnClickListener(new OnClickListener() {  
             @Override  
             public void onClick(View v) {  
                 customizeDialog = new CustomizeDialog(context);  
                 customizeDialog.setTitle("My Title");  
                 customizeDialog.setMessage("My Custom Dialog Message from \nSmartPhoneBySachin.Blogspot.com ");  
                 customizeDialog.show();  
             }  
         });  
     }  
 }  
Now you are ready to Run Project and you will get result as image below



Web Hosting
That's it, hope this simple tutorial may help you. Happy Coding!

AsyncTask

Web Hosting
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as ExecutorThreadPoolExecutor and FutureTask.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

Example:
Here is an example of subclassing:
 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
 
Once created, a task is executed very simply:
 new DownloadFilesTask().execute(url1, url2, url3);
 

AsyncTask's generic types


The three types used by an asynchronous task are the following:
  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
 private class MyTask extends AsyncTask<Void, Void, Void> { ... }
 

The 4 steps


When an asynchronous task is executed, the task goes through 4 steps:
  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately afteronPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call topublishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Cancelling a task


A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method,onCancelled(Object), instead of onPostExecute(Object) will be invoked afterdoInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically fromdoInBackground(Object[]), if possible (inside a loop for instance.)

Threading rules


There are a few threading rules that must be followed for this class to work properly:

Memory observability


AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.

Order of execution


When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invokeexecuteOnExecutor(java.util.concurrent.Executor, Object[]) withTHREAD_POOL_EXECUTOR.

Web Hosting
That's it. Hope this simple tutorial may help you. Happy Coding!