android-fragments 片段活动出现此错误,但我不知道这是怎么回事

y53ybaqx  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(112)
import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.navigation.NavigationView;

public class Home extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new BlogsFragment()).commit();
        navigationView.setCheckedItem(R.id.blogs);}
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.blogs:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new BlogsFragment()).commit();
                break;
            case R.id.blogs:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MedsFragment()).commit();
                break;
            case R.id.blogs:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new AboutFragment()).commit();
                break;
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)){
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}

This is the error.

ogsagwnx

ogsagwnx1#

请确保BlogsFragment()、MedsFragment()、AboutFragment()属于片段类型。这些Java类必须从片段类继承。

public class BlogsFragment extends Fragment {

..
}

相关问题