如何使用RecyclerView构建Horizo​​ntal ListView?

时间:2015-02-11 17:11:26

标签: android android-layout android-recyclerview

我需要在Android应用程序中实现水平列表视图。我做了一些研究并遇到了How can I make a horizontal ListView in Android?Horizontal ListView in Android?但是,在Recyclerview发布之前就提出了这些问题。现在使用Recyclerview有更好的方法来实现吗?

13 个答案:

答案 0 :(得分:630)

  

现在使用Recyclerview有更好的方法来实现吗?

使用RecyclerView时,您需要指定负责在视图中布置每个项目的LayoutManagerLinearLayoutManager允许您指定方向,就像普通的LinearLayout一样。

要创建包含RecyclerView的水平列表,您可以执行以下操作:

LinearLayoutManager layoutManager
    = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view);
myList.setLayoutManager(layoutManager);

答案 1 :(得分:138)

 <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager" />

答案 2 :(得分:61)

完整示例

enter image description here

纵向RecyclerView和横向LinearLayoutManager之间的唯一真正区别在于您设置LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(horizontalLayoutManagaer); 的方式。这是代码片段。完整的例子如下。

gradle.build

这个更全面的例子是在my vertical RecyclerView answer之后建模的。

更新Gradle依赖项

确保您的应用implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support:recyclerview-v7:27.1.1' 文件中包含以下依赖项:

RecyclerView

您可以将版本号更新为the most current

创建活动布局

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/rvAnimals" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> 添加到xml布局。

activity_main.xml中

RecyclerView

创建项目布局

View中的每个项目都会在TextView上有一个彩色<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <View android:id="@+id/colorView" android:layout_width="100dp" android:layout_height="100dp"/> <TextView android:id="@+id/tvAnimalName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp"/> </LinearLayout> 。创建一个新的布局资源文件。

recyclerview_item.xml

RecyclerView

创建适配器

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> { private List<Integer> mViewColors; private List<String> mAnimals; private LayoutInflater mInflater; private ItemClickListener mClickListener; // data is passed into the constructor MyRecyclerViewAdapter(Context context, List<Integer> colors, List<String> animals) { this.mInflater = LayoutInflater.from(context); this.mViewColors = colors; this.mAnimals = animals; } // inflates the row layout from xml when needed @Override @NonNull public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.recyclerview_item, parent, false); return new ViewHolder(view); } // binds the data to the view and textview in each row @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { int color = mViewColors.get(position); String animal = mAnimals.get(position); holder.myView.setBackgroundColor(color); holder.myTextView.setText(animal); } // total number of rows @Override public int getItemCount() { return mAnimals.size(); } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { View myView; TextView myTextView; ViewHolder(View itemView) { super(itemView); myView = itemView.findViewById(R.id.colorView); myTextView = itemView.findViewById(R.id.tvAnimalName); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition()); } } // convenience method for getting data at click position public String getItem(int id) { return mAnimals.get(id); } // allows clicks events to be caught public void setClickListener(ItemClickListener itemClickListener) { this.mClickListener = itemClickListener; } // parent activity will implement this method to respond to click events public interface ItemClickListener { void onItemClick(View view, int position); } } 需要一个适配器来填充每行(水平项)中的视图和您的数据。创建一个新的java文件。

MyRecyclerViewAdapter.java

ListViews

注释

  • 虽然不是绝对必要,但我还提供了监听项目点击事件的功能。这在旧的public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener { private MyRecyclerViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // data to populate the RecyclerView with ArrayList<Integer> viewColors = new ArrayList<>(); viewColors.add(Color.BLUE); viewColors.add(Color.YELLOW); viewColors.add(Color.MAGENTA); viewColors.add(Color.RED); viewColors.add(Color.BLACK); ArrayList<String> animalNames = new ArrayList<>(); animalNames.add("Horse"); animalNames.add("Cow"); animalNames.add("Camel"); animalNames.add("Sheep"); animalNames.add("Goat"); // set up the RecyclerView RecyclerView recyclerView = findViewById(R.id.rvAnimals); LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(horizontalLayoutManager); adapter = new MyRecyclerViewAdapter(this, viewColors, animalNames); adapter.setClickListener(this); recyclerView.setAdapter(adapter); } @Override public void onItemClick(View view, int position) { Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on item position " + position, Toast.LENGTH_SHORT).show(); } } 中可用,并且是常见的需求。如果您不需要,可以删除此代码。

在活动中初始化RecyclerView

将以下代码添加到您的主要活动中。

MainActivity.java

ItemClickListener

注释

  • 请注意,该活动实现了我们在适配器中定义的onItemClick。这允许我们处理{{1}}。
  • 中的项目点击事件

完成

就是这样。您现在应该可以运行项目并获得与顶部图像类似的内容。

注释

答案 3 :(得分:11)

如果您想将RecyclerViewGridLayoutManager一起使用,这是实现水平滚动的方法。

recyclerView.setLayoutManager(
new GridLayoutManager(recyclerView.getContext(), rows, GridLayoutManager.HORIZONTAL, false));

答案 4 :(得分:9)

尝试构建水平ListView需要花费太多时间。我已经用两种方式解决了这个问题。

1.使用ViewPager,其适配器从PagerAdapter扩展。

2.通过如上所述使用RecyclerView。需要应用LayoutManager,如下面的代码所示:

LinearLayoutManager layoutManager
    = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view);
myList.setLayoutManager(layoutManager);

答案 5 :(得分:6)

如果您希望使用Horizo​​ntal Recycler View作为ViewPager,那么现在可以在支持库版本24.2.0中添加LinearSnapHelper的帮助。

首先将RecyclerView添加到您的活动/片段

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

就我而言,我在CardView

中使用了RecyclerView

<强> blog_row.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 

    xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_margin="15dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical">

            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/imageBlogPost"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:paddingBottom="15dp"
                android:src="@drawable/common_google_signin_btn_text_light_normal" />

            <TextView
                android:id="@+id/TitleTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
               android:layout_marginBottom="20dp"

                android:text="Post Title Here"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/descriptionTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Post Description Here"
                android:paddingBottom="15dp"
                android:textSize="14sp" />
        </LinearLayout>

    </android.support.v7.widget.CardView>

在您的活动/片段

    private RecyclerView mBlogList;




 LinearLayoutManager layoutManager
                    = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
            mBlogList = (RecyclerView) findViewById(R.id.blog_list);

            mBlogList.setHasFixedSize(true);
            mBlogList.setLayoutManager(layoutManager);

LinearSnapHelper snapHelper = new LinearSnapHelper() {
            @Override
            public int findTargetSnapPosition(RecyclerView.LayoutManager lm, int velocityX, int velocityY) {
                View centerView = findSnapView(lm);
                if (centerView == null)
                    return RecyclerView.NO_POSITION;

                int position = lm.getPosition(centerView);
                int targetPosition = -1;
                if (lm.canScrollHorizontally()) {
                    if (velocityX < 0) {
                        targetPosition = position - 1;
                    } else {
                        targetPosition = position + 1;
                    }
                }

                if (lm.canScrollVertically()) {
                    if (velocityY < 0) {
                        targetPosition = position - 1;
                    } else {
                        targetPosition = position + 1;
                    }
                }

                final int firstItem = 0;
                final int lastItem = lm.getItemCount() - 1;
                targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
                return targetPosition;
            }
        };
        snapHelper.attachToRecyclerView(mBlogList);

最后一步是将适配器设置为RecyclerView

mBlogList.setAdapter(firebaseRecyclerAdapter);

答案 6 :(得分:4)

随着RecyclerView库的发布,现在您可以轻松地将图像列表与文本对齐。您可以使用LinearLayoutManager指定列表方向,垂直或水平,如下所示。

enter image description here

您可以下载完整的working demo from this post

答案 7 :(得分:2)

    <HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:scrollbars="vertical|horizontal" />
</HorizontalScrollView>

答案 8 :(得分:2)

recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));

recyclerView.setAdapter(adapter);

答案 9 :(得分:1)

有一个名为HorizontalGridView的RecyclerView子类,您可以使用它来获得水平方向。 垂直方向VerticalGridView

答案 10 :(得分:1)

水平动态中的回收站视图。

回收者视图实现

RecyclerView musicList = findViewById(R.id.MusicList);

// RecyclerView musiclist = findViewById(R.id.MusicList1);
// RecyclerView musicLIST = findViewById(R.id.MusicList2);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
musicList.setLayoutManager(layoutManager);

String[] names = {"RAP", "CH SHB", "Faheem", "Anum", "Shoaib", "Laiba", "Zoki", "Komal", "Sultan","Mansoob Gull"};
musicList.setAdapter(new ProgrammingAdapter(names));'

用于回收站视图的适配器类,其中有一个用于保存该回收站视图的视图支架。

public class ProgrammingAdapter 
     extendsRecyclerView.Adapter<ProgrammingAdapter.programmingViewHolder> {

private String[] data;

public ProgrammingAdapter(String[] data)
{
    this.data = data;
}

@Override
public programmingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.list_item_layout, parent, false);

    return new programmingViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull programmingViewHolder holder, int position) {
    String title = data[position];
    holder.textV.setText(title);
}

@Override
public int getItemCount() {
    return data.length;
}

public class programmingViewHolder extends RecyclerView.ViewHolder{
    ImageView img;
    TextView textV;
    public programmingViewHolder(View itemView) {
        super(itemView);
        img =  itemView.findViewById(R.id.img);
        textV =  itemView.findViewById(R.id.textt);
    }
}

答案 11 :(得分:0)

尝试一下:

myrecyclerview.setLayoutManager(
        new LinearLayoutManager(getActivity(),
                                LinearLayoutManager.HORIZONTAL,false));
myrecyclerview.setAdapter(recyclerAdapter);

仅当您获得带有某些碎片的回收站视图时。

答案 12 :(得分:0)

  

水平和垂直都适用。

RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_recycler);
    recyclerView = (RecyclerView)findViewById(R.id.recyclerViewId);

    RecyclAdapter adapter = new RecyclAdapter();

    //Vertical RecyclerView
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);

    //Horizontal RecyclerView
    //recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));

    recyclerView.setAdapter(adapter);

}