处理方向改变android

时间:2011-11-24 07:55:38

标签: android screen-orientation

我有一个表,每行包含许多图像。基于图像宽度和屏幕宽度,动态地确定每行的图像数量。当我正常使用手机时,图像在手机屏幕上间隔开。当手机方向改变时,所有图像都出现在同一行。我应该明确处理这种情况的方向变化吗?

// 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);

3 个答案:

答案 0 :(得分:3)

这取决于运行该代码的时间,但通常不需要做任何特殊的事情。

当Android检测到方向更改时,系统将重新创建您的活动,它将有机会完成onCreate并根据新配置重新布局并重新渲染所有内容。

使用android android:configChanges时应谨慎使用,而不是您想到的第一个选项,因为系统会在配置更改后为您选择合适的资源做得更好(并且您必须处理其他形式的配置的代码路径无论如何都会改变。)

请参阅: http://developer.android.com/guide/topics/resources/runtime-changes.html

答案 1 :(得分:0)

是。一种方法是将android:configChanges="orientation|keyboardHidden"放在AndroidManifest.xml文件中的<activity>上,然后覆盖onConfigurationChanged以检测方向更改。

答案 2 :(得分:0)

如果要保留一行中显示的图像数量,可以使用 GridView 。通过这种方式,您可以控制每行的列数。

<GridView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:isScrollContainer="true" 
        android:numColumns="3"
        android:verticalSpacing="10dp" 
        android:horizontalSpacing="10dp"
        />
相关问题