如何在首先启动应用程序时检测方向模式



我正在开发一个应用程序,我需要在不同的方向上提供不同的活动的背景图像。所以我是这样处理的:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setLanguage();
    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                 Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
                 // set background for landscape
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
               // set background for portrait
    }
}

android:configChanges="locale|orientation|screenSize"

onCreate()中,我设置背景图像为肖像,假设用户将启动应用程序并保持肖像模式。

一切正常,当用户改变他们的模式,相应的背景设置等。

但是如果用户在手机处于横向模式时启动这个应用程序,因为它在第一次启动时显示的是人像图像,因为我假设用户将在人像模式下启动应用程序。

那么我该如何解决这个问题呢?一句话,为不同的方向设置不同的背景图像的最好方法是什么 ?我的方向对吗?

在活动的onCreate中,您可以使用this

检查当前方向
Configuration newConfig = getResources().getConfiguration();
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                 Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
                 // set background for landscape
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
               // set background for portrait
}

在一个句子中,如何为不同的方向设置不同的背景图像?

步骤#1:删除你所做的一切,最明显的是整个android:configChanges的东西。现在忽略背景图像,让其余的配置更改逻辑工作。

步骤#2:创建所需资源目录的-land版本,无论该图像的密度如何(例如,res/drawable-land-hdpi/以匹配res/drawable-hdpi/)

步骤#3:将横向版本移动到-land目录中,命名与纵向版本相同(例如,res/drawable-hdpi/background.pngres/drawable-land-hdpi/background.png)

步骤#4:在android:background属性中引用通用资源名称(例如,@drawable/background)

:

  • 你坚持更好的配置更改行为,

  • Android会在正确的时间给你正确的背景

您可以在onCreate

中检查方向
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int orientation = display.getRotation();
if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_180)
{
    // Portrait
}
else
{
    // landscape
}

检查setContentView方法后方向的变化

int orientation = getResources().getConfiguration().orientation;
    if (orientation == 1){
        utility.toast("portrait");
    }else {
        utility.toast("landscape");
   }

最新更新