检测Android主屏幕的旋转

drm*_*wer 21 android rotation homescreen android-appwidget

我有一个App Widget,当它更新时,获取具有与小部件匹配的尺寸的图像,并将该图像放入ImageView(通过RemoteViews).它工作得很好.

但是对于支持主屏幕旋转的设备(我不是在谈论Activity基于设备方向的旋转,而是关于主屏幕本身的旋转),小部件的尺寸和宽高比从横向到纵向,反之亦然......即不保持固定尺寸.

因此,我的小部件需要能够检测主屏幕何时旋转,并获取新图像(或至少加载不同的预取图像).

我无法为我的生活找出是否以及如何做到这一点.有线索吗?

Ami*_*ale 7

使用以下代码检测方向: -

    View view = getWindow().getDecorView();
    int orientation = getResources().getConfiguration().orientation;

    if (Configuration.ORIENTATION_LANDSCAPE == orientation) {
       relativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.log_landscape));
        imageview_Logo.setImageResource(R.drawable.log_landscape_2);
        Log.d("Landscape", String.valueOf(orientation));
        //Do SomeThing; // Landscape
    } else {
       relativeLayout.setBackgroundDrawable( getResources().getDrawable(R.drawable.login_bg) );
       imageview_Logo.setImageResource(R.drawable.logo_login);
        //Do SomeThing;  // Portrait
        Log.d("Portrait", String.valueOf(orientation));
    }
Run Code Online (Sandbox Code Playgroud)


Roh*_*tap 0

使用Activity的onConfigurationChanged方法。请看下面的代码:

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);

// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
    Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
Run Code Online (Sandbox Code Playgroud)

好的,对于小部件,我们必须添加如下所示的应用程序类,并且不要忘记在清单中声明它,该方法基本上向小部件的所有实例发送更新广播。

public class MyApplication extends Application {

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // create intent to update all instances of the widget
    Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, MyWidget.class);

    // retrieve all appWidgetIds for the widget & put it into the Intent
    AppWidgetManager appWidgetMgr = AppWidgetManager.getInstance(this);
    ComponentName cm = new ComponentName(this, MyWidget.class);
    int[] appWidgetIds = appWidgetMgr.getAppWidgetIds(cm);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

    // update the widget
    sendBroadcast(intent);
}
}
Run Code Online (Sandbox Code Playgroud)

并且明显...

<application
android:name="yourpackagename.MyApplication"
android:description="@string/app_name"
android:label="@string/app_name"
android:icon="@drawable/app_icon">

<!-- here go your Activity definitions -->
Run Code Online (Sandbox Code Playgroud)