How to Pre-load MainActivity in SplashActivity so

2019-06-14 19:57发布

问题:

I have a working splash

public class MainSplash extends AppCompatActivity  {
private final int SPLASH_DISPLAY_LENGTH = 1000;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);


    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            Intent mainIntent = new Intent(MainSplash.this, MainMenu.class);
            MainSplash.this.startActivity(mainIntent);
            MainSplash.this.finish();
        }

    },   SPLASH_DISPLAY_LENGTH);
}
}

and I want to add few buttons like share, more etc

and wen I do that by removing handler and SPLASH_DISPLAY_LENGTH, and adding buttons to xml and handling clicks on them just like any other other activity and set a Start button to start MainActivity, the MainActivity starts in few seconds ( after 1, 2 seconds of loading).

But I want to handle the loading time of MainActivity in SplashActivity,

How can I do that?

Here is the example SplashActivity after adding buttons

public class MainSplash extends AppCompatActivity implements View.OnClickListener {
//private final int SPLASH_DISPLAY_LENGTH = 1000;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);

    Button btn1 = (Button) findViewById(R.id.button);
    Button btn2 = (Button) findViewById(R.id.button2);
    Button btn3 = (Button) findViewById(R.id.button3);
    Button btn4 = (Button) findViewById(R.id.button4);

    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);
    btn3.setOnClickListener(this);
    btn4.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.button4:
            Intent mainIntent = new Intent(this,MainMenu.class);
            startActivity(mainIntent);
            finish();
            break;
    }

}
}

回答1:

you can try adding delay in loading time of MainActivity by putting a handler inside onCLick



回答2:

well if anyone else having the same issue like when we load Mainactivity from SplashActivity we get a black screen for a second or two, which is the loading time for the MainActivity and it really doesn't look good.

To make it go away i just added a Fragment for splash Screen instead of SplashActivity and another fragment for Main interface.

This way Activity loads when app start so and transaction from splash fragment to main fragment takes no time :)

Hope it helps someone.