简体   繁体   English

Android:切换布局或活动?

[英]Android: switch layouts or activities?

I can implement both variants - it's easy. 我可以实现两种变体-很简单。 But I'm interested: what approach is better? 但是我很感兴趣:哪种方法更好?

I mean if my application contains several screens I can make them as several layouts (XML-files) and switch using setContentView() . 我的意思是,如果我的应用程序包含多个屏幕,则可以将它们设置为多个布局(XML文件),然后使用setContentView()切换。 Or they can be several classes like MyActivity1 , MyActivity2 etc., and I will switch them using Intent class. 或者它们可以是MyActivity1MyActivity2等几个类,我将使用Intent类对其进行切换。

So I'm curious: what's the best practice? 所以我很好奇:最佳实践是什么?

Remember this as the Rule of Thumb: 记住这是经验法则:

It's better to have similar behaviors, under single Activity, but always prefer different Activities when behaviors differ. 最好在单个“活动”下具有相似的行为,但是当行为不同时,总是喜欢使用不同的“活动”。

If you are using several different screens, I would argue that fragments/activities would be a better solution. 如果您使用几个不同的屏幕,我会认为片段/活动将是更好的解决方案。 Not only did Android include this to help people with multiple activities, but it also makes your code much cleaner. Android不仅包括此功能以帮助人们进行多种活动,而且还使您的代码更简洁。 Mitra sums it up quite well. Mitra很好地总结了这一点。

I think before Fragments using setContentView() was a handy way to move between sibling "screens" when you did not want the Back button to change the screen. 我想在Fragments之前使用setContentView()是一种便捷的方法,当您不希望“后退”按钮更改屏幕时,可以在同级“屏幕”之间移动。 On the other hand, Activities launched via Intents will be poped off the stack with the Back button. 另一方面,通过“意图”启动的“活动”将使用“后退”按钮从堆栈中弹出。


To be clear, note that within Activity B, you can use setContentView to change layouts, and the Back button takes you back to Activuty A. 为了清楚起见,请注意,在活动B中,您可以使用setContentView更改布局,然后单击“后退”按钮将您带回到ActivutyA。

ActivityA

  |
  |
  |
  V

ActivityB,Layout1  <---> ActivityB,Layout2  <---> ActivityB,Layout3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM