使用Glide的RecyclerView不会崩溃,但也不会显示任何内容

时间:2018-03-18 16:05:45

标签: android android-recyclerview

主要活动

public  class MainActivity extends AppCompatActivity implements LocationEngineListener, PermissionsListener{
    private MapView mapView;
    private MapboxMap map;
    private PermissionsManager permissionsManager;
    private LocationLayerPlugin locationPlugin;
    private LocationEngine locationEngine;
    private Location originLocation;
    private Marker destinationMarker;
    private LatLng originCoord;
    private LatLng destinationCoord;
    private Point originPosition;
    private Point destinationPosition;
    private DirectionsRoute currentRoute;
    private static final String TAG = "DirectionsActivity";
    private NavigationMapRoute navigationMapRoute;
    private Button button;
    private ArrayList <String> mNames=new ArrayList<>();
    private ArrayList <String> mImages=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this,getString(R.string.token));
        setContentView(R.layout.activity_main);

        mapView=(MapView)findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        button = findViewById(R.id.startnav);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Point origin = originPosition;
                Point destination = destinationPosition;

                // Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
                // Set to null to use the default Android speech synthesizer
                String awsPoolId = null;

                boolean simulateRoute = true;

                NavigationViewOptions options = NavigationViewOptions.builder()
                        .origin(origin)
                        .destination(destination)
                        .awsPoolId(awsPoolId)
                        .shouldSimulateRoute(simulateRoute)
                        .build();

                // Call this method with Context from within an Activity
                NavigationLauncher.startNavigation(MainActivity.this, options);
            }
        });

        mapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(final MapboxMap mapboxMap) {
                map = mapboxMap;
                enableLocationPlugin();
                originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
                mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
                    @Override
                    public void onMapClick(@NonNull LatLng point) {
                        button.setEnabled(true);
                        button.setBackgroundResource(R.drawable.button_press);

                        if (destinationMarker != null) {
                            mapboxMap.removeMarker(destinationMarker);
                        }

                        destinationCoord = point;

                        destinationMarker = mapboxMap.addMarker(new MarkerOptions()
                                .position(destinationCoord)
                        );
                        destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
                        originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
                        getRoute(originPosition, destinationPosition);
                    }
                });
            }
        });

        getImages();
    }

    private void getImages() {
        Log.d(TAG, "initImageBitmaps: preparing bitmaps");
        mImages.add("https://c1.staticflickr.com/5/4636/25316407448_de5fbf183d_o.jpg");
        mNames.add("Havasu Falls");
        mImages.add("https://i.redd.it/tpsnoz5bzo501.jpg");
        mNames.add("Trondheim");

        mImages.add("https://i.redd.it/qn7f9oqu7o501.jpg");
        mNames.add("Portugal");

        mImages.add("https://i.redd.it/j6myfqglup501.jpg");
        mNames.add("Rocky Mountain National Park");

        mImages.add("https://i.redd.it/0h2gm1ix6p501.jpg");
        mNames.add("Mahahual");

        mImages.add("https://i.redd.it/k98uzl68eh501.jpg");
        mNames.add("Frozen Lake");

        mImages.add("https://i.redd.it/glin0nwndo501.jpg");
        mNames.add("White Sands Desert");

        mImages.add("https://i.redd.it/obx4zydshg601.jpg");
        mNames.add("Austrailia");

        mImages.add("https://i.imgur.com/ZcLLrkY.jpg");
        mNames.add("Washington");

        InitRecyclerView();
    }

    private void InitRecyclerView() {
        Log.d(TAG, "InitRecyclerView: init recyclerview");
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
        RecyclerView recyclerView=findViewById(R.id.myrecyclerview);
        recyclerView.setLayoutManager(linearLayoutManager);
        MainAdapter adapter=new MainAdapter(this,mNames,mImages);
        recyclerView.setAdapter(adapter);
    }

    @SuppressWarnings( {"MissingPermission"})
    private void enableLocationPlugin() {
        // verifica daca are permission si le cere
        if (PermissionsManager.areLocationPermissionsGranted(this)) {
            // Create an instance of LOST location engine
            initializeLocationEngine();

            locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
            locationPlugin.setLocationLayerEnabled(LocationLayerMode.TRACKING);
        } else {
            permissionsManager = new PermissionsManager( this);
            permissionsManager.requestLocationPermissions(this);
        }
    }

    @SuppressWarnings( {"MissingPermission"})
    private void initializeLocationEngine() {
        locationEngine = new LostLocationEngine(MainActivity.this);
        locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
        locationEngine.activate();

        Location lastLocation = locationEngine.getLastLocation();
        if (lastLocation != null) {
            originLocation = lastLocation;
            setCameraPosition(lastLocation);
        } else {
            locationEngine.addLocationEngineListener(this);
        }
    }

    private void setCameraPosition(Location location) {
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(location.getLatitude(), location.getLongitude()), 13));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {

    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            enableLocationPlugin();
        } else {
            finish();
        }
    }

    @Override
    @SuppressWarnings( {"MissingPermission"})
    public void onConnected() {
        locationEngine.requestLocationUpdates();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            originLocation = location;
            setCameraPosition(location);
            locationEngine.removeLocationEngineListener(this);
        }
    }

    @Override
    @SuppressWarnings( {"MissingPermission"})
    protected void onStart() {
        super.onStart();
        if (locationEngine != null) {
            locationEngine.requestLocationUpdates();
        }
        if (locationPlugin != null) {
            locationPlugin.onStart();
        }
        mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (locationEngine != null) {
            locationEngine.removeLocationUpdates();
        }
        if (locationPlugin != null) {
            locationPlugin.onStop();
        }
        mapView.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (locationEngine != null) {
            locationEngine.deactivate();
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    private void getRoute(Point origin, Point destination) {
        NavigationRoute.builder()
                .accessToken(Mapbox.getAccessToken())
                .origin(origin)
                .destination(destination)
                .build()
                .getRoute(new Callback<DirectionsResponse>() {
                    @Override
                    public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
                        // You can get the generic HTTP info about the response
                        Log.d(TAG, "Response code: " + response.code());
                        if (response.body() == null) {
                            Log.e(TAG, "No routes found, make sure you set the right user and access token.");
                            return;
                        } else if (response.body().routes().size() < 1) {
                            Log.e(TAG, "No routes found");
                            return;
                        }

                        currentRoute = response.body().routes().get(0);

                        // Draw the route on the map
                        if (navigationMapRoute != null) {
                            navigationMapRoute.removeRoute();
                        } else {
                            navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
                        }
                        navigationMapRoute.addRoute(currentRoute);
                    }

                    @Override
                    public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
                        Log.e(TAG, "Error: " + throwable.getMessage());
                    }
                });
    }
}

MainAdapter

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
    private static final String TAG="MainAdapter";
    private ArrayList <String> mNames=new ArrayList<>();
    private ArrayList <String> mImages=new ArrayList<>();
    private Context mContext;

    public MainAdapter(Context context , ArrayList<String> images, ArrayList<String> names) {
        mNames=names;
        mImages=images;
        mContext=context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.d(TAG, "onCreateViewHolder: called ");
        View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        Log.d(TAG, "onBindViewHolder: called");
        Glide.with(mContext)
                .asBitmap()
                .load(mImages.get(position))
                .into(holder.image);
        holder.name.setText(mNames.get(position));
        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: clicked on a image"+mNames.get(position));
                Toast.makeText(mContext,mNames.get(position),Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return mImages.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder
    {
        CircleImageView image;
        TextView name;

        public ViewHolder(View itemView) {
            super(itemView);
            image=itemView.findViewById(R.id.image_view);
            name=itemView.findViewById(R.id.name);
        }
    }
}

这是activitymain布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:mapbox="http://schemas.android.com/apk/res-auto"
    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="com.example.matei.meetup.MainActivity">

<android.support.v7.widget.RecyclerView
    android:id="@+id/myrecyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" />

    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        mapbox:mapbox_cameraTargetLat="38.9098"
        mapbox:mapbox_cameraTargetLng="-77.0295"
        mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
        mapbox:mapbox_cameraZoom="12" >

    </com.mapbox.mapboxsdk.maps.MapView>

    <Button
        android:id="@+id/startnav"
        android:layout_width="316dp"
        android:layout_height="41dp"
        android:layout_margin="20px"
        android:background="@drawable/button_unpressed"
        android:padding="5px"
        android:text="Start navigation"
        android:textColor="@color/mapboxWhite"
        mapbox:layout_constraintBottom_toBottomOf="parent"
        mapbox:layout_constraintLeft_toLeftOf="parent"
        mapbox:layout_constraintRight_toRightOf="parent"
        mapbox:layout_constraintTop_toBottomOf="@+id/mapView"
        mapbox:layout_constraintVertical_bias="1.0" />

</android.support.constraint.ConstraintLayout>

这是另一个布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="1dp">

    <android.support.v7.widget.CardView
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:cardCornerRadius="4dp"
        app:cardElevation="1dp"
        app:cardMaxElevation="2dp"
        android:layout_centerInParent="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <de.hdodenhof.circleimageview.CircleImageView
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:scaleType="centerCrop"
                android:layout_centerHorizontal="true"
                android:id="@+id/image_view"
                android:src="@mipmap/ic_launcher"/>

            <TextView
                android:id="@+id/name"
                android:layout_width="wrap_content"
                android:layout_height="18dp"
                android:text="Chestie"
                android:layout_below="@+id/image_view"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:layout_marginTop="5dp"
                android:textColor="#000"
                android:layout_marginBottom="5dp" />
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</RelativeLayout>

应用程序在运行时不会崩溃,它只显示没有RecyclerView的地图。在我的gradle文件中,我包含了我需要的依赖项。我试着搞乱gradle文件,似乎没什么用。在我的logcat中,我有以下java.io.FileNotFoundException-No such file or directory

1 个答案:

答案 0 :(得分:0)

库de.hdodenhof.circleimageview.CircleImageView中的问题。检查一下

to_csv

如果您需要圈出imageview,可以使用带有imageview的滑行变换 https://github.com/hdodenhof/CircleImageView/issues/121 示例滑行v4:

RequestOptions options = new RequestOptions(); 
options.CircleCrop();
 Glide.with(fragment)
.load(url)
.apply(options)
.into(imageView);