Android - 解除对话框片段

时间:2017-09-23 12:13:20

标签: android refresh android-dialogfragment dismiss dialogfragment

我有一个包含imageview的活动。 当我点击该图像时,会显示一个对话框片段,其中包含html内容和一个按钮。 当我单击该按钮时,我想关闭此对话框片段。 我尝试使用函数dismiss()但它没用,对话框片段没有关闭,它实际刷新,有时在按钮上触摸3-4次后关闭!。

以下是我的活动代码:

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;
        }
    });
}

}

这是对话框片段的代码:

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
}

}

这是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>

1 个答案:

答案 0 :(得分:0)

onTouchListener中的backButton替换为onClickListener

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

单击侦听器是按钮的推荐方法。希望这会使按钮和对话框片段的行为更具可预测性和确定性。