In my app MainActivity
contains a BottomNavigation
, so it can display different tabs. Now my intention was, to force some of them to stay in portrait orientation, regardless of how the user holds the device.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new OverviewFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_overview:
selectedFragment = new OverviewFragment();
break;
case R.id.nav_reports:
selectedFragment = new ReportsFragment();
break;
case R.id.nav_settings:
selectedFragment = new SettingsFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottom_navigation"/>
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="@menu/bottom_navigation"/>
At least one tab should be displayable in portrait AND in landscape mode. Do I have to add some stuff into the xml, or do some java magic? Thanks in advance!
You can set screenOrientation
in AndroidManifest.xml
.
<activity
android:name="yourActivity"
android:screenOrientation="portrait"/>
This activity will remain portrait always.
If you need it programatically then you can use this.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Edit If i understood right, you want make different layout for different orientation.
Then create a
layout-land
directory and place the landscape layout XML file in that directory.