[英]Change activity in a navigation Drawer with Fragment and FragmentActivity
我是一名新手程序員,我正在嘗試學習 Android 的一些東西。 我遵循一些教程,現在我有一個導航抽屜應用程序。 到目前為止,我已經使用菜單中的按鈕管理了布局的更改。 現在我想創建一個 map 定位器,我按照本教程進行操作。 現在我想單擊一個按鈕,將我帶到這個新的活動,我可以在其中跟蹤 position。
我的代碼是: 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
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
<?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
<?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
<?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>
我認為問題出在這段代碼中(實際上它甚至沒有編譯)
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);
}
});
我不知道是否可以將此 Fragment 更改為 FragmentActivity。 我一直在尋找類似的問題,但我沒有找到任何東西。 感謝您的任何幫助
我認為您忘記提交交易,就像這樣
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();
}
});
我希望它可以幫助你的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.