问题
I have a Table containing a number of images per row. The number of images per row is decided on the fly based on the image width and screen width. When I use the phone normally, images are spaced on the phone screen. When the phone orientation changes, all the images appear on the same row. Should I explicitly handle the orientation changes for this case?
// get the number of images per column based on the screen
// resolution
Display display = getWindowManager().getDefaultDisplay();
int screenWidth = display.getWidth();
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.emo_im_happy);
numberOfImagesPerRow = screenWidth / (drawable.getIntrinsicWidth() + 10);
int numberOfRows = (int) Math.ceil(numberOfEmotions
/ numberOfImagesPerRow);
回答1:
It depends when that code is run, but you generally don't need to do anything special.
When Android detects an orientation change, the system will re-create your Activity and it will get a chance to go through onCreate and re-layout and re-render everything according to the new configuration.
Using android android:configChanges
should be used with care and not be the first option you think of, since the system will do a better job at selecting appropriate resources for you after a configuration change (and you'll have to handle that code path for other forms of configuration change anyways).
See: http://developer.android.com/guide/topics/resources/runtime-changes.html
回答2:
Yes. One way is to put android:configChanges="orientation|keyboardHidden"
on your <activity>
in the AndroidManifest.xml file, and then override onConfigurationChanged
to detect the orientation change.
回答3:
If you want to persist the number of images displayed in one row you can use the GridView. In this way you can control the number of columns per line.
<GridView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:isScrollContainer="true"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
/>
来源:https://stackoverflow.com/questions/8253735/handling-orientation-changes-android