I am Android Studio beginner and I wish to get some guidance from experienced one. So I've created a project with bottom navigation activity and have 1 default layout which is
activity_main.xml. With those ready bottom navigation, I created layouts for each of them by adding a new empty fragment.
I have Home, MainActivity, Notifications, Profile, Settings under my bundle folder (under java). Layout folder has activity_main.xml, fragment_home.xml, fragment_notifications.xml, fragment_profile.xml, fragment_settings.xml.
I want to make
fragment_home.xml layout to be first displayed in the container of
activity_main.xml
What I understand about the layout is, activity_main.xml now acting like a master container where it's elements (such as button, textinput) will keep on displayed even after I change the view screen by clicking one of the menu from bottom navbar.
This is what I have in
activity_main.xml :
="1.0"="utf-8"
<androidx.constraintlayout.widget.ConstraintLayout>
<TextView />
<com.google.android.material.bottomnavigation.BottomNavigationView />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my
MainActivity.java :
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new Home()).commit();
return true;
case R.id.navigation_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new Profile()).commit();
return true;
case R.id.navigation_notifications:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new Notifications()).commit();
return true;
case R.id.navigation_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new Settings()).commit();
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
mTextMessage = findViewById(R.id.message);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
What I have tried:
I tried replacing
<TextView />
with
<include layout="@layout/fragment_home" />
from activity_main.xml but like I said, it will be displayed in every screen when switched.
How should I load the home fragment as default view and replaced with other view based on the navigation selection? Thank you.