检测Android主屏幕的旋转

时间:2015-09-02 13:18:39

标签: android rotation android-appwidget homescreen

我有一个App Widget,当它更新时,会提取尺寸与小工具相匹配的图片,并将该图片放入ImageView(通过RemoteViews)。它运作得很好。

但对于支持主屏幕旋转的设备(我不是在谈论基于设备方向的Activity的旋转,而是关于的旋转主屏幕本身)当从横向到纵向时,窗口小部件的尺寸和纵横比会发生一些变化,反之亦然......即不保持固定尺寸。

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

我不能为我的生活找出是否以及如何做到这一点。有线索吗?

8 个答案:

答案 0 :(得分: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));
    }

答案 1 :(得分:1)

使用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();
}
}

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

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

并在清单......

<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 -->

答案 2 :(得分:1)

检查此代码是否有效:

 myButton.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {

    int rotation = getWindowManager().getDefaultDisplay()
      .getRotation();
    // DisplayMetrics dm = new DisplayMetrics();
    // getWindowManager().getDefaultDisplay().getMetrics(dm);
    int orientation;
    CharSequence text;

    switch (rotation) {
    case Surface.ROTATION_0:
     text = "SCREEN_ORIENTATION_PORTRAIT";
     break;
    case Surface.ROTATION_90:
     text = "SCREEN_ORIENTATION_LANDSCAPE";
     break;
    case Surface.ROTATION_180:
     text = "SCREEN_ORIENTATION_REVERSE_PORTRAIT";
     break;
    case Surface.ROTATION_270:
     text = "SCREEN_ORIENTATION_REVERSE_LANDSCAPE";
     break;
    default:
     text = "SCREEN_ORIENTATION_PORTRAIT";
     break;
    }

    // CharSequence text = String.valueOf(orientation);
    Toast toast = Toast.makeText(getApplicationContext(), text,
      Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER | Gravity.CENTER, 10, 0);
    toast.show();

   }
  });

答案 3 :(得分:1)

也许您可以使用透明背景构图。如果图像小到足以在旋转时也适合,则您不需要重新获取它。

答案 4 :(得分:1)

您可以收听当前设备配置(方向,区域设置等)发生变化时由android系统发送的广播ACTION_CONFIGURATION_CHANGED。 根据文件:

  

ACTION_CONFIGURATION_CHANGED:

     

广播操作:当前设备配置(方向,   locale等)已经改变了。当发生这样的变化时,UI(查看   层次结构)需要根据这些新信息重建;对于   大多数情况下,应用程序不需要担心这一点,因为   系统将负责停止和重新启动应用程序   确保它看到新的变化。一些不能的系统代码   重新启动将需要观察此操作并处理它   适当。

     

您无法通过清单中声明的​​组件收到此信息   通过使用Context.registerReceiver()显式注册它。

     

这是受保护的意图,只能由系统发送。

public class YourWidgetProvider extends AppWidgetProvider {

        @Override
        public void onEnabled(Context context) {
            super.onEnabled(context);
            context.registerReceiver(mOrientationChangeReceiver,new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
        }

        @Override
        public void onDisabled(Context context) {
            context.unregisterReceiver(mOrientationChangeReceiver);
            super.onDisabled(context);
        }

        public BroadcastReceiver mOrientationChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent myIntent) {
                if ( myIntent.getAction().equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
                    if(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
                        // landscape orientation
                        //write logic for building remote view here
                        // buildRemoteViews();
                    }
                    else {
                        //portrait orientation
                        //write logic for building remote view here
                        // buildRemoteViews();
                    }
                }
            }
        };
    }

答案 5 :(得分:1)

您可以使用小部件的宽度和高度进行检查,如以下代码段所示:

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Information</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="css/bootstrap.min.css">
      <script src="js/jquery-2.1.4.min.js"></script>
      <script src="js/bootstrap.min.js"></script>

      <!--Sorry: i didn't find online links for the links below -->
      <link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css">
      <script src="js/moment.min.js"></script> <!-- bootstrap-datetimepicker requires Moment.js to be loaded first -->
      <script src="js/bootstrap-datetimepicker.min.js"></script>

      <script type="text/javascript">
         $(function () {
            $('#datetimepicker1').datetimepicker({format:"DD/MM/YYYY", useCurrent: false });
         });    

         //this will be called for new datetimepicker.i think, unique id needed every time.
         $(function () {
            $('#datetimepicker2').datetimepicker({format:"DD/MM/YYYY", useCurrent: false });
         });            
      </script>  

      <style>
         div.child_div:first-child {
         margin-top: 0px;
         padding-top: 0px;
         }
         div.child_div {
         width: 615px;
         }
         div.job-position {
         width: 220px;
         }
         div.job-type {
         width: 180px;
         }
         div.job-amount {
         width: 180px;
         }
         div.form-group {
         padding-top: 25px;
         }
         input#create_button {
         margin-top: 50px;
         }
      </style>
   </head>
   <body >
      <div class="container"  >
         <div class="panel-group">
            <div class="panel panel-primary">
               <div class="panel-heading">
                  <h3 class="panel-title" style="text-align: center;"><b>Information</b></h3>
               </div>
               <div class="panel-body">
                  <form class="form-horizontal" >
                     <div class="form-group">
                        <label class="control-label col-sm-3"  for="employeeid">ID:</label>
                        <div class="col-sm-8">
                           <div class="input-group">
                              <span class="input-group-addon"><i class="glyphicon glyphicon-user"  aria-hidden="true"></i></span>
                              <input type="text" class="form-control" id="employeeid"  placeholder="Enter ID">             
                           </div>
                        </div>
                     </div>
                     <div class="form-group" id="parent_div1">
                        <div class="row form-group" id="child_div1">
                           <label  class="col-xs-2 control-label"></label>
                           <div class="col-xs-12 col-lg-3">
                              <label  class="wb-inv">Job:</label>
                              <div class="input-group" style="">
                                 <select class="form-control " id="employeetype" onchange="updateText('facultyinstitute')">
                                    <option value="" disabled="" selected=""  >Select Job Type</option>
                                    <option value="10">Type 1</option>
                                    <option value="10">Type 2</option>
                                 </select>
                              </div>
                           </div>
                           <div class="col-xs-12 col-lg-3" >
                              <label  class="wb-inv"> Effective Date:</label>
                              <div class="input-group" >
                                 <input type="text"  id='datetimepicker1' class="form-control" placeholder="DD/MM/YYYY">
                                 <span class="input-group-addon">
                                 <span class="glyphicon glyphicon-calendar"></span>
                                 </span>
                              </div>
                           </div>
                           <div class="col-xs-12 col-lg-3">
                              <label class="wb-inv">Amount:</label>
                              <div class="input-group" >
                                 <input type="text" class="form-control" id="pamount" placeholder=".00" />
                                 <span class="input-group-addon"><i class="glyphicon glyphicon-usd"></i></span>
                              </div>
                           </div>
                        </div>
                     </div>
                     <div class="form-group"  style="padding-left:200px;">
                        <div class="form-group" id="parent_div">
                           <div class="row form-group child_div">
                              <div class="col-xs-12 col-lg-3 job-position">
                                 <label for="form-input-col-xs-2" class="wb-inv">Other Job Position:</label>
                                 <div class="input-group" style="">
                                    <select class="form-control " id="employeetype" onchange="updateText('')">
                                       <option value="" disabled="" selected="">Select Job Type</option>
                                       <option value="10">1</option>
                                       <option value="10">2</option>
                                       <option value="10">3</option>
                                    </select>
                                 </div>
                              </div>
                              <div class="col-xs-12 col-lg-3 job-date">
                                 <label for="form-input-col-xs-3" class="wb-inv">Date:</label>
                                 <div class="input-group">
                                 <!-- its duplicate is not working -->
                                    <input type="text" class="form-control" id="datetimepicker2" placeholder="DD/MM/YYYY" />
                                    <span class="input-group-addon">
                                    <span class="glyphicon glyphicon-calendar"></span>
                                    </span>
                                 </div>
                              </div>
                              <div class="col-xs-12 col-lg-3 job-amount">
                                 <label for="form-input-col-xs-3" class="wb-inv">Amount:</label>
                                 <div class="input-group">
                                    <input type="text" class="form-control" id="form-input-col-xs-3" placeholder=".00" />
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-usd"></i></span>          
                                 </div>
                              </div>
                              <div class="form-group ">
                                 <div class="input-group">
                                    <input class="btn btn-danger deleteButton" type="button" value="-" />       
                                 </div>
                              </div>
                           </div>
                        </div>
                        <input class="btn btn-success " type="button" id="create_button" value="+" />
                     </div>
                     <div class="form-group">
                     </div>
                     <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                           <button type="submit" class="btn btn-primary">Save</button>
                           <button type="button" class="btn btn-success">Edit</button>
                           <button type="button" class="btn btn-danger">Delete</button>
                           <button type="button" class="btn btn-info">Exit</button> 
                        </div>
                     </div>
                  </form>
               </div>
            </div>
         </div>
      </div>
      <script  type="text/javascript">     
         $('#create_button').click(function() {
           var html = $('.child_div:first').parent().html();
           $(html).insertBefore(this);
         });

         $(document).on("click", ".deleteButton", function() {
           $(this).closest('.child_div').remove();
         }); 
      </script>
   </body>
</html>

答案 6 :(得分:0)

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

答案 7 :(得分:0)

自Android API 16起,有一个新的替代项可以接收配置信息。

@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions)
{
    int width = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
    int height = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
    int orientation = context.getResources().getConfiguration().orientation;

    if (BuildConfig.DEBUG) logWidgetEvents("UPDATE " + width + "x" + height + " - " + orientation, new int[] { appWidgetId }, appWidgetManager);

    onUpdate(context, appWidgetManager, new int[] { appWidgetId });
}

然后onUpdate()可以检查方向,就像这样:

int rotation = context.getResources().getConfiguration().orientation;
if (rotation == Configuration.ORIENTATION_PORTRAIT)
{
    ... portrait ...
}
else
{
    ... landscape ...
}