RecyclerView 是Android L版本中新添加的一个用来取代ListView的SDK,它的灵活性与可替代性比listview更好。本文给大家介绍Android中RecyclerView实现横向滑动代码,一起看看吧。
android.support.v7.widget.RecyclerView
功能:RecyclerView横向滑动
控件:
Java类:RecyclerView、GalleryAdapter、List
1、主界面布局
<&#63;xml version="1.0" encoding="utf-8"&#63;>
2、子界面布局
<&#63;xml version="1.0" encoding="utf-8"&#63;>
3、Java代码
package com.info.activity; import android.app.Activity; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RecyclerActivity extends Activity { private RecyclerView mRecyclerView; private GalleryAdapter mAdapter; private ListmDatas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler); initDatas(); //得到控件 mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview_horizontal); //设置布局管理器 LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); mRecyclerView.setLayoutManager(linearLayoutManager); //设置适配器 mAdapter = new GalleryAdapter(this, mDatas); mRecyclerView.setAdapter(mAdapter); } private void initDatas() { mDatas = new ArrayList<>(Arrays.asList(R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher)); } public class GalleryAdapter extends RecyclerView.Adapter { private LayoutInflater mInflater; private List mDatas; public GalleryAdapter(Context context, List datats) { mInflater = LayoutInflater.from(context); mDatas = datats; } public class ViewHolder extends RecyclerView.ViewHolder { public ViewHolder(View arg0) { super(arg0); } ImageView mImg; TextView mTxt; } @Override public int getItemCount() { return mDatas.size(); } /** * 创建ViewHolder */ @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View view = mInflater.inflate(R.layout.activity_recycler_item, viewGroup, false); ViewHolder viewHolder = new ViewHolder(view); viewHolder.mImg = (ImageView) view .findViewById(R.id.id_index_gallery_item_image); return viewHolder; } /** * 设置值 */ @Override public void onBindViewHolder(final ViewHolder viewHolder, final int i) { viewHolder.mImg.setImageResource(mDatas.get(i)); } } }
以上所述是小编给大家介绍的Android中RecyclerView实现横向滑动代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!