Not getting orientation using OrientationEventListener in android
I need to determine the orientation of the device, for which I wrote the code below. But I cannot get orientation. This is my oncreate () in MainActivity ... If I need to change anything please let me know
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);
}
});
}
// Thanks in Advance
+3
source to share
2 answers
You need to include a listener for it to work.
OrientationEventListener mOrientationListener = new OrientationEventListener(
getApplicationContext()) {
@Override
public void onOrientationChanged(int orientation) {
if (orientation == 1) {
Toast.makeText(getApplicationContext(), "portrait",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "landscape",
Toast.LENGTH_LONG).show();
}
}
};
if (mOrientationListener.canDetectOrientation()) {
mOrientationListener.enable();
}
This works great for me.
Hope it helps.
+5
source to share
use this ....
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
}
}
write this code in onCreate () function because Activity starts its loop from the beginning when orientation changes.
-1
source to share