我是初学者。我的项目包含一个包含导航抽屉的现有地图活动。这两个活动的Java代码合并为一个。我想在每次点击抽屉的任何菜单项时开始一个新的活动/新片段,但我无法这样做。
这是我的activity_maps.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.DrawerLayout
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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main2"
app:menu="@menu/activity_main2_drawer" />
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Wallpaper.NoTitleBar.AppBarOverlay">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frame">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:layout_marginBottom="0dp"
tools:context=".MapsActivity2" />
</FrameLayout>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="137dp"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
app:popupTheme="@style/Wallpaper.NoTitleBar.PopupOverlay" />
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="115dp"
android:layout_height="75dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
card_view:cardElevation="6dp"
card_view:cardMaxElevation="10dp"
app:cardBackgroundColor=" #D3D3D3">
<TextView
android:id="@+id/textView"
android:layout_width="115dp"
android:layout_height="wrap_content"
android:text="Find Ambulances"
android:textAlignment="center"
android:textColor="#000000" />
<ImageView
android:id="@+id/imageView6"
android:layout_width="115dp"
android:layout_height="55dp"
android:layout_gravity="bottom"
card_view:srcCompat="@mipmap/ambu" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="@+id/card_view1"
android:layout_width="115dp"
android:layout_height="75dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
card_view:cardElevation="6dp"
card_view:cardMaxElevation="10dp"
app:cardBackgroundColor=" #D3D3D3">
<TextView
android:id="@+id/textView6"
android:layout_width="115dp"
android:layout_height="wrap_content"
android:text="Find Hospitals"
android:textAlignment="center"
android:textColor="#000000" />
<ImageView
android:id="@+id/imageView5"
android:layout_width="115dp"
android:layout_height="55dp"
android:layout_gravity="bottom"
card_view:srcCompat="@mipmap/hosp" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="@+id/card_view2"
android:layout_width="115dp"
android:layout_height="75dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
card_view:cardElevation="6dp"
card_view:cardMaxElevation="10dp"
app:cardBackgroundColor=" #D3D3D3">
<TextView
android:id="@+id/textView7"
android:layout_width="115dp"
android:layout_height="wrap_content"
android:text="Search"
android:textAlignment="center"
android:textColor="#000000" />
<ImageView
android:id="@+id/imageView4"
android:layout_width="115dp"
android:layout_height="55dp"
android:layout_gravity="bottom"
card_view:srcCompat="@mipmap/search" />
</android.support.v7.widget.CardView>
</RelativeLayout>
</android.support.design.widget.AppBarLayout>
</android.support.v4.widget.DrawerLayout>
</FrameLayout>
MapsActivity2.java:
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity2 extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,NavigationView.OnNavigationItemSelectedListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
//getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
/*fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.getBackground().setAlpha(120);
navigationView.setItemIconTintList(null);
navigationView.setNavigationItemSelectedListener
((NavigationView.OnNavigationSelectedListener) this);
}
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates
(mGoogleApiClient, (com.google.android.gms.location.LocationListener)
this);
}
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.
PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates
(mGoogleApiClient, mLocationRequest,
(com.google.android.gms.location.LocationListener) this);
}
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
@Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(),
location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker
(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't
block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission,
please accept to use location functionality")
.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,
int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity2.this,
new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[]
grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied",
Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
@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.main2, 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);
}
private void displaySelectedScreen(int id) {
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_c) {
// Handle the camera action
} else if (id == R.id.nav_g) {
Intent intent= new Intent(this,KnowActivity.class);
Bundle bundle= new Bundle();
bundle.putString("Value Send","this data sent");
intent.putExtras(bundle);
this.startActivity(intent);
} else if (id == R.id.nav_s) {
} else if (id == R.id.nav_feed) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
KnowActivity.java:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class KnowActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_know);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String dataSentFromMain = bundle.getString("Value Send");
Toast.makeText(this, dataSentFromMain, Toast.LENGTH_SHORT).show();
}
}
}
答案 0 :(得分:0)
这里需要一些更多的背景。很高兴看到你已经有的java代码,但是你可以在这里展示一个现有活动的新片段......
NewFragment someFrag = new NewFragment();
getSupportedFragmentManager().beginTransaction()
.replace(R.id.YourActivity, someFrag).addToBackStack("")
.commit();
这将替换您由R.id.YourActivity
定义的活动布局,并将其替换为您在someFrag
中提供的任何片段,这也会将此活动添加到backstack,这样当用户访问新片段时按下后退按钮,它将返回此活动。
希望这会有所帮助,但很难用这么少的背景来明确解决问题