如何打开片段而不是活动

时间:2016-01-29 11:28:28

标签: android android-fragments

这是我的应用程序到目前为止: MapsActivity:

public class MapsActivity extends FragmentActivity implements GoogleMap.OnMarkerDragListener, OnMapReadyCallback, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerClickListener, GoogleMap.OnMapLoadedCallback {

private GoogleMap mMap;
private HashMap<LatLng, CustomMarker> list;
public static String TAG = MapsActivity.class.getClass().getName();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    list = new HashMap<>();
    Log.e(TAG, "onCreate()");



}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setOnMarkerClickListener(this);
    mMap.setOnMapLoadedCallback(this);
    mMap.setOnMapLongClickListener(this);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.setOnMarkerDragListener(this);
    Log.e(TAG, "onMapReady");
}


@Override
public void onMapLoaded() {
    retrieveMarkersFromDB();
    Log.e(TAG, "onMapLoaded");
    Toast.makeText(MapsActivity.this, "Touch and hold to create a marker", Toast.LENGTH_SHORT).show();

}


private void retrieveMarkersFromDB() {
    new GetMarkers().execute();
}

@Override
public void onMapLongClick(LatLng latLng) {
    mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
    CustomMarker customMarker = getMarkerAddress(latLng);
    addMarkerToList(customMarker,latLng);
    Toast.makeText(MapsActivity.this, "Marker Added", Toast.LENGTH_SHORT).show();

}

private void addMarkerToList(CustomMarker customMarker, LatLng latLng) {
    list.put(latLng, customMarker);
}

private CustomMarker getMarkerAddress(LatLng latLng) {
    CustomMarker customMarker = null;
    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
    try {
        List<Address> allAddresses = geocoder.getFromLocation(latLng.latitude,latLng.longitude,2);
        Address oneAddress = allAddresses.get(0);
        try{
            if(!oneAddress.getLocality().equals("null")||!oneAddress.getLocality().isEmpty()){
                customMarker = new CustomMarker(oneAddress.getAddressLine(0)+", "+oneAddress.getLocality(),oneAddress.getCountryName(),"","");
            }

        }catch (NullPointerException e){
            customMarker = new CustomMarker(oneAddress.getAddressLine(0),oneAddress.getCountryName(),"","");
        }


    } catch (IOException e) {
        e.printStackTrace();
    }catch (IndexOutOfBoundsException er){
        customMarker = new CustomMarker("N/A","N/A","","");
    }
    return customMarker;
}

@Override
public boolean onMarkerClick(Marker marker) {
    Intent intent = new Intent(this,com.example.fixxxer.mapapp.MarkerScreen.class);
    CustomMarker customMarker = list.get(new LatLng(marker.getPosition().latitude,marker.getPosition().longitude));
    intent.putExtra("addressLine",customMarker.getAddressLine());
    intent.putExtra("countryName",customMarker.getCountryName());
    intent.putExtra("imageURL",customMarker.getImageURL());
    intent.putExtra("comment",customMarker.getComment());
    intent.putExtra("lat",marker.getPosition().latitude);
    intent.putExtra("lng",marker.getPosition().longitude);
    startActivityForResult(intent,1);
    return true;
}

@Override
protected void onDestroy() {
    new DatabaseHelper(this,null,null,1).addMarkers(list);

    super.onDestroy();
}

@Override
public void onMarkerDragStart(Marker marker) {
    marker.remove();
    list.remove(marker.getPosition());
    Toast.makeText(MapsActivity.this, "Marker removed", Toast.LENGTH_SHORT).show();
}

@Override
public void onMarkerDrag(Marker marker) {

}

@Override
public void onMarkerDragEnd(Marker marker) {

}


public class GetMarkers extends AsyncTask<Void,Void,Void>{


    @Override
    protected Void doInBackground(Void... params) {
        Log.e(TAG,"background task started");
        list=new DatabaseHelper(MapsActivity.this,null,null,1).getallmarkers();
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        Log.e("onPostExecute","background task ready");
        Log.e(TAG,String.valueOf(list.size()));
        if (!list.isEmpty()){
            for (LatLng position: list.keySet() ) {
                mMap.addMarker(new MarkerOptions().position(position).draggable(true));
            }
        }
        super.onPostExecute(aVoid);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.e("Main", "onActivityResult()");
    if (requestCode == 1) {
        if (resultCode == MarkerScreen.RESULT_COMMENT_ONLY) {
            String comment = data.getStringExtra("Comment");
            String[]split = data.getStringExtra("Index").split(",");
            list.get(new LatLng(Double.valueOf(split[0]),Double.valueOf(split[1]))).setComment(comment);

        }else if (resultCode == MarkerScreen.RESULT_IMAGE_ONLY) {
            String imageURI = data.getStringExtra("Image");
            String[]split = data.getStringExtra("Index").split(",");
            list.get(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]))).setImageURL(imageURI);
        } else if (resultCode == MarkerScreen.RESULT_BOTH) {
            String comment = data.getStringExtra("Comment");
            String imageURI = data.getStringExtra("Image");
            String[]split = data.getStringExtra("Index").split(",");
            list.get(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]))).setComment(comment);
            list.get(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]))).setImageURL(imageURI);
        } else {
            Log.e("Main", "Result - no change");
        }
    }

}

标记屏幕类(活动)

public class MarkerScreen extends AppCompatActivity {
private static final int REQUEST_TAKE_PHOTO = 1;
private ImageView imageView;
private TextView addressView;
private TextView countryView;
private TextView latlngView;
private EditText commentView;
private Button saveButton;
private Button deleteButton;
private String addressFromIntent;
private String countryFromIntent;
private String commentFromIntent;
private double latFromIntent;
private double lngFromIntent;
private String photoPath;
private String newPhotoPath;
private int imageModified = 0;
private int commentModified = 0;
static final int RESULT_NONE = 0;
static final int RESULT_BOTH = 1;
static final int RESULT_COMMENT_ONLY = 2;
static final int RESULT_IMAGE_ONLY = 3;
static final int RESULT_DELETE=1;



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

    //Initialising Views
    addressView=(TextView)findViewById(R.id.textView);
    countryView=(TextView)findViewById(R.id.textView2);
    latlngView=(TextView)findViewById(R.id.textView3);
    saveButton=(Button)findViewById(R.id.button);
    saveButton.setText("Save");
    imageView=(ImageView)findViewById(R.id.imageView);
    commentView=(EditText)findViewById(R.id.editText);

    //Getting intent information
    addressFromIntent=getIntent().getStringExtra("addressLine");
    countryFromIntent=getIntent().getStringExtra("countryName");
    commentFromIntent=getIntent().getStringExtra("comment");
    photoPath=getIntent().getStringExtra("imageURL");
    latFromIntent=getIntent().getDoubleExtra("lat",0);
    lngFromIntent=getIntent().getDoubleExtra("lng",0);
    //Setting textFields
    addressView.setText(addressFromIntent);
    countryView.setText(countryFromIntent);
    final String latlngTextField=String.valueOf(latFromIntent)+", "+String.valueOf(lngFromIntent);
    latlngView.setText(latlngTextField);
    if (photoPath.equals("")){
        imageView.setImageResource(R.drawable.image);
    } else {
        imageView.setImageURI(Uri.parse(photoPath));
    }

    commentView.setText(commentFromIntent);
    commentView.setHint("Enter comment here...");
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePictureIntent();
            Toast.makeText(MarkerScreen.this, photoPath, Toast.LENGTH_SHORT).show();
        }
    });
    commentView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            commentModified++;

        }
    });
    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            if (imageModified == 0 && commentModified == 0) {
                setResult(RESULT_NONE);
                Log.e("MarkerActivity", "intentResult: RESULT_NONE");
                finish();
            } else if (imageModified > 0 && commentModified == 0) {
                intent.putExtra("Image", newPhotoPath);
                intent.putExtra("Index", latlngView.getText());
                Log.e("MarkerActivity", "intentResult: RESULT_IMAGE ONLY");
                setResult(RESULT_IMAGE_ONLY, intent);
                finish();
            } else if (imageModified == 0 && commentModified > 0) {
                intent.putExtra("Comment", commentView.getText().toString());
                intent.putExtra("Index", latlngView.getText());
                setResult(RESULT_COMMENT_ONLY, intent);
                Log.e("MarkerActivity", "intentResult: RESULT_COMMENT ONLY");
                finish();
            } else if (imageModified > 0 && commentModified > 0) {
                intent.putExtra("Comment", commentView.getText().toString());
                intent.putExtra("Image", newPhotoPath);
                intent.putExtra("Index", latlngView.getText());
                setResult(RESULT_BOTH, intent);
                Log.e("MarkerActivity", "intentResult: RESULT_BOTH");
                finish();
            }
        }
    });
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            this.finish();
            Log.e("markerActivity","back button pressed");
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
@Override public void onBackPressed(){
    this.finish();
    Log.e("markerActivity"," hardware back button pressed");
}
private File createImageFile() throws IOException {
    @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES+ "/MapApp/" + addressFromIntent);
    if (!storageDir.exists()){
        File wallpaperDirectory = new File(storageDir.getPath());
        boolean photoStatus =wallpaperDirectory.mkdirs();
    }
    File image = File.createTempFile(
            imageFileName,
            ".jpg",
            storageDir
    );
    newPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}
private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
           ex.printStackTrace();
        }
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
        Uri uri = Uri.parse(newPhotoPath);
        imageView.setImageURI(uri);
        imageModified++;

    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("photopath",newPhotoPath);
    outState.putString("comment",commentView.getText().toString());
    outState.putString("addressView",addressView.getText().toString());
    outState.putString("countryView",countryView.getText().toString());
    outState.putString("latlngView",latlngView.getText().toString());
    outState.putInt("imageModified", imageModified);
    outState.putInt("commentModified", commentModified);
    Log.e("Saved","saved info");
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    photoPath=savedInstanceState.getString("photopath");
    commentView.setText(savedInstanceState.getString("comment"));
    addressView.setText(savedInstanceState.getString("addressView"));
    countryView.setText(savedInstanceState.getString("countryView"));
    latlngView.setText(savedInstanceState.getString("latlngView"));
    imageModified=savedInstanceState.getInt("imageModified");
    commentModified=savedInstanceState.getInt("commentModified");
    Log.e("Restored","restored info");

}

activity_maps.xml

 xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.fixxxer.mapapp.MapsActivity">
<include layout="@layout/map_layout"/>

map_layout.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fixxxer.mapapp.MapsActivity" />

我想用类似的Activity替换起始MarkerScreen Fragment。这该怎么做?我到目前为止尝试的是创建一个新的BlankFragment通过菜单,并在onMarkerClick()方法中设置:

getFragmentManager()
.beginTransaction()
.replace(R.id.layout.map_layout, BlankFragment.newInstance())
.addToBackStack(null) // enables back key
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) // if you need transition
.commit();

但我收到no view found错误。有一个简单的方法来做这一切吗?我非常喜欢碎片。

1 个答案:

答案 0 :(得分:0)

在替换片段代码中使用R.id.map代替containerViewId,如下所示

    getFragmentManager()
.beginTransaction()
.replace(R.id.map, BlankFragment.newInstance())
.addToBackStack(null) // enables back key
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) // if you need transition
.commit();