效果:
此gif来自https://www.jianshu.com/p/33a798ac3298,不知道怎么录gif,就在网上找了一个别人的
1.新建一个Activity,命名为SplashActivity(当然名字可以随便),并将其设置为最先启动的Activity,即在AndroidManifest.xml中:
2.为其添加布局<?xml version="1.0" encoding="utf-8"?>
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.splashlx2.SplashActivity">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/splashimg"
android:scaleType="centerCrop"/>
3.在styles.xml中为SplashActivity添加自定义style,来解决应用打开时的白屏问题。
如图打开应用后有一段时间是白屏。如下操作可以解决此问题。
@drawable/splashimg//windowBackground设置为闪屏页要显示的图片。
@color/colorPrimary
@color/colorPrimaryDark
@color/colorAccent
4.在AndroidManifest.xml中将SplashActivity的theme设置为自定义的style。
5.在SplashActivity的代码中,在setContentView()前使用如下代码将SplashActivity设置为全屏。getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);然后使用如下代码来让闪屏页延时几秒钟(3000表示延迟的毫秒数),在run()中启动闪屏页之后要显示的Activity。startActivity()之后要添加SplashActivity.this.finish();这行代码,这样在SplashActivity之后的Activity按Back键就不会返回到闪屏页了。
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent1=new Intent(SplashActivity.this,MainActivity.class);
startActivity(intent1);
SplashActivity.this.finish();
}
},3000);
6.完整代码如下:完整代码如下:
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
/*activity继承AppCompatActivity使用getSupportActionBar().hide()来隐藏ActionBar,且
* 必须写在 setContentView后面,如果在styles.xml中设置了NoTitleBar就不用写。*/
/*getSupportActionBar().hide();*/
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent1=new Intent(SplashActivity.this,MainActivity.class);
startActivity(intent1);
SplashActivity.this.finish();
}
},3000);//3000表示延迟的毫秒数。
}
}