0

J'ai une activité qui comprend une vue d'image. Lorsque je clique sur cette image, un fragment de dialogue est affiché composé de contenu html et un bouton. Lorsque je clique sur ce bouton, je veux fermer ce fragment de dialogue. J'ai essayé d'utiliser la fonction dismiss() mais c'était inutile, le fragment de dialogue ne se ferme pas, il rafraîchit réellement, et se ferme parfois après 3-4 touches sur le bouton !.Android-Dismissing un fragment de dialogue

Voici mon code pour l'activité:

public class MainActivity extends FragmentActivity implements OnMapReadyCallback,GeneralCallback { 
private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1; 
private Polyline line; 
private GoogleMap googleMap; 
private Controller controller; 
private JSONObject UserDetails; 
private JSONArray routePath; 
private JSONArray stopPoints; 
private List<LatLng> pointsRoutePath; 
private List<LatLng> pointsStopPoints; 

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

    controller=new Controller(this); 

    requireLocationPermissions(); 

    initializeGoogleMap(); 

    configureImage(); 
} 


@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { 
    switch (requestCode) { 
     case REQUEST_ID_MULTIPLE_PERMISSIONS: { 
      Map<String, Integer> perms = new HashMap<String, Integer>(); 
      // Initialize the map with both permissions 
      perms.put(android.Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED); 
      perms.put(android.Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); 

      // Fill with actual results from user 
      if (grantResults.length > 0) { 
       for (int i = 0; i < permissions.length; i++) 
        perms.put(permissions[i], grantResults[i]); 
      } 
     } 
    } 
} 

@Override 
public void onMapReady(GoogleMap googleMap) { 
    setZoomedLocation(googleMap); 
    controller.getUserDetails(); 
    this.googleMap=googleMap; 
} 

//This function is used to require location permissions from the user during run time. 
private void requireLocationPermissions(){ 
    RequestPermissions requestPermissions = new RequestPermissions(this, this); 
    requestPermissions.checkAndRequestPermissions(); 
} 

//This function is used to initialize Google Map Fragment 
private void initializeGoogleMap(){ 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
} 

@Override 
public void VolleyResponse(JSONObject response, String data) { 
    if (data.equals("getUserDetails")) { 
     try { 
      if(response!=null){ 
       Log.i("onResponse","Callback"); 
       UserDetails=response.getJSONObject("InnerData").getJSONObject("user"); 
       routePath=getRoutePath(); 
       stopPoints=getStopPoints(); 
       decodePoly(); 
       drawPath(); 
       putStopMarkers(); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
    else if(data.equals("AboutUs")){ 
     Log.i("onResponse","Callback"); 
     AboutUs aboutUs = (AboutUs) getSupportFragmentManager().findFragmentByTag("AboutUs"); 
     if(aboutUs!=null && response!=null) 
      aboutUs.initializeContent(response); 
    } 
} 

@Nullable 
private JSONArray getRoutePath(){ 
    try { 
     if(UserDetails!=null) 
      return UserDetails.getJSONObject("bus").getJSONObject("route").getJSONArray("routePath"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

@Nullable 
private JSONArray getStopPoints(){ 
    try { 
     if(UserDetails!=null) 
      return UserDetails.getJSONObject("bus").getJSONObject("route").getJSONArray("stop_points"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 


private void drawPath() { 
    if (line != null) { 
     googleMap.clear(); 
    } 

    for (int z = 0; z < pointsRoutePath.size() - 1; z++) { 
     LatLng src = pointsRoutePath.get(z); 
     LatLng dest = pointsRoutePath.get(z + 1); 
     line = googleMap.addPolyline(new PolylineOptions() 
       .add(new LatLng(src.latitude, src.longitude), 
         new LatLng(dest.latitude, dest.longitude)) 
       .width(60).color(Color.rgb(47,191,220)).geodesic(true)); 
    } 
} 

private void putStopMarkers(){ 
    for(int i=0;i<pointsStopPoints.size();i++){ 
     LatLng point=new LatLng(pointsStopPoints.get(i).latitude,pointsStopPoints.get(i).longitude); 
     Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.stop_marker); 
     bitmap=Bitmap.createScaledBitmap(bitmap,bitmap.getWidth()/10,bitmap.getHeight()/10,false); 
     googleMap.addMarker(new MarkerOptions().position(point).icon(BitmapDescriptorFactory.fromBitmap(bitmap))); 
    } 
} 

private void decodePoly(){ 
    pointsRoutePath = new ArrayList<>(); 
    pointsStopPoints = new ArrayList<>(); 

    for (int i=0;i<routePath.length();i++){ 
     try { 
      LatLng point=new LatLng(routePath.getJSONObject(i).getDouble("lat"),routePath.getJSONObject(i).getDouble("lng")); 
      pointsRoutePath.add(point); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 

    for (int i=0;i<stopPoints.length();i++){ 
     try { 
      LatLng point=new LatLng(stopPoints.getJSONObject(i).getDouble("lat"),stopPoints.getJSONObject(i).getDouble("lng")); 
      pointsStopPoints.add(point); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

private void setZoomedLocation(GoogleMap googleMap){ 
    LocListener locationListener=new LocListener(this); 

    //checks if location permission is granted 
    if(locationListener.canGetLocation()){ 
     googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(locationListener.getLatitude(), locationListener.getLongitude()), 14.0f)); 
    } 
    LatLng point=new LatLng(locationListener.getLatitude(),locationListener.getLongitude()); 

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.marker_hi); 
    bitmap=Bitmap.createScaledBitmap(bitmap,bitmap.getWidth()/10,bitmap.getHeight()/10,false); 

    googleMap.addMarker(new MarkerOptions().position(point).icon(BitmapDescriptorFactory.fromBitmap(bitmap))); 
} 

private void configureImage(){ 
    ImageView aboutUs=findViewById(R.id.AboutUs); 
    aboutUs.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      AboutUs aboutUsFragment = new AboutUs(); 
      // Show DialogFragment 
      aboutUsFragment.show(getSupportFragmentManager(), "AboutUs"); 
      controller.aboutUS(); 
      return true; 
     } 
    }); 
} 

}

et voici mon code pour le fragment de dialogue:

public class AboutUs extends DialogFragment{ 
Controller controller; 
private View view; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    view = inflater.inflate(R.layout.about_us, container, false); 
    controller = new Controller(getActivity()); 
    configureBackButton(); 
    return view; 
} 

private void configureBackButton(){ 
    Button backButton=view.findViewById(R.id.backButton); 
    backButton.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      Log.i("onTouch","onTouch"); 
      getDialog().dismiss(); 
      return true; 
     } 
    }); 
} 

public void initializeContent(JSONObject response){ 
    try { 
     String content=response.getJSONArray("InnerData").getJSONObject(0).getString("content"); 
     WebView webView = view.findViewById(R.id.html); 
     webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
} 

@Override 
public void onResume() { 
    super.onResume(); 
    controller.aboutUS(); 
} 

@Override 
public void onDismiss(DialogInterface frag) { 
    dismissAllowingStateLoss(); 
    // DO Something 
} 

}

est ici about_us.xml

<?xml version="1.0" encoding="utf-8"?> 


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/RelativeLayout" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_marginLeft="0dp" 
    android:layout_marginTop="250dp"> 

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 
    <WebView 
     android:id="@+id/html" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true" 
     /> 
    </ScrollView> 

    <Button 
     android:id="@+id/backButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="25dp" 
     android:background="@drawable/button_style" 
     android:gravity="top|bottom|center" 
     android:padding="10dp" 
     android:text="Dismiss" 
     android:textColor="#ffffff" 
     android:paddingBottom="20dp"/> 

</RelativeLayout> 
+0

pouvez-vous partager les journaux – GeekWithGlasses

+0

mettre le code "about_us.xml" ainsi. –

Répondre

0

Remplacez le onTouchListener dans votre backButton par un onClickListener.

backButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       getDialog().dismiss(); 
      } 
     }); 

L'écoute des clics est l'approche recommandée pour les boutons. Heureusement, cela rendrait le comportement du bouton et du fragment de dialogue plus prévisible et déterministe.

+0

c'est toujours le même problème. –

+0

@AhmedKhairy essaie de remplacer 'getDialog(). Dismiss()' avec simplement 'dismiss()'. –

+0

toujours pas de différence –