Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

Android: is using setContentView multiple times bad while changing layouts?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's take a look at the Android Documents:

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

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: 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. Each band follows a specific layout. There is only 1, or maybe a few, possible layouts.
  2. When the Band activity starts, the appropriate layout is chosen, and populated, knowing what's in there.

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...