【发布时间】:2016-02-03 14:51:12
【问题描述】:
我正在我的应用程序中创建一个水平的 RecyclerView。
它必须一次在屏幕上显示 2 个图像(因此每个图像的宽度必须是屏幕的 50%)。
现在它工作正常,但每个项目都占用了屏幕的所有宽度。
这是我的代码
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_main_ads);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(getActivity());
mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(tmp, R.layout.lv_main_screen);
mRecyclerView.setAdapter(adapter);
这是一个项目的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:id="@+id/iv_main_ad"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:scaleType="fitXY"
android:src="@drawable/baner_gasoline"
/>
</LinearLayout>
如您所见,我尝试使用 Layout_gravity="0.5", 但这无济于事。
我尝试指定 layout_width = ...dp,但我无法获得正好一半的屏幕。
我正在考虑将另一个 ImageView 添加到项目布局中,但在这种情况下我会遇到适配器问题,因为我想实现带圆圈(无限)的水平列表视图
这是我的适配器:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {
private List<Integer> mImages;
private int itemLayout;
public RecyclerViewAdapter(ArrayList<Integer> imageResourceIds, int itemLayout) {
this.mImages = imageResourceIds;
this.itemLayout = itemLayout;
}
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
return new MyHolder(v);
}
@Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.adIv.setImageResource(mImages.get(position));
}
@Override
public int getItemCount() {
return mImages.size();
}
public static class MyHolder extends RecyclerView.ViewHolder {
protected ImageView adIv;
private MyHolder(View v) {
super(v);
this.adIv = (ImageView) v.findViewById(R.id.iv_main_ad);
}
}
}
【问题讨论】:
-
"每个项目都占用了屏幕的所有宽度"。 "这里是一个项目的布局" ->
android:layout_width="match_parent" -
计算屏幕宽度并设置您要检查的最大元素数
-
@Pedro Oliveira,我尝试了 wrap_content,但没有任何改变
标签: android android-recyclerview