My Android application is supposed to show a splash screen consisting solely of an ImageView while it is still loading. The ImageView should just display a local resource. Here is my code:
public class GameActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView splash = new ImageView(this);
splash.setImageResource(R.drawable.splashImage);
RelativeLayout layout = new RelativeLayout(this);
layout.setId(R.id.gameView);
uilayout addView(splash, someLayoutParams);
setContentView(layout, someOtherLayoutParams);
// with a return-statement, the image would be displayed now
final GameActivity activity = this;
this.findViewById(R.id.gameView).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// this is supposed to wait until the image has been fully loaded
activity.init(this);
}
});
}
public void init(ViewTreeObserver.OnGlobalLayoutListener listener) {
try {
findViewById(R.id.gameView).getViewTreeObserver().removeOnGlobalLayoutListener(listener);
} catch (NoSuchMethodError x) {
findViewById(R.id.gameView).getViewTreeObserver().removeGlobalOnLayoutListener(listener);
} finally {
LinearLayout layout = new LinearLayout(this);
// lots of stuff
setContentView(layout);
}
}
}
My problem is that as soon as I execute code after the first call for setContentView(), my splash screen image is not displayed and the new layout immediately shows up. I would appreciate any help on how to solve this problem.
EDIT: It was my fault to assume that my code was the ideal solution for a splash screen. This tutorial really helped me out. My solution based on this tutorial:
@drawable/layer-list_splash:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@color/color_background"/>
<item>
<bitmap
android:gravity="center"
android:src="@drawable/sprite_splash"/>
</item>
</layer-list>
and my styles.xml:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/layers_splash</item>
</style>
</resources>
How about running the activity.init() after 2 secs to show the splash screen?
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
activity.init();
}
}, 2000)