Friday, August 17, 2012

Android ViewFlipper

Android ViewFlipper

-->
Simple ViewAnimator that will animate between two or more views that have been added to it. Only one child is shown at a time. If requested, can automatically flip between each child at a regular interval.

Below i wrote the code for through flipping you can see the next ITEM or Previous Item with Animation.
Activity Code :
-->
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;
/**
*
* @author vijayakumar
*
*/
public class AndroidMADQAActivity extends Activity {
ViewFlipper flipper;
Button btn1_next ,btn_prev ,btn_playwithAnimation;
/**
* This method called when activity started
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Integer[] items = { R.drawable.a, R.drawable.e,R.drawable.d,R.drawable.c};
setContentView(R.layout.main);
btn1_next = (Button)findViewById(R.id.button2);
btn_prev = (Button)findViewById(R.id.button1);
btn_playwithAnimation = (Button)findViewById(R.id.button3);
flipper = (ViewFlipper) findViewById(R.id.viewFlipper1);
flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.left_in));
flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.left_out));
for (Integer item : items) {
TextView textView = new TextView(this);
textView.setTextSize(30);
textView.setBackgroundResource(item);
flipper.addView(textView, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT));
}
btn_playwithAnimation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(flipper.isFlipping()){
flipper.stopFlipping();
}
flipper.setFlipInterval(1000);
flipper.startFlipping();
}
});
btn1_next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(flipper.isFlipping()){
flipper.stopFlipping();
}
flipper.showNext();
}
});;
btn_prev.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(flipper.isFlipping()){
flipper.stopFlipping();
}
flipper.showPrevious();
}
});;
}
}

Screen Shot  
 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"
>

<ViewFlipper
android:id="@+id/viewFlipper1"
android:layout_width="match_parent"
android:layout_height="370dip" >
</ViewFlipper>
<LinearLayout
android:orientation="horizontal"
android:layout_gravity="bottom"
android:padding="4dip"
android:background="#A4C639"
android:gravity="bottom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous" />

<Button
android:id="@+id/button3"
android:layout_marginLeft="30dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Slide Show" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_marginLeft="30dip"
android:layout_height="wrap_content"
android:text=" Next " />
</LinearLayout>
</LinearLayout>

Animation XML

left_out.xml 
-->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="300"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>

left_in.xml
-->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="300"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>

Wednesday, August 15, 2012

Android Adapterview

Android Adapterview
An AdapterView is a view whose children are determined by an Adapter.
See Listview, Gridview, Spinner and Gallery for commonly used subclasses of AdapterView.
Below the example just i create array of values and set that values into ArrayAdapter.
Array of string  values 
Step 1

private static final String[] AndroidVersion = {

"Android2.1", "Android2.2", "Android2.3",

"Android3.0", "Android3.2", "Android4.0",

"Android4.1"

};


Step 2. i created one XML in that having Spinner lauout.
Spinner s = (Spinner) findViewById(R.id.spinner);
Step 3
then i added the array of values to ArrayAdapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,

android.R.layout.simple_spinner_item, AndroidVersion);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Step 4.
Then Set the adapter to spinner 
s.setAdapter(adapter);

*Same like listview and Galleryview and Gridview
Step 5. Output -run the application

FULL SOURCE CODE
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
/**
 *
 * @author vijayakumar
 *
 */
public class AndroidMADQAActivity extends Activity implements AdapterView.OnItemSelectedListener {
    private static final String[] AndroidVersion = {
            "Android2.1", "Android2.2", "Android2.3",
            "Android3.0", "Android3.2", "Android4.0",
            "Android4.1"
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Spinner s = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, AndroidVersion);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(adapter);
        s.setOnItemSelectedListener(this);
    }
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    }
    public void onNothingSelected(AdapterView<?> parent) {
    }
}


Download Source Code 

Android AnalogClock

Android AnalogClock
This widget display an analogic clock with two hands for hours and minutes.  
 a) Anlogclock
Like AnalogClock, but digital. Shows seconds. FIXME: implement separate views for hours/minutes/seconds, so proportional fonts don't shake rendering 
 b) Digitalclock
Analogclock example 
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <AnalogClock android:id="@+id/content"
         android:background="#D0A0A0"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent" />
</RelativeLayout>

Digital clock and AnalogClock
this code analog clokc and digital clock
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <AnalogClock android:id="@+id/analogclk"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentTop="true"
    />
  <DigitalClock android:id="@+id/digitalclk"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@id/analogclk"
    />
</RelativeLayout>
Activity code

/**

*

* @author vijayakumar

*

*/

public class AndroidMADQAActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

Android Action Bar

Android ActionBar 

The action bar is a window feature that identifies the application and user location, and provides user actions and navigation modes. You should use the action bar in most activities that need to prominently present user actions or global navigation, because the action bar offers users a consistent interface across applications and the system gracefully adapts the action bar's appearance for different screen configurations. You can control the behaviors and visibility of the action bar with the ActionBar APIs, which were added in Android 3.0 (API level 11).

i) Using Tabs ActionBar
ii)Demonstrates idiomatic usage of the Action Bar.


i) Using Tabs ActionBar
A tab in the action bar.
Tabs manage the hiding and showing of Fragments.
 ii)Demonstrates idiomatic usage of the Action Bar.
This demonstrates idiomatic usage of the Action Bar. The default Honeycomb theme includes the action bar by default and a menu resource is used to populate the menu data itself. If you'd like to see how these things work under the hood, see ActionBarMechanics.
Android  Quick Action Bar.
Quick Actions are basically actions/functions in a popup bar that are triggered by specific visual elements/buttons/items on the screen. Quick Actions are used to display contextual actions typically used in list views but not limited to it. You can imagine a phone-book or contact list on the phone. Now, there are certain set of actions that will be common to all contacts in the views like; make a call, send message, edit contact or may be even transfer files by  Email, Bluetooth etc. Basically these functions that are common to items in a context can be put in the Quick Action bar. This way the screen is uncluttered and simple and more importantly we needn’t sacrifice on the actions needed.

Create Actionable Items:
The below code snippet is used to create an actionable item i.e. the actions you would want to place in the quick action bar. Creating an actionable item involves specifying the title, setting an icon that represents the item which will help you relate to the action, and finally set a Listener for the action. The term itself is self-explanatory. Yes, it is used to determine the action to be performed when clicked or pressed. As far as the icon /image goes, it can be easily set by referring to it from the resources as is the case with any external resource set in android which you would aware of, I am most certain.

final QuickActionIcons edit = new QuickActionIcons();;
 edit.setTitle("Edit");
 edit.setIcon(getResources().getDrawable(R.drawable.edit));
 edit.setOnClickListener(new OnClickListener()
 {
 public void onClick(View v)
 {
// add u r action
 }

 });]


Create Quick Action Dialog:

This part is even simpler. Like in this example, when an item in the list view is clicked / pressed, a new quick action bar/dialog is created. Then all the actionable items that you have created in the previous step are appended one by one to the quick action bar. After this you simply have to specify the animation style i.e. how do you want the dialog to be displayed on screen.

resultPane.setOnItemClickListener(new OnItemClickListener()
    {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
      QuickActionBar qab = new QuickActionBar(view);

      qab.addItem(edit);
      qab.addItem(call);
      qab.addItem(send_data);
      qab.setAnimationStyle(QuickActionBar.GROW_FROM_LEFT);

      qab.show();
    }
    });
  DOWNLOAD SOURCE CODE

Android AlertDialog

Android AlertDialog
 A subclass of Dialog that can display one, two or three buttons. If you only want to display a String in this dialog box, use the setMessage() method. If you want to display a more complex view, look up the FrameLayout called "custom" and add your view to it:

a) show yes or no alertdialog
b) show firsttime popup alertdialog
c) show message alertdialog
d) show alert alertdialog
c) helper alertdialog
a) show yes or no alertdialog
This alert dialog represents for show yes or no question.
Sampele code

 public  void showYesNoPrompt(Context _context, String title, String message, OnClickListener onYesListener, OnClickListener onNoListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(_context);
        builder.setTitle(title);
        builder.setIcon(android.R.drawable.ic_dialog_info); // lame icon
        builder.setMessage(message);
        builder.setCancelable(false);
        builder.setPositiveButton("Yes", onYesListener);
        builder.setNegativeButton("No", onNoListener);
        builder.show();
      }
 b) show firsttime popup alertdialog
This dialog represents for alert the welcome message
Sample code
public  void openFirstTimePopup(final Context context) {
        final String html = "Thank you!";
        final AlertDialog.Builder builder = new AlertDialog.Builder(context).
        setCancelable(true).
        setTitle("Welcome!").
        setMessage(html).
        setNegativeButton("Close",null);
        final AlertDialog di = builder.create();
        di.show();
      }
 c) show message alertdialog 
This alert dialog represents for show message
Sample Code
  public  void showMessage(Context _context, String title, String message, int icon, DialogInterface.OnClickListener ackHandler) {
        AlertDialog.Builder builder = new AlertDialog.Builder(_context);
        builder.setTitle(title);
        builder.setMessage(Html.fromHtml(message));
        builder.setCancelable(false);
        builder.setPositiveButton("Ok", ackHandler);
        builder.setIcon(icon);
        builder.show();
      }
d) show alert alertdialog 
This dialog represents for show the error message to user.
Sample code
public static void showAlert(Context context, String title, String text,
              boolean showOk) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
            alertBuilder.setTitle(title);
            alertBuilder.setMessage(text);
            if (showOk)
              alertBuilder.setNeutralButton("ok", null);
            alertBuilder.create().show();
          }
c) helper alertdialog
This dialog represents for show the helper message to user.
Sample Code
 public  void helperAlertDialog(final Context ctx, final CharSequence title, final CharSequence message) {
        new AlertDialog.Builder(ctx)
       .setIcon(R.drawable.ic_launcher)
        .setTitle(title)
        .setMessage(message)
        .setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
        })
        .show();
        }

Full Source Code 
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
 *
 * @author vijayakumar
 *
 */
public class AndroidMADQAActivity extends Activity {
    Button btn1,btn2,btn3,btn4,btn5;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      btn1 = (Button)findViewById(R.id.button1);
      btn2 = (Button)findViewById(R.id.button2);
      btn3 = (Button)findViewById(R.id.button3);
      btn4 = (Button)findViewById(R.id.button4);
      btn5 = (Button)findViewById(R.id.button5);
      btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                 showYesNoPrompt(AndroidMADQAActivity.this,"Yes or No AlertDialog","Hello",null,null);
        }
    });
      btn2.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              // TODO Auto-generated method stub
               openFirstTimePopup(AndroidMADQAActivity.this);
          }
      });
      btn3.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
               showMessage(AndroidMADQAActivity.this,"Show Message Alert Dialog","You Have Message",R.drawable.ic_launcher,null);
          }
      });
      btn4.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
               showAlert(AndroidMADQAActivity.this,"show alert dialog","Error",true);
          }
      });
      btn5.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
             helperAlertDialog(AndroidMADQAActivity.this,"Helper Dialog", "Helper dialog");
            
          }
      });
    }
   
    public  void showYesNoPrompt(Context _context, String title, String message, OnClickListener onYesListener, OnClickListener onNoListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(_context);
        builder.setTitle(title);
        builder.setIcon(android.R.drawable.ic_dialog_info); // lame icon
        builder.setMessage(message);
        builder.setCancelable(false);
        builder.setPositiveButton("Yes", onYesListener);
        builder.setNegativeButton("No", onNoListener);
        builder.show();
      }
    public  void openFirstTimePopup(final Context context) {
        final String html = "Thank you!";
        final AlertDialog.Builder builder = new AlertDialog.Builder(context).
        setCancelable(true).
        setTitle("Welcome!").
        setMessage(html).
        setNegativeButton("Close",null);

        final AlertDialog di = builder.create();
       
        di.show();
      }
    public  void showMessage(Context _context, String title, String message, int icon, DialogInterface.OnClickListener ackHandler) {
        AlertDialog.Builder builder = new AlertDialog.Builder(_context);
        builder.setTitle(title);
        builder.setMessage(Html.fromHtml(message));
        builder.setCancelable(false);
        builder.setPositiveButton("Ok", ackHandler);
        builder.setIcon(icon);
        builder.show();
      }

    public static void showAlert(Context context, String title, String text,
              boolean showOk) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
            alertBuilder.setTitle(title);
            alertBuilder.setMessage(text);
            if (showOk)
              alertBuilder.setNeutralButton("ok", null);
            alertBuilder.create().show();
          }
    public  void helperAlertDialog(final Context ctx, final CharSequence title, final CharSequence message) {
        new AlertDialog.Builder(ctx)
       .setIcon(R.drawable.ic_launcher)
        .setTitle(title)
        .setMessage(message)
        .setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
        })
        .show();
        }

}

Android-Activity

Android Activity
An activity having UserInterface its sub class of Activity
An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup). There are two methods almost all subclasses of Activity will implement:
  a) Backup Activity
  b) Notification Activity
  c) setContentView from XML for activity
  d) more than one Activity
  e) find user control by using findbyview
  f) A simple form
  g) Link from with POJO
  h) LifeCycle
   a) Backup Activity
This class  using for take backup your database or your application any other data.
class BackAsyncTask extends AsyncTask<String,Void,Integer> {
    public interface CompletionListener {
        void onBackupComplete();
        void onRestoreComplete();
        void onError(int errorCode);
    }
    public static final int BACKUP_SUCCESS = 1;
    public static final int RESTORE_SUCCESS = 2;
    public static final int BACKUP_ERROR = 3;
    public static final int RESTORE_NOFILEERROR = 4;
    public static final String COMMAND_BACKUP = "backupDatabase"; // cmd for backup databse
    public static final String COMMAND_RESTORE = "restoreDatabase"; // cmd for restore the database
    private Context mContext;
    private CompletionListener listener;
    public BackAsyncTask(Context context) {
        super();
        mContext = context;
    }
    public void setCompletionListener(CompletionListener aListener) {
        listener = aListener;
    }
    @Override
    protected Integer doInBackground(String... params) {
// inside doinbackground creating directry for backup file and copy the file
        File dbFile = mContext.getDatabasePath("mydb");
        File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        File backup = new File(exportDir, dbFile.getName());
        String command = params[0];
        if(command.equals(COMMAND_BACKUP)) {
            try {
                backup.createNewFile();
                fileCopy(dbFile, backup);
                return BACKUP_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else if(command.equals(COMMAND_RESTORE)) {
            try {
                if(!backup.exists()) {
                    return RESTORE_NOFILEERROR;
                }
                dbFile.createNewFile();
                fileCopy(backup, dbFile);
                return RESTORE_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else {
            return BACKUP_ERROR;
        }
    }
   
    @Override
    protected void onPostExecute(Integer result) {

        switch(result) {
// result for back up success
        case BACKUP_SUCCESS:
            if(listener != null) {
                listener.onBackupComplete();
            }
            break;
        case RESTORE_SUCCESS:
            if(listener != null) {
                listener.onRestoreComplete();
            }
            break;
        case RESTORE_NOFILEERROR:
            if(listener != null) {
                listener.onError(RESTORE_NOFILEERROR);
            }
            break;
        default:
            if(listener != null) {
                listener.onError(BACKUP_ERROR);
            }
        }
    }
    // this method for copying the file  source to disetination
    private void fileCopy(File source, File dest) throws IOException {
        FileChannel inChannel = new FileInputStream(source).getChannel();
        FileChannel outChannel = new FileOutputStream(dest).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }
Download FullSourecode
  b) Notification Activity
A class that represents how a persistent notification is to be presented to the user using the NotificationManager.
The Notification.Builder has been added to make it easier to construct Notifications.
This Notification Activity for notify any task completed.
 Sample Code 


 
/**
* * @author vijayakumar
*
*/
public class AndroidMADQAActivity extends Activity implements View.OnClickListener {
private static final int NOTE_ID = 100;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Click New Notification");
button.setOnClickListener(this);
setContentView(button);
}
@Override
public void onClick(View v) {
handler.postDelayed(task, 10000);
Toast.makeText(this, "Notification will Appear in 10 seconds", Toast.LENGTH_SHORT).show();
}
private Handler handler = new Handler();
private Runnable task = new Runnable() {
@Override
public void run() {
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent launchIntent = new Intent(getApplicationContext(), AndroidMADQAActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent, 0);
Notification note = new Notification(R.drawable.ic_launcher, "Download Completed", System.currentTimeMillis());
note.setLatestEventInfo(getApplicationContext(), "Finished!", "Click Here!", contentIntent);
note.defaults |= Notification.DEFAULT_SOUND;
note.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(NOTE_ID, note);
}
};
}

C).Timer Activity
 Timer activity class  represents will keep updating current time using timer task.
Sampe code .


 import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
/**
 *
 * @author vijayakumar
 *
 */
public class AndroidMADQAActivity extends Activity {  
    TextView mClock;   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mClock = new TextView(this);
        setContentView(mClock);
    } 
    private Handler mHandler = new Handler();
    private Runnable timerTask = new Runnable() {
        @Override
        public void run() {
            Calendar now = Calendar.getInstance();
            mClock.setText(String.format("%02d:%02d:%02d",
                    now.get(Calendar.HOUR),
                    now.get(Calendar.MINUTE),
                    now.get(Calendar.SECOND)) );
            mHandler.postDelayed(timerTask,1000);
        }
    };
    @Override
    public void onResume() {
        super.onResume();
        mHandler.post(timerTask);
    }
    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(timerTask);
    }

}

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...