Android:在更改布局时是否多次使用 setContentView? [英] Android: is using setContentView multiple times bad while changing layouts?

查看:29
本文介绍了Android:在更改布局时是否多次使用 setContentView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否在更改布局时多次使用 setContentView?

is using setContentView multiple times bad while changing layouts?

有些人说这很糟糕,但他们从不说为什么.

Some people say that it's bad and they never say why.

还有其他可以使用按钮更改布局的方法吗?

and is there some other thing to change layout using button?

推荐答案

我们来看看Android 文档:

将活动内容设置为显式视图.此视图直接放置在活动的视图层次结构中.

Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy.

因此,setContentView 将覆盖布局,并将其替换为新的布局.通常,您只想在 onCreate 中执行此操作一次.从理论上讲,您可以做得更多,但这涉及重新绘制整个布局,这可能需要一些时间.有几种选择,具体取决于您想要什么:

So, setContentView will overwrite the layout, and replace it with a new one. Usually, you only want to do this once in onCreate. Theoretically, you could do it more, but it involves re-drawing the entire layout, and this could take some time. There are a few alternatives, depending on exactly what you want:

  1. ViewAnimator:这对于显示快速动画很有用,如果您想快速连续多次更改视图.
  2. Fragments - 无需重新绘制整个视图,您可以切换出碎片.每个片段都是一种迷你活动,总体而言,这会更好地包含代码.
  3. 传递意图参数- 将信息传递给活动以帮助它设置.第一个活动将信息传递给共同的第二个活动,后者知道如何根据从第一个活动收到的信息进行设置.
  1. ViewAnimator: This is useful for showing a quick animation, if you want to change the view multiple times in quick succession.
  2. Fragments- Instead of re-drawing the entire view, you can switch out fragments. Each fragment is a kind of mini activity, and overall this will contain the code much better.
  3. Pass Intent Arguments- Pass information to an activity to help it set up. The first activity passes information to a common second activity, which knows how to set itself up based off of the information it receives from the first activity.

至于您的具体应用,我会这样做:

As for your specific application, here's what I would do:

  1. 每个乐队都遵循特定的布局.只有 1 种或几种可能的布局.
  2. 当 Band 活动开始时,会选择并填充适当的布局,了解其中的内容.

Android SDK 展示了如何从一个活动到另一个.只需传递第二个活动需要的第一个活动的数据,使用如下所示:

The Android SDK shows how to pass data from one activity to another. Just pass the data that the second activity needs from the first, using something like this:

Intent intent=new Intent(...);
intent.putExtra("Album","Some Album")
startActivity(intent);

第二个活动将执行此操作:

The second activity will do this:

Intent intent=getIntent();
String albumName=intent.getExtraString("Album");
//Does something with albumName, maybe get a TextView and .setText()

这篇关于Android:在更改布局时是否多次使用 setContentView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆