In my main activity is there a difference between loading a view as an intent or using setContentView?
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Or is this better? Not sure what the differnce is if they both load the layout file?
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = new Intent(MainActivity.this, CalculateTip.class);
startActivity(i);
}
}
SetContentView is used to fill the window with the UI provided from layout file incase of setContentView(R. layout. somae_file). Here layoutfile is inflated to view and added to the Activity context(Window).
So, with respect to time, setContentView alone is faster, since it doesn't start a new activity. Hence, your app will show the new screen faster... On the other hand, if you call startActivity, this activity is put on the stack, so you can go back by pressing the back button.
onCreate() method calls the setContentView() method to set the view corresponding to the activity. By default in any android application, setContentView point to activity_main. xml file, which is the layout file corresponding to MainActivity.
Q 9 – What is the purpose of super. onCreate() in android? The super. onCreate() will create the graphical window for subclasses and place at onCreate() method.
The difference is that with the first way you are not creating a new Activity, you are simply changing the layout of the current Activity. With the second way, you are creating a new Activity.
The practical difference will be that with the second way after you've started the new Activity you can press the back button and be taken back to the first. Whereas with the first way once the second layout is shown if you pressed the back button it would finish the current (only) activity which would put the user back to whatever they were doing before entering your application.
Which is "better" is impossible to determine without knowing more about what specifically you are trying to accomplish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With