我需要检测设备的方向,为此我在下面编写了代码。但我无法获得方向。这是我在 MainActivity 中的 oncreate()... 如果我需要更改任何内容请告诉我
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mOrientationListener = new OrientationEventListener(getApplicationContext())
{
@Override
public void onOrientationChanged(int orientation)
{
if(orientation == 0)
{
setContentView(R.layout.activity_main_portrait);
}
else
{
setContentView(R.layout.activity_main_landscape);
}
}
};
if (mOrientationListener.canDetectOrientation())
{
mOrientationListener.enable();
}
mImgPreview = (ImageView) findViewById(R.id.imgpreview);
mVideoPreview = (ImageView) findViewById(R.id.videopreview);
mAudioPreview = (ImageView) findViewById(R.id.audiopreview);
/*-------Intent to view Image Gallery---------*/
mImgPreview.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(), ImageList.class);
startActivity(intent);
}
});
/*-------Intent to view Video Gallery---------*/
mVideoPreview.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(), Video.class);
startActivity(intent);
}
});
/*--------Intent to view Audio Gallery--------*/
mAudioPreview.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(), AudioPlayer.class);
startActivity(intent);
}
});
}
//提前致谢
您需要启用侦听器才能使其工作。
OrientationEventListener mOrientationListener = new OrientationEventListener(
getApplicationContext()) {
@Override
public void onOrientationChanged(int orientation) {
if (orientation == 0 || orientation == 180) {
Toast.makeText(getApplicationContext(), "portrait",
Toast.LENGTH_LONG).show();
} else if (orientation == 90 || orientation == 270) {
Toast.makeText(getApplicationContext(), "landscape",
Toast.LENGTH_LONG).show();
}
}
};
if (mOrientationListener.canDetectOrientation()) {
mOrientationListener.enable();
}
这对我来说效果很好。
希望有帮助。
检查您的AndroidManifest,您的主要活动(应用程序的入口)应设置为 android:exported="true"在此处输入图像描述 对于 sdk 28 来说这不是必需的,但如果未设置导出,侦听器将无法工作; 您还可以在运行应用程序时检查您的 logcat,在我的情况下,每次使用orientationEventListener 运行活动时,都可以在 logcat 中找到“尝试启用传感器(lsm6dso 加速计非唤醒)而不保持”。
用这个....
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// setContentView 1 here
}else{
// setContentView 2 here
}
}
将此代码写入 onCreate() 函数中,因为 Activity 在方向更改期间从开始开始其循环..