我需要检测设备的方向,因为我已经在下面编写了代码。但是我无法获得方向。这是我在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);
}
});
}
//提前致谢
答案 0 :(得分:7)
您需要启用侦听器才能使其正常工作。
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();
}
这对我来说很好。
希望它有所帮助。
答案 1 :(得分:0)
使用这个......
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在方向更改期间从启动开始循环。