[英]Change activity in a navigation Drawer with Fragment and FragmentActivity
I am a newbie programmer and I am trying to learn something of Android.我是一名新手程序员,我正在尝试学习 Android 的一些东西。 I follow some tutorials and now I have a navigation Drawer App.我遵循一些教程,现在我有一个导航抽屉应用程序。 Until now I have managed changes of layouts with the buttons in the menu.到目前为止,我已经使用菜单中的按钮管理了布局的更改。 Now I want to create a map locator and I followed this Tutorial .现在我想创建一个 map 定位器,我按照本教程进行操作。 Now I want to click a button that brings me to this new Activity in which I can track the position.现在我想单击一个按钮,将我带到这个新的活动,我可以在其中跟踪 position。
My code is: GalleryFragment.Java我的代码是: GalleryFragment.Java
package com.example.frangela.ui.gallery;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.example.frangela.R;
import com.example.frangela.Spesa;
import com.example.frangela.databinding.FragmentGalleryBinding;
import com.example.frangela.ui.deter.DeterminaFrag;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
private FragmentGalleryBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
new ViewModelProvider(this).get(GalleryViewModel.class);
binding = FragmentGalleryBinding.inflate(inflater, container, false);
View root = binding.getRoot();
EditText ET = binding.EditProva;
Button btn = binding.buttonProva;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentActivity fragment = new DeterminaFrag();
FragmentManager fragmentManager = fragment.getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.nav_host_fragment_content_main, fragment);
}
});
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
//textView.setText(s);
}
});
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
DeterminaFrag.java DeterminaFrag.java
package com.example.frangela.ui.deter;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.example.frangela.R;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Arrays;
public class DeterminaFrag extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private DatabaseReference databaseReference;
private LocationListener locationListener;
private LocationManager locationManager;
private final long MIN_TIME = 1000;
private final long MIN_DIST = 5;
private EditText editTextLatitude;
private EditText editTextLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
editTextLatitude = findViewById(R.id.editText);
editTextLongitude = findViewById(R.id.editText2);
databaseReference = FirebaseDatabase.getInstance().getReference("Location");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
String databaseLatitudeString = dataSnapshot.child("latitude").getValue().toString().substring(1, dataSnapshot.child("latitude").getValue().toString().length()-1);
String databaseLongitudedeString = dataSnapshot.child("longitude").getValue().toString().substring(1, dataSnapshot.child("longitude").getValue().toString().length()-1);
String[] stringLat = databaseLatitudeString.split(", ");
Arrays.sort(stringLat);
String latitude = stringLat[stringLat.length-1].split("=")[1];
String[] stringLong = databaseLongitudedeString.split(", ");
Arrays.sort(stringLong);
String longitude = stringLong[stringLong.length-1].split("=")[1];
LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
mMap.addMarker(new MarkerOptions().position(latLng).title(latitude + " , " + longitude));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// // Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
try {
editTextLatitude.setText(Double.toString(location.getLatitude()));
editTextLongitude.setText(Double.toString(location.getLongitude()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DIST, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DIST, locationListener);
}
catch (Exception e){
e.printStackTrace();
}
}
public void updateButtonOnclick(View view){
databaseReference.child("latitude").push().setValue(editTextLatitude.getText().toString());
databaseReference.child("longitude").push().setValue(editTextLongitude.getText().toString());
}
}
fragment_Gallery.xml fragment_Gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.gallery.GalleryFragment">
<EditText
android:id="@+id/EditProva"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100sp"
android:foregroundGravity="center_horizontal"
android:gravity="center_horizontal"
android:padding="40sp"
android:text="Inserire qualcosa di prova"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/button_prova"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prova"
app:layout_constraintTop_toBottomOf="@+id/EditProva"
tools:layout_editor_absoluteX="150dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_maps.xml activity_maps.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.deter.DeterminaFrag">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="550dp"
tools:context=".MapsActivity"
tools:layout="@android:layout/simple_spinner_dropdown_item" />
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="550dp"
android:ems="10"
android:hint="Latitudine"
android:inputType="textPersonName"
android:autofillHints="" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="220dp"
android:layout_marginTop="550dp"
android:ems="10"
android:hint="Longitudine"
android:inputType="textPersonName"
android:autofillHints="" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginTop="600dp"
android:onClick="updateButtonOnclick"
android:text="Aggiorna" />
</FrameLayout>
content_main.xml content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/app_bar_main">
<fragment
android:id="@+id/nav_host_fragment_content_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
I think the problem is in this code (in fact it does not even compile)我认为问题出在这段代码中(实际上它甚至没有编译)
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentActivity fragment = new DeterminaFrag();
FragmentManager fragmentManager = fragment.getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.nav_host_fragment_content_main, fragment);
}
});
I don't know if is possible to change this Fragment into a FragmentActivity.我不知道是否可以将此 Fragment 更改为 FragmentActivity。 I have looked for similar questionsn but I haven't find anything.我一直在寻找类似的问题,但我没有找到任何东西。 Thank you for any help感谢您的任何帮助
I think you forget to Commit the transaction, like this我认为您忘记提交交易,就像这样
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentActivity fragment = new DeterminaFrag();
FragmentManager fragmentManager = fragment.getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.nav_host_fragment_content_main, fragment);
fragmentManager.commit();
}
});
I hope it's can help your problem我希望它可以帮助你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.