简体   繁体   English

导航抽屉无法使用片段进行活动

[英]Navigation drawer not working on activities using fragments

I've been trying to add a Nav Drawer to my app. 我一直在尝试向我的应用添加导航抽屉。 I have this MapsActivty which is my main activity. 我有这个MapsActivty,这是我的主要活动。

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

public GoogleMap mMap;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    }


@SuppressWarnings("StatementWithEmptyBody")
public void onMapSearch(View view) {
    EditText locationSearch = (EditText) findViewById(R.id.editText);
    String location = locationSearch.getText().toString();
    List<Address> addressList = null;

    if (location != null || !location.equals("")) {
        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location, 1);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }
}

public void onNormalMap(View view) {
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}

public void onSatelliteMap(View view) {
    mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}

public void onTerrainMap(View view) {
    mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}


public void onHybridMap(View view) {
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
public static double lng;
public static double lat;
@Override
public void onMapReady(final GoogleMap googleMap) {
    mMap = googleMap;

    Button btn = (Button) findViewById(R.id.button);


    btn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent (v.getContext(), RegistroInfo.class);
            intent.putExtra("longitud", String.valueOf(lng));
            intent.putExtra("latitud", String.valueOf(lat));
            startActivityForResult(intent, 0);
        } });
    //View v;

    mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

        @Override
        public void onMapLongClick(LatLng point) {
            mMap.addMarker(new MarkerOptions().position(point).title("Custom location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
            RegistroInfo regis = new RegistroInfo();
            lng = point.longitude;
            lat = point.latitude;

        }

    });

    // Add a marker in Sydney and move the camera
    LatLng cusco = new LatLng(-13.537733, -71.903838);
    mMap.addMarker(new MarkerOptions().position(cusco).title("Cusco, Peru"));
    float zoomLevel = 16; //This goes up to 21
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(cusco, zoomLevel));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(cusco));


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        return;
    }
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setIndoorLevelPickerEnabled(true);}}
  1. NOTICE that a use extends FragmentActivity and i saw that i could use extends MenuActivity from my MenuActivity I tried this post [ Same Navigation Drawer in different Activities ) 注意,某用途extends FragmentActivity ,我看到可以使用我的MenuActivity extends MenuActivity ,我尝试了这篇文章[ 不同活动中的相同导航抽屉 ]

  2. From my Menu Activity i have some items, which are the MapsActivity( nav_MenuPrincipal ), PerfilActivity(another activity showing information of current user) nav_perfil , NormalMap(style of map) nav_normal , SatelliteMap(style of map) nav_satellite, TerrainMap(style of map) nav_terrainmap , HybridMap(style of map) nav_hybrid 在我的菜单活动中,我有一些项目,分别是MapsActivity( nav_MenuPrincipal ),PerfilActivity(另一个显示当前用户信息的活动) nav_perfil ,NormalMap(地图样式) nav_normal ,SatelliteMap(地图样式) nav_satellite, TerrainMap(style of map) nav_terrainmap , HybridMap(style of map) nav_hybrid

Here goes the MenuActivity 这里是MenuActivity

    public class MenuActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

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

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_MenuPrincipal) {
        startActivity(new Intent(this, MapsActivity.class));
        return true;
    }
    else if (id == R.id.nav_perfil) {


    }
    else if (id == R.id.nav_suggestions) {


    } else if (id == R.id.nav_normalmap) {

    } else if (id == R.id.nav_satellitemap) {

    } else if (id == R.id.nav_terrainmap) {

    } else if (id == R.id.nav_hybridmap) {


    } else if (id == R.id.nav_aboutus) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}
  1. Notice that I've tried this if (id == R.id.nav_MenuPrincipal) { startActivity(new Intent(this, MapsActivity.class)); return true; } 请注意, if (id == R.id.nav_MenuPrincipal) { startActivity(new Intent(this, MapsActivity.class)); return true; } if (id == R.id.nav_MenuPrincipal) { startActivity(new Intent(this, MapsActivity.class)); return true; } if (id == R.id.nav_MenuPrincipal) { startActivity(new Intent(this, MapsActivity.class)); return true; } , it works but not showing the menu bar. if (id == R.id.nav_MenuPrincipal) { startActivity(new Intent(this, MapsActivity.class)); return true; } ,但无法显示菜单栏。

  2. For the items called Normal, Satellite, Terrain, Hybrid i just want to change the style of the map for the MapsActivity 对于名为Normal, Satellite, Terrain, Hybrid的项目Normal, Satellite, Terrain, Hybrid我只想更改MapsActivity的地图MapsActivity

  3. Now I'm using a LoginActivity which is already connected to a DB on a Hosting, it has the intent filter. 现在,我使用的是已连接到Hosting上的DB的LoginActivity,它具有意图过滤器。 Then i want to show my MainActivity (MapsActivity) but with that Menu (NavigationDrawer) 然后我想显示我的MainActivity(MapsActivity)但带有该菜单(NavigationDrawer)

Thank you very much. 非常感谢你。 Sorry if I'm not very clear, its my first time here 抱歉,如果我不太清楚,这是我第一次来

here is your solution 这是你的解决方案

public class MapsActivity extends AppCompatActivity implements
        OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener,
        OnClickListener {

    private GoogleMap mMap;
    private NavigationView mDrawer;
    private DrawerLayout mDrawerLayout;
    SupportMapFragment mMapFragment;
    private ActionBarDrawerToggle mDrawerToggle;
    private Button search;
    int PLACE_PICKER_REQUEST = 1;
    String placeName, address;
    private static final float ALPHA_DIM_VALUE = 0.1f;

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

        mMapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        try {
            manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(myIntent);
                overridePendingTransition(R.anim.push_up_in,
                        R.anim.push_up_out);
            } else {
                mMapFragment.getMapAsync(this);
                overridePendingTransition(R.anim.push_up_out,
                        R.anim.push_up_in);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        setupDrawer();

        mDrawerLayout.addDrawerListener(mDrawerToggle);
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

    private void showErrorToast() {
        Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.Toast_Error), Toast.LENGTH_SHORT).show();
    }

    private void setupDrawer() {
        assert getSupportActionBar() != null;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        mDrawer = (NavigationView) findViewById(R.id.mNavDrawer);
        assert mDrawer != null;
        mDrawer.setNavigationItemSelectedListener(this);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.string.DrawerOpen,
                R.string.DrawerClose) {
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        mDrawerLayout.addDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();
    }


    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Intent intent = null;
        if (item.getItemId() == R.id.navigation_item_1) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
            intent = new Intent(this, LocationList.class);
            startActivity(intent);
            overridePendingTransition(R.anim.push_up_in,
                    R.anim.push_up_out);
            finish();
            return true;
        }
        if (item.getItemId() == R.id.navigation_item_2) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
            intent = new Intent(this, MapsActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.push_up_in,
                    R.anim.push_up_out);
            finish();
            return true;
        }
        mDrawerLayout.closeDrawers();
        return true;
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

   @Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    if (id == android.R.id.home) {
        mDrawerLayout.openDrawer(GravityCompat.START);
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

just copy reliable code.. and have any doubt about Map then ask me.. i have all your solution regarding map. 只需复制可靠的代码即可..对Map有任何疑问,然后问我..我拥有有关map的所有解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM