在android中使用OrientationEventListener无法获取方向信息
我需要检测设备的方向,为此我在下面写了一段代码。但我无法获取方向。这是我在MainActivity中的oncreate()。。。 如果我需要改变什么,请告诉我在android中使用OrientationEventListener无法获取方向信息,android,Android,我需要检测设备的方向,为此我在下面写了一段代码。但我无法获取方向。这是我在MainActivity中的oncreate()。。。 如果我需要改变什么,请告诉我 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mOrientationListener = new OrientationEventListener(getApplicationConte
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();
}
这对我来说很好
希望有帮助。用这个
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()函数中编写此代码,因为活动从方向更改期间开始循环。是否启用了它?否如何启用itI我已在if condition中定义了我的纵向和横向布局。。。当我运行应用程序时,它显示应用程序已停止…@NarendraKumar查看日志。当我运行应用程序时,有一个崩溃,它不会检查方向。更改设备方向后,将仅执行orientationeventlistener。。。我不知道问题出在哪里如果你只需要在onCreate中检查一次,那么试试其他答案如果有效@NarendraKumarorientaiton可以取0到359,而不是1或0。上面的代码总是显示“风景”。首先,这不是问题所在。他想用传感器(定向文案监听器)来做这件事。第二,你的代码不标准;您不应该手动检查布局的方向,这是/res/layout和/res/layout land的目的。