Handling orientation changes android

青春壹個敷衍的年華 提交于 2019-12-11 16:16:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!