how to set landscape orientation in particular activity?
android, material-design, xml
Solution
To lock your Activity during runtime, you can use
// lock orientation to landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
All you need now is to determine the current orientation, and pass it to keep it locked that way.
First, add these imports:
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
Then you can add this to your Activitys onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// lock the current device orientation
int currentOrientation = this.getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_PORTRAIT){
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
else{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
// ... rest of your code
}
See ActivityInfo documentation for the other orientation configurations.
Problem
I am showing graph in my activity using a graphview. Now, I need to set the orientation of activity according to user's rotation. Means, if user will hold mobile horizontally, activity should set its orientation as "landscape" and same for vertical i.e. "portrait". It should not be depends on mobile settings rotation. I just want this for my graph activity only. here is screen short you can easily understand. enter image description here