Android启动页面动图实现
主要方法
- 在欢迎界面布局中设定一个ImageView组件,大小为整个屏幕大小
- 利用图片加载框架Glide加载动图
Glide是google推荐的图片加载库,至今有专人维护
Glide导入
在gradle文件中添加依赖:dependencies { implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.github.bumptech.glide:glide:3.7.0' }
- Handler,sendEmptyMessageDelayed()函数,在指定的延迟之后安排指定的任务执行。
1.MainActivity
此处不再赘述
2.welcom.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/welocom_gif"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
</android.support.constraint.ConstraintLayout>
3.WelcomActivity
package com.example.ray.ultraray;
import android.os.Bundle;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
public class WelcomActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
handler.sendEmptyMessageDelayed(1,2000);
ImageView welcome_gif = (ImageView) findViewById(R.id.welocom_gif);
Glide.with(this).load(R.drawable.giphy2).into(welcome_gif);
}
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
if (message.what == 1){
Intent intent = new Intent(WelcomActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
return false;
}
});
}
备注:加载图片到ImageView方法:
Glide.with(context)
.load(url)
.into(imageView);
/*
with() :用于图片加载的生命周期,参数可以是Activity、Fragment等。如传入的是activity,则在activity销毁时将对相关图片资源进行回收。
load() :参数可以为String、Uri、File、资源ID等。
into() :参数可以是ImageView,Target、图片的宽高。
*/
这里我们加载了本地动图giphy2.gif到 ImageView welcome_gif组件:
ImageView welcome_gif = (ImageView) indViewById(R.id.welocom_gif);
Glide.with(this).load(R.drawable.giphy2).into(welcome_gif);
4.更改AndroidManifest.xml文件
原文件如下:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WelcomActivity">
更改为:
<activity android:name=".MainActivity">
</activity>
<activity android:name=".WelcomActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
至此,可以运行启动页面GIF