How do you rate this blog

Sunday, January 22, 2012

ViewFlipper


             A ViewFlipper is used to animate the movement between 2 or more different views. This is generally used to improve the visual and make the app appear smooth.

So in this post I have created a small and simple app using the ViewFlipper control. The flow of the app is given below –
1) The first screen will have a text indicating the screen on which the user is present and it will have a button through which the user can go to the second screen.
2) When the user clicks on the button in screen 1 the first screen will move to right and the second screen will move in from left.
3) The second screen will be similar to the first screen but the button will redirect the user to the first screen.
If you haven’t got the flow, go to the bottom of the post where I have included the snapshot of the output.

Now lets get on with the coding part. Create a new project, once you have created a new project you need to create a new folder in res (resource) call it anim (you can name the folder anything you like. Here I have named it as anim). In this folder create new xml files which will define the animation of the screen. Create 2 new xml called transition_in_left and transition_out_left.

Ok here I will deviate from the topic a bit, since we need to understand what animation is all about.  As you know animation is making simple transformation or loading of different images to make an object livelier. In android there are 2 kinds of animation \
1) Property Animation – Creates animation by modifying the property of the image.
2) View Animation – Creates animation by showing sequence of image in sequence.
In this post I am using View animation, which in turn has 2 types
1) Tween Animation – Animation by performing series of transformation on an image.
2) Frame Animation – Animation by showing sequence of images in a particular order.

In this post I will be using Tween animation and will use the translate property of it, given below is a very brief description of the same.
It has 4 main elements,
1) alpha – provides fade in and fade out animations.
2) scale – provides the ability to increase or decrease the size.
3) translate – provides the ability to make horizontal or vertical movement.
4) rotate – provides the ability to rotate the image

So open the transition_in_left.xml file and use the code below. The below code will case the screen to move from left to right as you can see the fromdelta value changes from -100% to 0.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:interpolator="@android:anim/decelerate_interpolator">
<translate
 android:fromXDelta="-100%"
 android:toXDelta="0%"
 android:duration="500" />
</set>

Similarly create open another xml file transition_in_left.xml and add the property as shown below –
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:interpolator="@android:anim/decelerate_interpolator">
<translate
 android:fromXDelta="0%"
 android:toXDelta="100%"
 android:duration="500" />
</set>

Now that we are done with the definition of the animator, lets define the main layout. Open main.xml layout in resà layout folder. Remove the existing text box and add a new textbox which will have a text called “View Flipper Demo”. Then add the fiew flipper such that it spans the entire length and width of the screen. Then add the LinearLayout which will have a text which indicates the screen which you are in and a button which will cause the second screen to appear with animation. Add one more LinearLayout and add the same contents as in screen 1.

With the UI and the animation done, we need to add action part. So go to the src folder and open the java file in it. As you can see the basic features are already present.
We need to bind the viewflipper, buttons , animations and assign action to the buttons. The code below does the same

The below code defines the ViewFlipper and buttons used.
        final ViewFlipper vf=(ViewFlipper) findViewById(R.id.viewFlipper1);
        Button firstScreenButton=(Button) findViewById(R.id.buttonfirstscreen);
        Button secondScreenButton=(Button) findViewById(R.id.buttonsecondscreen);
 
Then you need to define the animations. The below code does the same
        Animation inanimation=AnimationUtils.loadAnimation(this,R.anim.transition_in_left);
        Animation outanimation=AnimationUtils.loadAnimation(this, R.anim.transition_out_left);
 Now we need to assign the animation to in and out movements.
        vf.setInAnimation(inanimation);
        vf.setOutAnimation(outanimation);
  
Since we need the animations to appear when button is clicked we need to assign action to the onClickListener as shown below. In the below code we assign action to button in Screen1.
        firstScreenButton.setOnClickListener(new Button.OnClickListener(){

                   @Override
                   public void onClick(View arg0) {
                   vf.showNext();
                   }});
  
Similarly we need to assign action for the button in screen2.
        secondScreenButton.setOnClickListener(new Button.OnClickListener(){

                   @Override
                   public void onClick(View arg0) {
                   vf.showPrevious();
                   }});

The entire file will look in the snapshot shown below.



Now run the application in an emulator or a device. When the application runs the first screen that appears is given below. 



Click on the button and you can see the screen 1 appears to move out and screen 2 appears to move in from left replacing screen1 as shown below.



Now that you are in screen 2 it will be as shown in the snapshot shown below. Click on the button and it should take you back to the first Screen.


Wednesday, January 4, 2012

SeekBar

A seekbar is just like a progress bar with a dragger in it which the user can set. In this post I have just created a simple seekbar which shows the value in a text below and shows if the tracking is on if the touch is present over the tracker.
First create a new project. Then open file main.xml under resà layouts. Remove the default text there and add a text which will show if the tracking is on or not. Below that add the seekbar control. Below this add one more text which will show the value to which the slider has been dragged to. The layout will look as shown in the snapshot below.


Then we need to bind the functionality with the UI controls so open the java file under src à your package. You can see already there will be basic code is already there. The class will by default extend Activity you need to implement OnSeekBarChangeListener, once you do this you will need to override other functions onProgressChanged, onStartTrackingTouch, onStopTrackingTouch. Then declare the seekbar and the 2 text views which will show the tracking status and the value.
Then create a seekbar and create a listener for that as shown below-
sb=(SeekBar) findViewById(R.id.seekBar1);
sb.setOnSeekBarChangeListener(this);
Then you need to declare and bind the textboxes. Once this is done you need to add functionality when the seekbar position is changed, when the tracking has started, when the tracking has stopped as shown below.
@Override
public void onProgressChanged(SeekBar arg0, int progress, boolean TouchStart) {
                                sv.setText("Progress="+String.valueOf(progress));
}

@Override
public void onStartTrackingTouch(SeekBar arg0) {
                                title.setText("Tracking On");
}

@Override
public void onStopTrackingTouch(SeekBar arg0) {
                                title.setText("Tracking Off");
}
 Once this is done we are done and the file will look as in the snapshot given below.

Now run the project in your emulator or mobile. Drag the slider and the text above the seekbar should change to Tracking On and when u stop it should say Tracking off and the value in the textbox below the seekbar should show value at which the slider has been dragged to as show in the snapshot given below.


Thursday, December 22, 2011

Introduction to Fragments


    As the name suggests, a fragment is a subset of the UI in an activity. What this means is now  you can create multiple fragments in the same UI of an activity. The fragment can perform actions independent of other fragments while an activity is running. This means a fragment has its own lifecycle and it exists till the activity is running. The fragments can also be reused. This property is released from Android 3.0 API 11 onwards but it can be used in lower version as well, refer to this to get more info.
                So what is the use of fragments, well there are lot of places where these properties can be exploited to the fullest. A developer can create 2 separate fragments where in one fragment can be used to display a list of values and other fragment can be used to display description of the item selected in the list. Developers can also take advantage of this in devices like tablets where the display area is very large and by using fragments they can add many functionality in a single activity.

LifeCycle on a Fragment –
                In this lets see how to use a fragment. The following are the states while you use a fragment.
Creation of Fragment – You need to create a subclass of Fragments. Then you need to attach the fragment to an activity using Attach(). Then you need to call the view hierarchy with which the fragments are associated with using creatView() method.  Then you need to create onCreate() where in you instantiate the fragment and retain the parts of the fragment when it is paused state.

Running state of a fragment- When the activity is started the onStart() method is called by the activity to make the fragment visible to user.  

Resume –  The method onResume() makes the fragment intractable with the user.

Paused – In this state the fragment is processing function after the user action or has been paused. This is done by onPause() method.

Stop – When the activity is completed or closed by the user the method onStop() is called.

Destruction of the fragment – The method onDestroyView() is called to destroy the view hierarchy associated with the fragment. Then it calls onDestroy() to release all the resources used by the fragment. Then the fragment is disassociated from the activity by the method onDettach().

As you can see it’s relatively complex but none the less interesting and helpful in using the screen real estate and providing a nice UI to the users. In the next post will give an example using the fragment.

Sunday, December 18, 2011

Creating Simple Gestures


Gestures are mainly useful in touch screens. Instead of users clicking on the menu and performing actions they can use gestures to perform the same. A gesture can be used to perform actions like add, delete, update etc.
In this post I have used to gestures to display alert dialogues. For this you need to add gestures using the GestureBuilder. The GestureBuilder is available in your emulators. Make sure that your emulator has SD card configured.
If you need to add SD Card into the emulator –
Step1 – Open command prompt go the folder where the android-sdk is located and go to tools and use the below command
“mksdcard 256M <path>\<filename>.iso“
you can vary the size of the SD card based on your needs.
Step2 - Now open the AVD manager, click on the AVD for which you want to add the SD card and click on edit.
Step 4 - Now make the SD card point to the iso file created in the step above.
Open the GestureBuilder app in the emulator and create your own gestures as shown below.



Now that you have added the Gestures you need to copy it to the local environment and add it to the solution since it will be used in the GestureOverlayView.
You can copy the data from the sdcard by –
Step 1 – Start the emulator.
Step2 – open command prompt and go to the <anroid-sdk location>/platform-tools and use the below command
Adb pull /sdcard/gestures <folder on your local environment>

Now create a new project. Then create a new folder called ‘raw’ under ‘res’. Then open ‘main.xml’ file under layouts and remove the default text box. Now add the GestureOverlayView and match its width and height with that of the parent.

Now go to the main java file, you will notice it extends Activity by default. Since we also need gestures we have to implement OnGesturePerformedListener as well. Once you do that you can see it suggests you to implement onGesturePerformed as well. This function is required since we will define the actions based on the gestures which are available.
Before defining actions we need to define GestureOverlayView and bind it to the control which we have defined in the ‘main.xml’ and add function which will read the gesture performed.
GestureOverlayView gov=(GestureOverlayView) findViewById(R.id.gestureOverlayView1);
gov.addOnGesturePerformedListener(this);
Now we need to define the Gesture library and include the gestures we had created earlier.
gl=GestureLibraries.fromRawResource(this, R.raw.gestures);
if(!gl.load()){
  finish();
}

Now we need to define the action when the gesture is performed and this is done inside onGesturePerformed.
Here you need to create an arraylist which will store all the gestures. Then we need to see if the gesture has matched a certain gesture in the library. If the score is above 1 then it’s a pretty good one else its considered poor. Hence we will consider only those gestures which have score greater than 1 and create an alert dialog with the name of the gesture.
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {                        
ArrayList<Prediction> pred=gl.recognize(gesture);         
for(Prediction p:pred){
if(p.score > 1.0){
AlertDialog.Builder ab=new AlertDialog.Builder(GesturesDemoActivity.this);
ab.setTitle("Gesture Demo");
ab.setMessage("You used the gesture"+p.name);
ab.setPositiveButton("OK",null);
ab.show();
                }
}
The code will look like the snapshot shown below


Now run the project in the simulator. Once the app starts running, write a gesture which you have created earlier as shown below.



When you release the touch from the screen you can see an alert dialog appears with the name of the gesture on it.


Thursday, December 15, 2011

Beautiful world of Android Sensors – Accelerometer


Well finally decided to get hands on sensors in android. In my view it’s the most exciting part of android. It will surely light up new ideas.
The sensors are used to detect changes in the phones surrounding environment like change in position, temperature, light etc. Android provides various sensors like – Accelerometer, Gyroscope, Light, Magnetic Field, Pressure, Temperature, Orientation and Proximity. I am sure looking at the list you will be excited to use these features. There is a catch however, not all sensors are available on all the phones. Only in high end android phones there is a high possibility of all the sensor hardware being included. In this post I will use the Accelerometer since it will be available in almost all android phones.
                I will use the accelerometer and try to find out if the phone has been shaked. If the phone has been shaked beyond certain threshold it should display it in the textbox with the value.
                Create a new project and choose Android 2.3.3. Go to the layout under the folder ‘res’ and open the file main.xml and remove the default contents. Add a Large text which will display a text if the phone has been shaked along with the value.
Now open the main java file, and declare a variable which is of the type SensorManager, also declare variable which will hold the acceleration across x, y and z axis as shown below.
SensorManager sensorMgr;
float xaxis,yaxis,zaxis;
float accel;

Next you need to create a SensorEventListener, if you are referring to old android ebooks it might have used SensorListener which is deprecated in android 2.3.3 onwards. When you create SensorEventListener you need to implement 2 functions one is onSensorChanged which is used to detect change in the sensors values and the other is called when accuracy of sensor has changed, this is received by the system and you cannot set anything like high accuracy etc.
Now inside the onSensorChanged function get the values of acceleration across x, y and z axis from the sensorevent as shown below.
xaxis=event.values[0];                                 
yaxis=event.values[1];                                 
zaxis=event.values[2];
Now that we have values lets calculate the acceleration as √x^2+y^2+Z^2.
accel=(float) Math.sqrt((double) ((xaxis*xaxis)+(yaxis*yaxis)+(yaxis*yaxis)));
Since we want the value to be displayed only if it is shaked beyond a point we will use if condition for this. In this case we will make 2 as the threshold value.
if(accel >=2){
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText("The Device was shaked and the acceleration was "+accel);
                                                }

So the SensorEventListener will look like as shown below
private final SensorEventListener listner=new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
xaxis=event.values[0];
yaxis=event.values[1];
zaxis=event.values[2];
accel=(float) Math.sqrt((double) ((xaxis*xaxis)+(yaxis*yaxis)+(yaxis*yaxis)));
if(accel >=2){
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText("The Device was shaked and the acceleration was "+accel);
}                                                                                             
                                }                                                             
                };
Now create a sensor manager and register the accelerometer sensor to it in the OnCreate function as shown below.
sensorMgr=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorMgr.registerListener(listner, sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
In registerListener function, you will have to set the SensorEventListener which you have created above. Then set the sensorManager to Accelerometer.  After this you will have to set the rate at which the sensor data are delivered here we can use for game.
Well you might think that we are done at this part, but its not. The sensors eat up lot of resource in the phone so it’s a good practice that we unregister the listener when it’s paused or stopped and started on resumption as shown below.
 @Override
    protected void onResume(){
super.onResume();
sensorMgr.registerListener(listner, sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
    }

@Override
public void onStop(){
sensorMgr.unregisterListener(listner);
super.onStop();
    }
   
@Override
protected void onPause(){
sensorMgr.unregisterListener(listner);
super.onPause();  }
The code will look the snapshot given below.



Now run the app on your phone and shake it, once you shuffle it the text box should change as shown in the screen shot given below.

The above screen shot is taken from a mobile.

Well this is just a simple application and we have just skimmed the surface. I will post more about various sensors in the future : ).

Saturday, December 3, 2011

Photo Gallery


Well I wanted to try out gallery in android and finally I got time and little idea to do it. In this post I have created a gallery which will display 3 images and you can scroll through it.
Create a new project and open res folder and add images which want to display in the app into this folder. Once you are done open the main.xml file and drag the gallery control onto the screen area. Then you need to create resource called styleable which will be applied to each item of the gallery.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="GalleryTheme">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>

Then create a new class where you will define the images and bind to the gallery. We will extend BaseAdapter since we need adapter to hold all the images. Now create an array which has the names of the all the images which need to be displayed as shown below.
Integer images[]={R.drawable.ferrari,R.drawable.manutd,R.drawable.rcb};
Then create a constructor which takes the context into consideration. Then define the style for the images as shown below.

public MyImageGallery(Context ctx){
context=ctx;
TypedArray ta = ctx.obtainStyledAttributes(R.styleable.GalleryTheme);
galleryItem=ta.getResourceId(galleryItem, R.styleable.GalleryTheme_android_galleryItemBackground);
ta.recycle();
}
When you extend the BaseAdapter the eclipse will give u warning saying you need to implement 4 methods
1) getCount() – to get the number of items in the array.
public int getCount() {
return images.length;
                                          }
2) getItem(int pos) – to get the particular item at the position as specified.
                                @Override
                                public Object getItem(int pos) {
                                                                                return pos;
                                }
3) getItemId(int pos)  - to obtain the Id of the item at the position specified.
                                public long getItemId(int pos) {
                                                return pos;
                                }
4) getView() – where you define the properties related to the image.
@Override
                public View getView(int arg0, View view, ViewGroup vg) {
                                ImageView iv=new ImageView(context);
                                iv.setImageResource(images[arg0]);
                                iv.setLayoutParams(new Gallery.LayoutParams(500, 500));
                                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                                iv.setBackgroundResource(galleryItem);
                                return iv;
                }
The final code will look as shown in the screenshot given below.



Now that we are done creating the adapter for the images, go back to the main java file and create a new Gallery and start the above class which will define all the images as shown in the code below
Gallery gly=(Gallery) findViewById(R.id.gallery1);
gly.setAdapter(new MyImageGallery(this));

The main java file will look as shown below.




Now run the project and the result is as shown below when you scroll through the gallery.





Friday, December 2, 2011

Sliding Drawer with simple Checkboxes


In this post I have created a simple sliding drawer and have placed three checkboxes in it. A sliding drawer is generally used to hide contents and only show it when the user wishes to see them.  Checkboxes are used when you want to select more than one checkbox at a time.

First create a new project and open main.xml file under resà layout. Add a textbox to the top of the layout. Add sliding drawer into the layout, you can see it comes with a default button called Handle, rename this to ‘Click to Open the slider’. Then add 3 check boxes into the sliding drawer. Finally the layout will look like the image shown below.



Now open the java file under src folder. You can see there is a default code already available to you. Now create a sliding drawer component and bind it to the resource as defined by you in the xml file.
SlidingDrawer sh=(SlidingDrawer) findViewById(R.id.slidingDrawer1);
Similarly bind the button and all the check boxes in the layout as shown below.

final CheckBox Messi, Ronaldo,Rooney;
Messi=(CheckBox) findViewById(R.id.checkBox1);
Rooney=(CheckBox) findViewById(R.id.checkBox2);
Ronaldo=(CheckBox) findViewById(R.id.checkBox3);
final Button insideslider=(Button) findViewById(R.id.button1);
final TextView tv=(TextView) findViewById(R.id.textView1);       

Now we need to define action for the sliding drawer when it opens and closes. So when the sliding drawer is opened it has all the checkboxes and the button, so we need to define action when the user ticks the checkboxes and clicks on the ‘Done’ button.  To check if the checkbox is selected or not use the ‘isChecked()’ function. Also we can modify the text of the sliding drawer button and change it ‘Click to Close the Slider’. The code shown below shows the same.

sh.setOnDrawerOpenListener(new OnDrawerOpenListener() {
               
               
                                @Override
                                public void onDrawerOpened() {
                                                button.setText("Click To Close Silder");
                                                insideslider.setOnClickListener(new View.OnClickListener() {
                                                                @Override
                                                                public void onClick(View v) {
                                                                                String Value="You Selected";
                                                                                if(Messi.isChecked()){
                                                                                                 Value+=" Messi ";
                                                                                }
                                                                                if(Rooney.isChecked()){
                                                                                                Value+=" Rooney ";
                                                                                }
                                                                                if(Ronaldo.isChecked()){
                                                                                                Value+=" Ronaldo ";
                                                                                }
                                                                                tv.setText(Value);                          
                                                                }
                                                });
                                }
                                });

Now that we have defined the function when the sliding drawer is opened, we can define the function when the sliding drawer is closed. Here I have changed the text on the sliding drawer button to ‘Click to Open the Sliding Drawer’ button. The code below shows the same.
sh.setOnDrawerCloseListener(new OnDrawerCloseListener() {
                @Override
                public void onDrawerClosed() {
                                button.setText("Click To Open Silder");
                }
  });



Now run the application and the output will be as shown in the screenshot shown below.



Click on the button and you can see the checkboxes and also observe that the text of the button has changed, select on any one of them or all of them and click on ‘Done’ button.  You can see all the checkboxes which you selected appear on in the textbox.



Hope you were able to create the same.