使用操作栏和底部导航时,片段重叠

时间:2020-11-12 13:17:01

标签: java android android-fragments

我正在尝试使用底部导航创建应用。
Layouts和MainActivity是由Android studio自动创建的,我现在在操作栏中添加了一个图标,当按下该图标时,应该会出现一个新的片段并显示设置。 问题在于设置片段与底部导航片段重叠(参见图片)

Settings fragment overlap with one of other fragment used in bottom navigation This should be how the settings fragment should be seen (here no overlap because notification fragment is curently void)
第一图像设置中,片段与底部导航中使用的其他片段之一重叠。在 second 中,这应该是应该看到设置片段的方式(此处没有重叠,因为通知片段当前无效)

要在操作栏上添加设置图标,我使用了onCreateOptionsMenu()方法,这是我的MainActivity类的代码:

public class MainActivity extends AppCompatActivity {

    private Client client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);

        this.client = null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.actionbar_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            setFragment();
            Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void setFragment() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        ft.replace(R.id.nav_host_fragment, new SettingsFragment());
        ft.commit();
    }
}

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

将背景色赋予片段布局的根视图