Android高仿微信(一)——如何消除启动时的白屏

时间:2022-08-20 21:47:45

默认情况下,APP启动时会先把屏幕刷成白色,然后才绘制第一个Activity中的View,这两个步骤之间的延迟会造成启动后先看到白屏(时间大概为1秒左右)。时间不长,但是我们也看到,一般的APP时不存在这个现象的,那么这个现象如何消除呢?

从网上得到了一些解决方案,主要的两种方式包括:在AppTheme中将“android:windowBackground”属性设置为背景图片;或者,将"android:windowIsTranslucent"设置为true。

在“高仿微信”这个项目中实验时,为了延长启动图片的时间,添加了一个StartActivity(里面有一个ImageView显示启动图片),启动时启动StartActivity,定时3秒后,跳转到MainActivity。

用第一种方式,由于图片的放大比例不一致,导致白屏与StartActivity切换时背景出现变形。

为了避免上述的缺点,采用第二种方法,问题得到完美解决(真机测试无异)。

1、styles.xml中的设置

     <!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.NoActionBar">
<item name="android:windowIsTranslucent">true</item>
</style>

2、StartActivity

activity_layout.xml:

注意,这里用了ImageView来显示背景图片,并且设置scaleType属性为"centerCrop",这样得到的效果是最好的。

也可以直接设置RelativeLayout的background属性,但是这样,图片会有点变形,可能是因为图片和真机屏幕的大小不完全匹配。

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="tina.myweixin2.StartActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/appstart"
android:scaleType="centerCrop"/> </RelativeLayout>

StartActivity.java:

这里,用了Timer来实现定时的效果。

 import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.util.Timer;
import java.util.TimerTask; public class StartActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start); Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
startActivity(new Intent(StartActivity.this,MainActivity.class));
StartActivity.this.finish();
}
},1000);
}
}