开发者

setContentView(R.Layout.main) vs startActivity(intent), which is more common?

Please tell me the difference between using startActivity(intent) and setContentView(R.Layout.main)

Which is more preferable and which should be used in which conditions?

I think when we like to perfo开发者_运维问答rm any action we use startActivity(intent) and just to move in different page we use setContentView(R.Layout.main)


If you use startActivity, in the new Activity's onCreate, you will also set the contentView(). 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. By using setContentView, you have to either manually configure the backbutton to go back to your previous layout...

Depending on the type of application, you have to determine which is best for you. For example, to chrome-to-phone source code, shows that google uses setContentView for the complete setup phase of the app. It is faster, and they put back-buttons on the bottom of the screen to go back. Pressing the physical back-button will stop the Activity. Using this approach, they use one activity for multiple screens to gather all info needed to complete the setup.

Once the setup is complete, Google switches to the startActivity methods, to perform different actions. Here, the app uses different activities for the different tasks the users can do. Each activity is kind of a stand-alone activity, with the back button allowing for quickly switching between them.

Hope this points you in the right direction


startActivity(intent) as name suggests starts the new activity. Now that activity uses setContentView(xml); to set xml layout to that activity. Now the question is how the first activity gets start cause we dont call startActivity(intent) for first activity.

The answer for this is in your manifest file. Your Launcher activity in manifest first gets called and it set the layout view as specified in respective jave files setContentView(R.layout.main);


They are very different, but based on your question, I have assumed you are trying to accomplish the same thing with both of them and it seems possible. What you should consider however is that setContentView(R.Layout.main), will un-register previous listeners that were set in that contentView if you moved back and forth, startActivity(intent) would be more preferred if you have listeners active and wanted somewhat an interactive experience. There are other better approaches that would depend on what you are trying to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜