Showing posts with label beginner. Show all posts
Showing posts with label beginner. Show all posts
Thursday, February 5, 2015
Android beginner tutorial Part 96 Frame Animation using code
In this tutorial we will learn how to create a Frame Animation using Java code instead of an XML file.
Well be using the same 3 drawable resources (images) as frames in this tutorial as we did last time. But instead of creating the sequence in an XML file, well do that in the MainActivity.java class of our project.
The acitivty_main.xml layout file remains like this:
In MainActivity class, we first declare an AnimationDrawable and ImageView instances:
We then add 2 clicks listeners to the two buttons on the screen. When the Start button is pressed, create 3 BitmapDrawable instances that refer to the 3 drawable resources we have. Then set the value of the animation object to a new AnimationDrawable() instance, set its oneShot property to false using setOneShot() method. Add each frame to it using addFrame() method, which has 2 parameters - reference to the drawable used in this frame and the duration of the frame.
Then we set the content of the image to this animation using setImageDrawable() method and start the animation after making it visible using the setVisible() method:
When the Stop button is pressed, stop the animation:
Full code:
Thanks for reading!
Read more »
Well be using the same 3 drawable resources (images) as frames in this tutorial as we did last time. But instead of creating the sequence in an XML file, well do that in the MainActivity.java class of our project.
The acitivty_main.xml layout file remains like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button android:text="Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/btn_start"
/>
<Button android:text="Stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/btn_stop"
/>
</LinearLayout>
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
In MainActivity class, we first declare an AnimationDrawable and ImageView instances:
AnimationDrawable animation;
ImageView image;
We then add 2 clicks listeners to the two buttons on the screen. When the Start button is pressed, create 3 BitmapDrawable instances that refer to the 3 drawable resources we have. Then set the value of the animation object to a new AnimationDrawable() instance, set its oneShot property to false using setOneShot() method. Add each frame to it using addFrame() method, which has 2 parameters - reference to the drawable used in this frame and the duration of the frame.
Then we set the content of the image to this animation using setImageDrawable() method and start the animation after making it visible using the setVisible() method:
final Button btnStart = (Button)findViewById(R.id.btn_start);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BitmapDrawable frame1 = (BitmapDrawable)getResources().getDrawable(R.drawable.sample1);
BitmapDrawable frame2 = (BitmapDrawable)getResources().getDrawable(R.drawable.sample2);
BitmapDrawable frame3 = (BitmapDrawable)getResources().getDrawable(R.drawable.sample3);
animation = new AnimationDrawable();
animation.setOneShot(false);
animation.addFrame(frame1, 500);
animation.addFrame(frame2, 500);
animation.addFrame(frame3, 500);
image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(animation);
animation.setVisible(true, true);
animation.start();
}
});
When the Stop button is pressed, stop the animation:
final Button btnStop = (Button)findViewById(R.id.btn_stop);
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
animation.stop();
animation.setVisible(false, false);
}
});
Full code:
package com.example.codeforfoodtest_two;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity{
AnimationDrawable animation;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btnStart = (Button)findViewById(R.id.btn_start);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BitmapDrawable frame1 = (BitmapDrawable)getResources().getDrawable(R.drawable.sample1);
BitmapDrawable frame2 = (BitmapDrawable)getResources().getDrawable(R.drawable.sample2);
BitmapDrawable frame3 = (BitmapDrawable)getResources().getDrawable(R.drawable.sample3);
animation = new AnimationDrawable();
animation.setOneShot(false);
animation.addFrame(frame1, 500);
animation.addFrame(frame2, 500);
animation.addFrame(frame3, 500);
image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(animation);
animation.setVisible(true, true);
animation.start();
}
});
final Button btnStop = (Button)findViewById(R.id.btn_stop);
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
animation.stop();
animation.setVisible(false, false);
}
});
}
}
Thanks for reading!
Friday, January 30, 2015
Android beginner tutorial Part 55 Explicit Intent basics
Today we will learn the basics of launching an Activity using an Explicit Intent.
Activities, as well as other Android components, are invoked using Intent objects. Intents can be used for communication between Activities of one or multiple applications.
There are two types of Intents - explicit and implicit. Explicit Intents refer to an exact, specific component. They usually dont carry much information on their own, but simply launch an Activity or some other internal process. Implicit ones dont have a specified component. They carry information so that the system decides what to run based on the requirements.
Today well learn how to launch a second Activity using an Explicit Inetnt object. To call an Activity, we need to provide the name of that Activity, which is done using one of the 3 methods - setComponent(), setClass() or setClassName().
First lets design our application, then establish the Intents. There will be 2 Activities - MainActivity and SecondActivity. The MainActivity layout will have 2 TextViews and a Button. The button will be used for calling the second Activity, the first TextView will be used to indicate that this is the main activity. The second TextView will act as a log, where we will display the name of all callback functions when they are called.
Go to activity_main.xml and use this layout code:
Create a new xml file in the layout folder next to activity_main.xml, call it activity_second.xml.
Display a single TextView there to indicate that it is the second Activity:
Go to the src folder using the PackageExplorer in Eclipse and open the current package. Add a new class there called SecondActivity.java.
The code is very simple, it doesnt even do anything:
And here is the code for MainActivity.java class. In the onCreate() function we set a click event listener to the Button that we have. Inside of the onClick() function of the listener, create a new Intent object, call its setClass() method to refer to the SecondActivity.class object, then start the Activity using startActivity() method and passing the intent object in the parameter.
Then create callback onStart(), onRestart(), onResume(), onPause(), onStop() and onDestroy() functions.
We are almost done. The only thing left is to go to AndroidManifest.xml file and add a new Activity. Open the Manifest using Eclipse and select the Application tab, scroll down to Application Nodes window and click Add...
Set the name of the application to SecondActivity with the package name and all that jazz, it should look something like this:
Save everything and test the application. You should be now able to launch a second activity from your first one. Youll also see the changes in the log text view.
Thats all for today.
Thanks for reading!
Read more »
Activities, as well as other Android components, are invoked using Intent objects. Intents can be used for communication between Activities of one or multiple applications.
There are two types of Intents - explicit and implicit. Explicit Intents refer to an exact, specific component. They usually dont carry much information on their own, but simply launch an Activity or some other internal process. Implicit ones dont have a specified component. They carry information so that the system decides what to run based on the requirements.
Today well learn how to launch a second Activity using an Explicit Inetnt object. To call an Activity, we need to provide the name of that Activity, which is done using one of the 3 methods - setComponent(), setClass() or setClassName().
First lets design our application, then establish the Intents. There will be 2 Activities - MainActivity and SecondActivity. The MainActivity layout will have 2 TextViews and a Button. The button will be used for calling the second Activity, the first TextView will be used to indicate that this is the main activity. The second TextView will act as a log, where we will display the name of all callback functions when they are called.
Go to activity_main.xml and use this layout code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="32sp"
android:text="Main Activity"
/>
<Button android:id="@+id/callButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Call another activity"
/>
<TextView android:id="@+id/logText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Create a new xml file in the layout folder next to activity_main.xml, call it activity_second.xml.
Display a single TextView there to indicate that it is the second Activity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="32sp"
android:text="Second Activity"
/>
</LinearLayout>
Go to the src folder using the PackageExplorer in Eclipse and open the current package. Add a new class there called SecondActivity.java.
The code is very simple, it doesnt even do anything:
package com.kircode.codeforfood_test;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
And here is the code for MainActivity.java class. In the onCreate() function we set a click event listener to the Button that we have. Inside of the onClick() function of the listener, create a new Intent object, call its setClass() method to refer to the SecondActivity.class object, then start the Activity using startActivity() method and passing the intent object in the parameter.
Then create callback onStart(), onRestart(), onResume(), onPause(), onStop() and onDestroy() functions.
package com.kircode.codeforfood_test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity{
private TextView logText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logText = (TextView)findViewById(R.id.logText);
final Button btn = (Button)findViewById(R.id.callButton);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
}
public void onStart(){
super.onStart();
logText.append("onStart();
");
}
public void onRestart(){
super.onRestart();
logText.append("onRestart();
");
}
public void onResume(){
super.onResume();
logText.append("onResume();
");
}
public void onPause(){
super.onPause();
logText.append("onPause();
");
}
public void onStop(){
super.onStop();
logText.append("onStop();
");
}
public void onDestroy(){
super.onDestroy();
logText.append("onDestroy();
");
}
}
We are almost done. The only thing left is to go to AndroidManifest.xml file and add a new Activity. Open the Manifest using Eclipse and select the Application tab, scroll down to Application Nodes window and click Add...
Set the name of the application to SecondActivity with the package name and all that jazz, it should look something like this:
com.kircode.codeforfood_test.SecondActivity
Save everything and test the application. You should be now able to launch a second activity from your first one. Youll also see the changes in the log text view.
Thats all for today.
Thanks for reading!
Monday, January 19, 2015
Android beginner tutorial Part 4 Running and debugging applications
Today well learn how to run and debug our application.
There are two ways to run our Android application - using an emulator, and using a real Android device that is connected to the computer.
First Ill explain how to install and run the application on a real Android device. Connect your device to the computer using a USB cable. You might need to install proper device drivers to do this correctly. Take your phone/tablet, launch Settings > Applications > Deevlopment, then make sure USB debugging item is checked.
Open your project in Eclipse, then in the menu select Run > Run. A window will pop up asking you to select a device or an emulator. Select your device, and click OK. Your application will be installed and launched on the device! By default its a simple screen with "Hello World" written on it.
Youll also find your application in the menu of your device, with the icon and title youve set. You can launch it from there as well.
The second way to run an application is using an emulator. Go to Window > Android Virtual Device Manager in Eclipse. Hit New, set the name and settings for your virtual device. Youre free to play around with the settings, if something is entered incorrectly - you will be informed of the error. When youre done, click OK.
You can now see your device in the list of the Android Virutal Devices tab in the dialog window. You can start it now by selecting it and hitting "Start". Youll have to wait for the system to boot on the virtual device before you can use it. Then you can look around the phone/tablet almost like its real.
Then go to Run > Run, and select the virtual device you have to launch your application there. If you didnt start your emulator before, you can do it here by ticking "Launch a new Android Virtual Device" radio button and then selecting the AVD.
And thats all you need to do to launch your application!
However, when developing programs, you might need more advanced debugging tools than just an error console.
There are 2 ways to debug Android applications in Eclipse - one is using the java debugger, the other one is using the DDMS (Dalvik Debug Monitor Server).
To use the java debugger, open Eclipse and go to Window > Open Perspective > Debug. Youll find a new button in the top right sector of the Eclipse IDE window labeled "Debug", located near Java button.
Launch your application if it isnt already launched on either your real device or an emulator, and youll see some activity taking place in the left section of the debug screen. You can select items there and manipulate things like Variables on the right side of the screen. If its just a simple application like our Hello World, there wont be much to do (or there wont be anything at all to debug).
The Debug feature includes Variables, Breakpoints and LogCat, which are tools that you can use to see values of variables, breakpoints, as well as system log messages in real time.
The Dalvik Debug Monitor Service is a tool that is included with Android SDK and is not present in Eclipse by default.
It can be launched the same way - Window > Open Perspective > DDMS. Youll quickly see that its more advanced than the standard Debug tool and includes more features. It gives you control of many Android-related objects and processes. You can even explore the files of the device. Its rather complex for me to explain all of its features, I suggest you head over to the official documentation page for DDMS if you want to explore all of its features.
And thats it for this tutorial!
Thanks for reading!
Read more »
There are two ways to run our Android application - using an emulator, and using a real Android device that is connected to the computer.
First Ill explain how to install and run the application on a real Android device. Connect your device to the computer using a USB cable. You might need to install proper device drivers to do this correctly. Take your phone/tablet, launch Settings > Applications > Deevlopment, then make sure USB debugging item is checked.
Open your project in Eclipse, then in the menu select Run > Run. A window will pop up asking you to select a device or an emulator. Select your device, and click OK. Your application will be installed and launched on the device! By default its a simple screen with "Hello World" written on it.
Youll also find your application in the menu of your device, with the icon and title youve set. You can launch it from there as well.
The second way to run an application is using an emulator. Go to Window > Android Virtual Device Manager in Eclipse. Hit New, set the name and settings for your virtual device. Youre free to play around with the settings, if something is entered incorrectly - you will be informed of the error. When youre done, click OK.
You can now see your device in the list of the Android Virutal Devices tab in the dialog window. You can start it now by selecting it and hitting "Start". Youll have to wait for the system to boot on the virtual device before you can use it. Then you can look around the phone/tablet almost like its real.
Then go to Run > Run, and select the virtual device you have to launch your application there. If you didnt start your emulator before, you can do it here by ticking "Launch a new Android Virtual Device" radio button and then selecting the AVD.
And thats all you need to do to launch your application!
However, when developing programs, you might need more advanced debugging tools than just an error console.
There are 2 ways to debug Android applications in Eclipse - one is using the java debugger, the other one is using the DDMS (Dalvik Debug Monitor Server).
To use the java debugger, open Eclipse and go to Window > Open Perspective > Debug. Youll find a new button in the top right sector of the Eclipse IDE window labeled "Debug", located near Java button.
Launch your application if it isnt already launched on either your real device or an emulator, and youll see some activity taking place in the left section of the debug screen. You can select items there and manipulate things like Variables on the right side of the screen. If its just a simple application like our Hello World, there wont be much to do (or there wont be anything at all to debug).
The Debug feature includes Variables, Breakpoints and LogCat, which are tools that you can use to see values of variables, breakpoints, as well as system log messages in real time.
The Dalvik Debug Monitor Service is a tool that is included with Android SDK and is not present in Eclipse by default.
It can be launched the same way - Window > Open Perspective > DDMS. Youll quickly see that its more advanced than the standard Debug tool and includes more features. It gives you control of many Android-related objects and processes. You can even explore the files of the device. Its rather complex for me to explain all of its features, I suggest you head over to the official documentation page for DDMS if you want to explore all of its features.
And thats it for this tutorial!
Thanks for reading!
Sunday, January 18, 2015
Android beginner tutorial Part 89 ShapeDrawable shapes
Today well learn about drawing shapes in Android using the ShapeDrawable class.
If you want to dynamically draw 2d shapes, the ShapeDrawable class might be what youre looking for. Similar to the Flash Drawing API used in Actionscript 3, this Android gives us the ability to draw and stylize simple primitive shapes.
There is a set of classes extended from Shape, which we can use to create different shapes. These classes are PathShape, RectShape, ArcShape, OvalShape and RoundRectShape.
The ShapeDrawable class is an extension of Drawable, so it can be used just like any other Drawable object. When drawing in a ShapeDrawable - remember to set the color and the boundaries of the object. If the color is not specified - black will be used by default. If the boundaries are not set - the drawing will not be visible.
Firstly, lets see how to draw lines with this. There isnt a separate class for displaying lines, but theres RectShape, which can work as lines too if we make them thing enough.
Example:
An oval is drawn similarly to a rectangle. Simply set the width and height:
Drawing rounded rectangles is a little bit more complex, but not hard at all. The RoundRectShape constructor has 3 parameters - outerRadii, inset and innerRadii.
The outerRadii value is an array of float values that represent the radii of each corner. Each corner has 2 radii, so there are 8 values in total. The first 2 values are the radii of the top left corner, each next 2 correspond to the next corner clockwise. If you dont want rounded corners, pass null.
The inset value is a RectF class object, which represents the distance between the inner rectangle and the outer one. The constructor of the RectF class has 4 parameters - pairs of coordinates (x and y) of top left corner and bottom right corner of the inner rectangle. If theres no inner rectangle, pass null.
The innerRadii value is an array of radii for the corners of the inner rectangle. Works the same way as outerRadii.
A simple example:
Thats all for today. Next time well look at more shapes to draw.
Thanks for reading!
Read more »
If you want to dynamically draw 2d shapes, the ShapeDrawable class might be what youre looking for. Similar to the Flash Drawing API used in Actionscript 3, this Android gives us the ability to draw and stylize simple primitive shapes.
There is a set of classes extended from Shape, which we can use to create different shapes. These classes are PathShape, RectShape, ArcShape, OvalShape and RoundRectShape.
The ShapeDrawable class is an extension of Drawable, so it can be used just like any other Drawable object. When drawing in a ShapeDrawable - remember to set the color and the boundaries of the object. If the color is not specified - black will be used by default. If the boundaries are not set - the drawing will not be visible.
Firstly, lets see how to draw lines with this. There isnt a separate class for displaying lines, but theres RectShape, which can work as lines too if we make them thing enough.
Example:
ShapeDrawable shape = new ShapeDrawable(new RectShape());
shape.setIntrinsicHeight(2);
shape.setIntrinsicWidth(200);
shape.getPaint().setColor(Color.RED);
An oval is drawn similarly to a rectangle. Simply set the width and height:
ShapeDrawable shape = new ShapeDrawable(new OvalShape());
shape.setIntrinsicHeight(100);
shape.setIntrinsicWidth(200);
shape.getPaint().setColor(Color.RED);
Drawing rounded rectangles is a little bit more complex, but not hard at all. The RoundRectShape constructor has 3 parameters - outerRadii, inset and innerRadii.
The outerRadii value is an array of float values that represent the radii of each corner. Each corner has 2 radii, so there are 8 values in total. The first 2 values are the radii of the top left corner, each next 2 correspond to the next corner clockwise. If you dont want rounded corners, pass null.
The inset value is a RectF class object, which represents the distance between the inner rectangle and the outer one. The constructor of the RectF class has 4 parameters - pairs of coordinates (x and y) of top left corner and bottom right corner of the inner rectangle. If theres no inner rectangle, pass null.
The innerRadii value is an array of radii for the corners of the inner rectangle. Works the same way as outerRadii.
A simple example:
float[] outR = new float[] {6, 6, 6, 6, 6, 6, 6, 6};
RectF rectF = nwe RectF(8, 8, 8, 8);
float[] inR = new float[] {6, 6, 6, 6, 6, 6, 6, 6};
ShapeDrawable shape = new ShapeDrawable(new RoundRectShape(outR, rectF, inR));
shape.setIntrinsicHeight(100);
shape.setIntrinsicWidth(200);
shape.getPaint().setColor(Color.RED);
Thats all for today. Next time well look at more shapes to draw.
Thanks for reading!
Subscribe to:
Posts (Atom)