The code below shows how to display an animated GIF image in your android activity.You can use it as a splashscreen of your application
activity_min.xml
Inside the drawables folder make sure that you have a .gif image named welcome.gif .
activity_min.xml
<?xml
version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ACC437"
android:textStyle="bold"
android:text="WelCome
To This Blog"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<com.example.animation.AnimationView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
MainActivity.java
import
android.app.Activity;
import
android.os.Bundle;
public
class MainActivity extends
Activity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The View Class
AnimationView.java
import
java.io.ByteArrayOutputStream;
import
java.io.InputStream;
import
android.content.Context;
import
android.graphics.Canvas;
import
android.graphics.Movie;
import
android.util.AttributeSet;
import
android.util.Log;
import
android.view.View;
public
class
AnimationView extends
View {
private
Movie mMovie;
private
long
mMovieStart;
private
static
final
boolean
DECODE_STREAM
= true;
private
static
byte[]
streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[]
buffer = new
byte[1024];
int
len;
try
{
while
((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
}
catch
(java.io.IOException e) {
}
return
os.toByteArray();
}
public
AnimationView(Context context,AttributeSet attrs) {
super(context,attrs);
setFocusable(true);
// YOUR GIF IMAGE Here
java.io.InputStream is;
is =
context.getResources() .openRawResource(R.drawable.welcome);
if
(DECODE_STREAM)
{
mMovie
= Movie.decodeStream(is);
}
else
{
byte[]
array = streamToBytes(is);
mMovie
= Movie.decodeByteArray(array,
0, array.length);
}
}
@Override
public
void
onDraw(Canvas canvas) {
long
now = android.os.SystemClock.uptimeMillis();
if
(mMovieStart
== 0) { // first time
mMovieStart
= now;
}
if
(mMovie !=
null)
{
int
dur = mMovie.duration();
if
(dur == 0) {
dur = 3000;
}
int
relTime = (int)
((now - mMovieStart)
% dur);
Log.d("",
"real time :: "
+relTime);
mMovie.setTime(relTime);
mMovie.draw(canvas,
getWidth() - 200, getHeight()-200);
invalidate();
}
}
}
screenshotInside the drawables folder make sure that you have a .gif image named welcome.gif .
0 comments:
Post a Comment