毕加索的回收者视图间距

Recycler view spacing with picasso

我正在尝试建立类似画廊的东西,例如 this

为此,我使用了 RecyclerViewLayoutManager

首先,我创建了一个自定义布局来放置我的图像:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#FFFFFF"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/img"
        android:adjustViewBounds="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="2dp"/>
</LinearLayout>

然后我创建了一个自定义 Adapter,在那里我设置 Picasso 以在每一行下载图像:

@Override
public void onBindViewHolder(PhotosForPlantsAdapter.ViewHolder viewHolder, int i) {

    String urlFoto = photos.get(i).getPath();
    String url = "http://10.0.2.2:3000/" + urlFoto;

    viewHolder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);

    Picasso.with(context)
            .load(url)
            .resize(240, 120)
            .centerInside()
            .into(viewHolder.img);
}

我得到的结果是这样的:

我想使行居中,最后没有那么大的 space,图像似乎不是固定大小的缩略图,如 (100x100) 或 (20x20) 我该如何实现??

**Acitivity code:**


package com.example.afcosta.inesctec.pt.android;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.android.volley.VolleyError;
import com.example.afcosta.inesctec.pt.android.Adapters.PhotosForPlantsAdapter;
import com.example.afcosta.inesctec.pt.android.Adapters.SimiliarPlantsAdapter;
import com.example.afcosta.inesctec.pt.android.interfaces.IResult;
import com.example.afcosta.inesctec.pt.android.models.Photo;
import com.example.afcosta.inesctec.pt.android.models.Plant;
import com.example.afcosta.inesctec.pt.android.services.VolleyService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class FotosForPlant extends AppCompatActivity implements IResult {

    RecyclerView recyclerView;
    ArrayList<Photo> photos = new ArrayList<Photo>();

    VolleyService mVolleyService;
    IResult mResultCallback = null;
    final String GETREQUEST = "GETCALL";
    PhotosForPlantsAdapter adapter;
    String token;

    Double latitude = null;
    Double longitude = null;
    Double altitude = null;

    String time = null;


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

        String id = getIntent().getExtras().getString("plantId");

        Log.d("responseId",getIntent().getExtras().getString("plantId"));

        final String URL = "http://10.0.2.2:3000/fotos/" + id + "/plants";

        Log.d("resposta",URL);
        getFotosForPlantVolleyCallback();

        mVolleyService = new VolleyService(mResultCallback,this);

        checkForToken();
        mVolleyService.getDataVolley(GETREQUEST,URL,token);

        recyclerView = (RecyclerView)findViewById(R.id.gallery);
        recyclerView.setHasFixedSize(true);

        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),5);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new PhotosForPlantsAdapter(getApplicationContext(), photos);
        recyclerView.setAdapter(adapter);
    }

    void getFotosForPlantVolleyCallback(){
        mResultCallback = new IResult() {
            @Override
            public void notifySuccess(String requestType, JSONObject response) {
            }

            @Override
            public void notifySuccess(String requestType, JSONArray response) {
                Photo photo;
                Log.d("resposta","HEYYY1");
                // iterate over the JSONArray response
                for (int i=0; i < response.length(); i++) {
                    try {
                        JSONObject object = response.getJSONObject(i); // get the individual object from JSONArray
                        Log.d("objeto",object.toString());
                        int id = Integer.parseInt(object.getString("id")); // get the unique identifier from the object
                        if(latitude != null && longitude != null && altitude != null){
                            latitude = Double.parseDouble(object.getString("lat"));
                            longitude = Double.parseDouble(object.getString("lon"));
                            altitude = Double.parseDouble(object.getString("altitude"));
                        }
                        time = object.getString("date");
                        String path = object.getString("image");
                        photo = new Photo(path,id,latitude,longitude,altitude,time); // construct the object
                        photos.add(photo); // add the object to the arraylist so it can be used on the cardLayout


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void notifyError(String requestType, VolleyError error) {
                Log.d("resposta",error.toString());
            }
        };
    }

    @Override
    public void notifySuccess(String requestType, JSONObject response) {

    }

    @Override
    public void notifySuccess(String requestType, JSONArray response) {

    }

    @Override
    public void notifyError(String requestType, VolleyError error) {

    }

    public void checkForToken(){
        SharedPreferences sharedPref = getSharedPreferences("user",MODE_PRIVATE);
        String tokenKey = getResources().getString(R.string.token);
        if(sharedPref.contains(tokenKey)){ // check if a tokena already exist on sharedPreferences
            token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
        }
    }
}

布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.example.afcosta.inesctec.pt.android.FotosForPlant">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/gallery"
        android:layout_width="395dp"
        android:layout_height="387dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="5dp" />
</android.support.constraint.ConstraintLayout>

谢谢

GridLayoutManager 默认为每个项目提供相同的宽度。您为每个图像指定了固定宽度,结果得到了您所拥有的。

我不知道你的图片大小,但如果你将 .resize(240,120) 更改为 .resize(0,120) 你应该会得到想要的结果。

你的 RecyclerView 的宽度和高度也应该是 match_parent。

public final class SquareImageView extends ImageView {


public SquareImageView(Context context) {
    super(context);
}

public SquareImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}

<android.support.v7.widget.RecyclerView
    android:id="@+id/gallery"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="5dp" />

这些行将解决您的问题并使您的视图看起来像缩略图。还要确保在加载 picasso 或 glide 时将其调整为正方形。 (无论你用什么)

用法`

<LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:background="#FFFFFF"
     android:layout_width="match_parent"
     android:layout_height="wrap_content">
       <your.package.whereverclass.SquareImageView
         android:id="@+id/img"
         android:adjustViewBounds="true"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:layout_margin="2dp"/>
</LinearLayout>`