I want to create animated splash screen using gif image. I have used Glide library because it supports gif images.
I have done following things to achieve this:
Created splash.xml with an imageview in it.
<ImageView
android:id="#+id/iv_gif_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Inside SplashActivity.java
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ImageView ivImage = (ImageView) findViewById(R.id.iv_gif_view);
Glide.with(this).load(R.drawable.splash_xxhdpi_2)
.asGif().into(ivImage);
}
But when I run the application screen goes black nothing appears on the screen. I'm using Glide compile 'com.github.bumptech.glide:glide:3.6.1'
You can try this way
public class GifImageView extends View {
private InputStream mInputStream;
private Movie mMovie;
private int mWidth, mHeight;
private long mStart;
private Context mContext;
public GifImageView(Context context) {
super(context);
this.mContext = context;
}
public GifImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public GifImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
if (attrs.getAttributeName(1).equals("background")) {
int id = Integer.parseInt(attrs.getAttributeValue(1).substring(1));
setGifImageResource(id);
}
}
private void init() {
setFocusable(true);
mMovie = Movie.decodeStream(mInputStream);
mWidth = mMovie.width();
mHeight = mMovie.height();
requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(mWidth, mHeight);
}
#Override
protected void onDraw(Canvas canvas) {
long now = SystemClock.uptimeMillis();
if (mStart == 0) {
mStart = now;
}
if (mMovie != null) {
int duration = mMovie.duration();
if (duration == 0) {
duration = 1000;
}
int relTime = (int) ((now - mStart) % duration);
mMovie.setTime(relTime);
mMovie.draw(canvas, 0, 0);
invalidate();
}
}
public void setGifImageResource(int id) {
mInputStream = mContext.getResources().openRawResource(id);
init();
}
public void setGifImageUri(Uri uri) {
try {
mInputStream = mContext.getContentResolver().openInputStream(uri);
init();
} catch (FileNotFoundException e) {
Log.e("GIfImageView", "File not found");
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GifImageView gifImageView = (GifImageView) findViewById(R.id.GifImageView);
gifImageView.setGifImageResource(R.drawable.android);
}
}
http://www.mavengang.com/2016/05/02/gif-animation-android/
http://www.geeks.gallery/how-to-display-the-animated-gif-image-in-android/
Android does not support GIF so avoid using it since it is memory consuming. Glide is nice image caching library and luckily it supports gif images.
I'm sharing alternate and efficient way to achieve animated splash screen.
Create splash.xml as usual with an image view.
Take out each frame from your gif image. I have used splash_hdpi_1, splash_hdpi_2, splash_hdpi_3 for example.
create splash_gif_animation.xml in drawable with below code
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false" >
<item
android:drawable="#drawable/splash_hdpi_1"
android:duration="150"/>
<item
android:drawable="#drawable/splash_hdpi_2"
android:duration="150"/>
<item
android:drawable="#drawable/splash_hdpi_3"
android:duration="150"/>
</animation-list>
In your SplashActivity.java put below code
ImageView ivImage = (ImageView) findViewById(R.id.your_image_view);
ivImage.setBackgroundResource(R.drawable.splash_gif_animation);
AnimationDrawable splashAnimation = (AnimationDrawable) ivImage.getBackground();
splashAnimation.start();
You are done:)
Try this:
ImageView ivImage= (ImageView) findViewById(R.id.iv_gif_view);
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(ivImage);
Glide.with(this)
.load(R.drawable.splash_xxhdpi_2)
.into(imageViewTarget);
Related
I have an Android application that shows a screen with an animated GIF image while it's loading. The image gets displayed forever or shown only a blank screen if I use a timer. I just want to show it for 5 seconds. How can I displaying the GIF only by 5 seconds?
With this code the image gets displayed forever:
public class MainActivity extends AppCompatActivity {
public GifImageView gifImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gifImageView = (GifImageView) findViewById(R.id.GifImageView);
gifImageView.setGifImageResource(R.drawable.gif2);
}
}
With this code the gif image is not shown only a blank screen is shown but after 5 seconds the application closes:
public class MainActivity extends AppCompatActivity {
public GifImageView gifImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gifImageView = (GifImageView) findViewById(R.id.GifImageView);
startCountDownTimer();
}
private void startCountDownTimer() {
new CountDownTimer( 5000, 5000 ) {
public void onTick(long millisUntilFinished) {
gifImageView.setGifImageResource(R.drawable.gif2);
}
public void onFinish() {
finish();
}
}.start();
}
}
Here is the GifImageView code:
public class GifImageView extends View {
private InputStream mInputStream;
private Movie mMovie;
private int mWidth, mHeight;
private long mStart;
private Context mContext;
public GifImageView(Context context) {
super(context);
this.mContext = context;
}
public GifImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public GifImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
if (attrs.getAttributeName(1).equals("background")) {
int id = Integer.parseInt(attrs.getAttributeValue(1).substring(1));
setGifImageResource(id);
}
}
private void init() {
setFocusable(true);
mMovie = Movie.decodeStream(mInputStream);
mWidth = mMovie.width();
mHeight = mMovie.height();
requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(mWidth, mHeight);
}
#Override
protected void onDraw(Canvas canvas) {
long now = SystemClock.uptimeMillis();
if (mStart == 0) {
mStart = now;
}
if (mMovie != null) {
int duration = mMovie.duration();
if (duration == 0) {
duration = 1000;
}
int relTime = (int) ((now - mStart) % duration);
mMovie.setTime(relTime);
mMovie.draw(canvas, 0, 0);
invalidate();
}
}
public void setGifImageResource(int id) {
mInputStream = mContext.getResources().openRawResource(id);
init();
}
You can use a CountDownTimer, set the time to 5000 milliseconds. When onFinish() is called you can stop displaying the GIF. Use this code:
new CountDownTimer(5000, 5000) {
public void onTick(long millisUntilFinished) {
// You don't need to use this.
}
public void onFinish() {
// Put the code to stop the GIF here.
}
}.start();
You can read more about CountDownTimers in the documentation.
With what #AmeerTaweel told, you can use a CountDownTimer. Another simple approach would be to use a Handler for that in the onCreate() method like this:
new Handle().postDelayed(new Runnable(
#Override
public void run() {
ImageView.setVisibility(View.GONE); //Or the GIF View
}
), 5000); //5 sec
I make gif Files animated then, I put this one in the Application's imageview.
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(character6);
Glide.with(this).load(R.raw.company_normal8).into(imageViewTarget);
here's code and I have no problem with apply this one.
But I have serious issue that The image have afterimage.
I made this gif file with photoshop and It have 2 frame
There's A frame and B frame.
But at android app,
A -> B -> A -> B (this is the normal one)
But My app
A -> A+B -> A -> A+b (like this afterimage)
You can use asGif
Glide.with(context)
.load(imgUrl)
.asGif()
.placeholder(R.drawable.img)
.crossFade()
.into(imageView);
OR
Try this if Glide is not working for you,Its working for me
public class GIFView extends View{
Movie movie;
long moviestart;
public GIFView(Context context) throws IOException {
super(context);
}
public GIFView(Context context, AttributeSet attrs) throws IOException{
super(context, attrs);
}
public GIFView(Context context, AttributeSet attrs, int defStyle) throws IOException {
super(context, attrs, defStyle);
}
public void loadGIFResource(Context context, int id)
{
//turn off hardware acceleration
this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
InputStream is=context.getResources().openRawResource(id);
movie = Movie.decodeStream(is);
}
public void loadGIFAsset(Context context, String filename)
{
InputStream is;
try {
is = context.getResources().getAssets().open(filename);
movie = Movie.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (movie == null) {
return;
}
long now=android.os.SystemClock.uptimeMillis();
if (moviestart == 0) moviestart = now;
int relTime;
relTime = (int)((now - moviestart) % movie.duration());
movie.setTime(relTime);
movie.draw(canvas,10,10);
this.invalidate();
}
}
XML
<yourpackagename.GIFView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:layout_marginTop="110dp"
android:src="#drawable/yourgifimage"/>
To set the image
imagevw.loadGIFResource(this, R.drawable.yourgifimage);
I'm using this library as a guide to display a 'gif' file. When using the saved gif in drawableit display correctly the gif I call it like this
<pl.droidsonroids.gif.GifImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgView1"
android:src="#drawable/gifFile"
/>
but when removing the src and tried like initializing the GifImageView in the Activity like this
GifImageView gifFromFile = (GifImageView) findViewById(R.id.imgView1);
gifFromFile.setImageBitmap(Utils.getBitmapImagefromStorage(context, imageHome));
Where getBitmapImagefromStorage get the path and imageHome gets the filename the gif file doesn't play its only display like an image. It was said that If given drawable is not a GIF then mentioned Views work like plain ImageView and ImageButton. But the file I'm providing is a gif.I'm wondering if I'm using it correctly.
Also the file can be png or gif so I needed to support the two.
GifTextView gifImageView;
In onCreate
gifImageView = (GifTextView) findViewById(R.id.imageView);
Call this method in onCreate
public void playGif(){
Animation fadeout = new AlphaAnimation(1.f, 1.f);
fadeout.setDuration(2500); // You can modify the duration here
fadeout.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
gifImageView.setBackgroundResource(R.drawable.gif_image);//your gif file
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
});
gifImageView.startAnimation(fadeout);
}
In your layout file
<pl.droidsonroids.gif.GifTextView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:scaleType="fitXY"
android:layout_height="fill_parent"
/>
Try this way to work with GIF in your app
public class PlayGifView extends View{
private static final int DEFAULT_MOVIEW_DURATION = 1000;
private int mMovieResourceId;
private Movie mMovie;
private long mMovieStart = 0;
private int mCurrentAnimationTime = 0;
#SuppressLint("NewApi")
public PlayGifView(Context context, AttributeSet attrs) {
super(context, attrs);
/**
* Starting from HONEYCOMB have to turn off HardWare acceleration to draw
* Movie on Canvas.
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
public void setImageResource(int mvId){
this.mMovieResourceId = mvId;
mMovie = Movie.decodeStream(getResources().openRawResource(mMovieResourceId));
requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if(mMovie != null){
setMeasuredDimension(mMovie.width(), mMovie.height());
}else{
setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight());
}
}
#Override
protected void onDraw(Canvas canvas) {
if (mMovie != null){
updateAnimtionTime();
drawGif(canvas);
invalidate();
}else{
drawGif(canvas);
}
}
private void updateAnimtionTime() {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) {
mMovieStart = now;
}
int dur = mMovie.duration();
if (dur == 0) {
dur = DEFAULT_MOVIEW_DURATION;
}
mCurrentAnimationTime = (int) ((now - mMovieStart) % dur);
}
private void drawGif(Canvas canvas) {
mMovie.setTime(mCurrentAnimationTime);
mMovie.draw(canvas, 0, 0);
canvas.restore();
}
}
in your activity class
PlayGifView pGif = (PlayGifView) findViewById(R.id.viewGif);
pGif.setImageResource(R.drawable.yourgifimage);
then in your XML
<YourPackageName.PlayGifView
android:id="#+id/viewGif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
I tried using GifDrawable
File gifFile = new File(context.getExternalFilesDir(null)
.getAbsolutePath(), imageHome);
GifDrawable gifFromPath = new GifDrawable(gifFile);
And then instead of using setImageBitmap I use setImageDrawable
GifImageView gifImageView = (GifImageView) findViewById(R.id.textViewDealFinder);
gifImageView.setImageDrawable(gifFromPath);
Custom progress bar with dots applied animation and given the traversing visual effect. Posting this code here because it can help you to understand and implement new designs too keeping this as reference. Hope this helps you people.
MainActivity.java :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_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="match_parent"
android:layout_height="match_parent"
android:id="#+id/rect"
android:gravity="center"
>
<com.example.horizontal.canvaslearn.HorizontalDottedProgress
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></com.example.horizontal.canvaslearn.HorizontalDottedProgress>
</LinearLayout>
HorizontalDottedProgress.java :
This is a custom class to create dots with animation applied.
public class HorizontalDottedProgress extends View{
//actual dot radius
private int mDotRadius = 5;
//Bounced Dot Radius
private int mBounceDotRadius = 8;
//to get identified in which position dot has to bounce
private int mDotPosition;
//specify how many dots you need in a progressbar
private int mDotAmount = 10;
public HorizontalDottedProgress(Context context) {
super(context);
}
public HorizontalDottedProgress(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HorizontalDottedProgress(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//Method to draw your customized dot on the canvas
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
//set the color for the dot that you want to draw
paint.setColor(Color.parseColor("#fd583f"));
//function to create dot
createDot(canvas,paint);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
//Animation called when attaching to the window, i.e to your screen
startAnimation();
}
private void createDot(Canvas canvas, Paint paint) {
//here i have setted progress bar with 10 dots , so repeat and wnen i = mDotPosition then increase the radius of dot i.e mBounceDotRadius
for(int i = 0; i < mDotAmount; i++ ){
if(i == mDotPosition){
canvas.drawCircle(10+(i*20), mBounceDotRadius, mBounceDotRadius, paint);
}else {
canvas.drawCircle(10+(i*20), mBounceDotRadius, mDotRadius, paint);
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width;
int height;
//calculate the view width
int calculatedWidth = (20*9);
width = calculatedWidth;
height = (mBounceDotRadius*2);
//MUST CALL THIS
setMeasuredDimension(width, height);
}
private void startAnimation() {
BounceAnimation bounceAnimation = new BounceAnimation();
bounceAnimation.setDuration(100);
bounceAnimation.setRepeatCount(Animation.INFINITE);
bounceAnimation.setInterpolator(new LinearInterpolator());
bounceAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
mDotPosition++;
//when mDotPosition == mDotAmount , then start again applying animation from 0th positon , i.e mDotPosition = 0;
if (mDotPosition == mDotAmount) {
mDotPosition = 0;
}
Log.d("INFOMETHOD","----On Animation Repeat----");
}
});
startAnimation(bounceAnimation);
}
private class BounceAnimation extends Animation {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
//call invalidate to redraw your view againg.
invalidate();
}
}
}
snap shot:
I have used the class HorizontalDottedProgress - this is a real solution, but it sometimes draws very small dots. Also this widget doesn't react on setVisibility(Visibility.GONE) and can't be hidden after showing.
That's why I slightly modified (and renamed for myself) this class. Dot sizes and distances are calculated using screen density now. Function onDraw() checks isShown() before drawing.
Then, I've added a possibility to specify some properties (such as color, count and timeout) in layout. In my project I use them in the following manner:
<my.domain.tools.ToolDotProgress
android:id="#+id/dots_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:color="#color/colorAccent"
app:count="5"
app:timeout="300" />
To declare these properties I've added to file res/values/attrs.xml the following code:
<declare-styleable name="ToolDotProgress">
<attr name="color" format="color" />
<attr name="count" format="integer" />
<attr name="timeout" format="integer" />
</declare-styleable>
For more information read the manual: https://developer.android.com/training/custom-views/create-view.html
Here is my variant of this class:
public class ToolDotProgress extends View {
// distance between neighbour dot centres
private int mDotStep = 20;
// actual dot radius
private int mDotRadius = 5;
// Bounced Dot Radius
private int mBigDotRadius = 8;
// to get identified in which position dot has to bounce
private int mDotPosition;
// specify how many dots you need in a progressbar
private static final int MIN_COUNT = 1;
private static final int DEF_COUNT = 10;
private static final int MAX_COUNT = 100;
private int mDotCount = DEF_COUNT;
private static final int MIN_TIMEOUT = 100;
private static final int DEF_TIMEOUT = 500;
private static final int MAX_TIMEOUT = 3000;
private int mTimeout = DEF_TIMEOUT;
private int mDotColor = Color.parseColor("#fd583f");
public ToolDotProgress(Context context) {
super(context);
initDotSize();
}
public ToolDotProgress(Context context, AttributeSet attrs) {
super(context, attrs);
initDotSize();
applyAttrs(context, attrs);
}
public ToolDotProgress(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initDotSize();
applyAttrs(context, attrs);
}
private void initDotSize() {
final float scale = getResources().getDisplayMetrics().density;
mDotStep = (int)(mDotStep * scale);
mDotRadius = (int)(mDotRadius * scale);
mBigDotRadius = (int)(mBigDotRadius * scale);
}
private void applyAttrs(Context context, AttributeSet attrs) {
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs, R.styleable.ToolDotProgress, 0, 0);
try {
mDotColor = a.getColor(R.styleable.ToolDotProgress_color, mDotColor);
mDotCount = a.getInteger(R.styleable.ToolDotProgress_count, mDotCount);
mDotCount = Math.min(Math.max(mDotCount, MIN_COUNT), MAX_COUNT);
mTimeout = a.getInteger(R.styleable.ToolDotProgress_timeout, mTimeout);
mTimeout = Math.min(Math.max(mTimeout, MIN_TIMEOUT), MAX_TIMEOUT);
} finally {
a.recycle();
}
}
//Method to draw your customized dot on the canvas
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isShown()) {
Paint paint = new Paint();
paint.setColor(mDotColor);
createDots(canvas, paint);
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
startAnimation();
}
private void createDots(Canvas canvas, Paint paint) {
for (int i = 0; i < mDotCount; i++ ) {
int radius = (i == mDotPosition) ? mBigDotRadius : mDotRadius;
canvas.drawCircle(mDotStep / 2 + (i * mDotStep), mBigDotRadius, radius, paint);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// MUST CALL THIS
setMeasuredDimension(mDotStep * mDotCount, mBigDotRadius * 2);
}
private void startAnimation() {
BounceAnimation bounceAnimation = new BounceAnimation();
bounceAnimation.setDuration(mTimeout);
bounceAnimation.setRepeatCount(Animation.INFINITE);
bounceAnimation.setInterpolator(new LinearInterpolator());
bounceAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
if (++mDotPosition >= mDotCount) {
mDotPosition = 0;
}
}
});
startAnimation(bounceAnimation);
}
private class BounceAnimation extends Animation {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
// call invalidate to redraw your view again
invalidate();
}
}
}
Change onDraw() method to:
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
if(isShown){
Paint paint = new Paint();
//set the color for the dot that you want to draw
paint.setColor(Color.parseColor("#fd583f"));
//function to create dot
createDot(canvas,paint);
}
}
SOLVED: Solution below as answer.
I have a custom view with a TransitionDrawable and when I draw it in the onDraw() method it scales automatically to fill the whole parent layout, even when it's set in the xml to wrap_content. The picture is in mdpi and hdpi and my testing device (samsung galaxy s) I think it's no more than hdpi.
package com.adyrsoft.pronunciationtrainer;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.TransitionDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class RecordButton extends View {
private static final String TAG = "RecordButton";
private TransitionDrawable mDrawable;
private boolean mActivated;
private OnClickListener mOnClickListenerInternal = new OnClickListener() {
#Override
public void onClick(View v) {
toggleState();
if(mOnClickListener != null) {
mOnClickListener.onClick(v);
}
}
};
private OnClickListener mOnClickListener = null;
public RecordButton(Context context) {
super(context);
init();
}
public RecordButton(Context context, AttributeSet attrib) {
super(context, attrib);
init();
}
public RecordButton(Context context, AttributeSet attrib, int defStyle) {
super(context, attrib, defStyle);
init();
}
public void setState(boolean activated) {
mActivated = activated;
if(mActivated){
mDrawable.startTransition(300);
}
else {
mDrawable.reverseTransition(300);
}
}
public void toggleState() {
if(mActivated) {
setState(false);
}
else {
setState(true);
}
}
#SuppressWarnings("deprecation")
private void init() {
mActivated = false;
mDrawable = (TransitionDrawable) getResources().getDrawable(R.drawable.btnrecord);
Log.d(TAG, "Drawable intrinsic width and height are: " +
Integer.toString(mDrawable.getIntrinsicWidth()) + " " +
Integer.toString(mDrawable.getIntrinsicHeight()));
mDrawable.setBounds(0,0,mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
Log.d(TAG, "The bounds for the button are: "+mDrawable.getBounds().flattenToString());
super.setBackgroundDrawable(mDrawable);
setClickable(true);
super.setOnClickListener(mOnClickListenerInternal);
invalidate();
}
public void setOnClickListener(View.OnClickListener listener) {
mOnClickListener = listener;
}
protected void onDraw (Canvas canvas) {
super.onDraw(canvas);
}
}
What am I doing wrong?
Thanks.
After hours trying to understand how I should use the drawables in a custom view in order to be displayed in its original size, I've figured out how to do it.
First a few things that I didn't know but are a must is:
The background drawable should be left to the parent class to be
drawn when using View as the parent. If not, the TransitionDrawable can't be seen fading between pictures.
Only if I am going to draw on the background drawable I should override onDraw() and do the drawing there.
And the last but not less important is that I should override onMeasure() to specify the size of the view. If I don't do it, it will fill all the free space in the parent layout, as it was happening to me.
I've passed the TransitionDrawable to the parent class with setBackgroundDrawable() and since I wasn't drawing in the background drawable, I've removed the onDraw() method. Also I've implemented onMeasure() with a quick and dirty solution specifying the size of the picture I am drawing.
This is the final result:
public class RecordButton extends View {
private static final String TAG = "RecordButton";
private static final int DESIRED_WIDTH = 180;
private static final int DESIRED_HEIGHT = 66;
private TransitionDrawable mDrawable;
private Rect mViewRect;
private boolean mActivated;
private OnClickListener mOnClickListenerInternal = new OnClickListener() {
#Override
public void onClick(View v) {
toggleState();
if(mOnClickListener != null) {
mOnClickListener.onClick(v);
}
}
};
private OnClickListener mOnClickListener = null;
public RecordButton(Context context) {
this(context, null, 0);
}
public RecordButton(Context context, AttributeSet attrib) {
this(context, attrib, 0);
}
public RecordButton(Context context, AttributeSet attrib, int defStyle) {
super(context, attrib, defStyle);
init();
}
public void setState(boolean activated) {
mActivated = activated;
if(mActivated){
mDrawable.startTransition(300);
}
else {
mDrawable.reverseTransition(300);
}
}
public void toggleState() {
if(mActivated) {
setState(false);
}
else {
setState(true);
}
}
#SuppressWarnings("deprecation")
private void init() {
mActivated = false;
mDrawable = (TransitionDrawable) getResources().getDrawable(R.drawable.btnrecord);
setBackgroundDrawable(mDrawable);
setClickable(true);
super.setOnClickListener(mOnClickListenerInternal);
invalidate();
}
public void setOnClickListener(View.OnClickListener listener) {
mOnClickListener = listener;
}
#Override
protected void onMeasure(int m, int n) {
setMeasuredDimension(DESIRED_WIDTH, DESIRED_HEIGHT);
}
}