一个简单的 Recycleview + GridLayoutManager 显示图片的例子

it2024-12-22  8

显示效果

Recycleview  XML 布局文件

(该文件内容有省略)

<android.support.v7.widget.RecyclerView android:id="@+id/recycleview" android:paddingLeft="18dp" android:paddingRight="18dp" android:layout_width="match_parent" android:layout_height="match_parent"/>

ITEM 项XML 布局文件

<?xml version="1.0" encoding="utf-8"?> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/iv" android:layout_height="wrap_content" android:padding="8dp" android:layout_width="match_parent" />

Aapter 代码 

构造函数中传入要显示的图片的URL。由 Gide  图片库负责图片的显示。

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<String> mDataset; private Context mContext; public static class ViewHolder extends RecyclerView.ViewHolder { ImageView iv; public ViewHolder(View v) { super(v); iv = (ImageView) v.findViewById(R.id.iv); } } public MyAdapter(List<String> myDataset) { mDataset = myDataset; } @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v; mContext = parent.getContext(); v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.image_item, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder holder, final int position) { ImageView iv = holder.iv; Glide.with(mContext).load(mDataset.get(position)).into(iv); } @Override public int getItemCount() { return mDataset.size(); } }

Ativity 代码

public class EditorActivity extends Activity { private static String TAG = "EditorActivity"; private RecyclerView recyclerView; private GridLayoutManager gridLayoutManager; @Override public void onCreate(Bundle bundle) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(bundle); this.setContentView(R.layout.post_commit_main); recyclerView = findViewById(R.id.recycleview); gridLayoutManager = new GridLayoutManager(this.getApplicationContext(), 3); recyclerView.setLayoutManager(gridLayoutManager); // 需要传入图片URL MyAdapter adapter = new MyAdapter(new ArrayList<String>()); recyclerView.setAdapter(adapter); } }

遇到的问题

一开始 item 项 imageView 的布局文件中 layout_width 赋值为  wrap_content

图片行与行之间的空白很大。

改为 match_parent 之后问题解决。

 

最新回复(0)