代码在RecyclerView(一)的基础上做修改实现类似ViewPager左右滑动显示效果,
直接上代码:
A activity_main.xml
B MainActivity.java
package com.example.aaaaa.recyclerviewtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
// 设置布局管理器
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayout.HORIZONTAL);
recyclerView.setLayoutManager(linearLayoutManager);
// 设置item添加、移除动画
recyclerView.setItemAnimator(new DefaultItemAnimator());
// 添加分割线
recyclerView.addItemDecoration(new DividerItemDecoration(
getApplicationContext(), DividerItemDecoration.VERTICAL));
//实现viewPager效果核心代码
new PagerSnapHelper().attachToRecyclerView(recyclerView);
// 添加adapter
RecyclerView.Adapter adapter = new RecyclerViewTestAdapter();
recyclerView.setAdapter(adapter);
}
}
【RecyclerView(二)(+SnapHelper实现类似ViewPager效果)】C recyclerview_item.xml
D RecyclerViewTestAdapter.java
package com.example.aaaaa.recyclerviewtest;
import android.content.Context;
import android.content.res.Resources;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by 49375 on 2019/3/19.
*/
public class RecyclerViewTestAdapter extends RecyclerView.Adapter {
@Override
public RecyclerViewTestAdapter.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, null);
MyHolder myHolder = new MyHolder(view);
return myHolder;
}@Override
public void onBindViewHolder(RecyclerViewTestAdapter.MyHolder holder, int position) {
holder.textView1.setText("pos:" + position);
}@Override
public int getItemCount() {
return 10;
}// ViewHolder用来初始化控件
public class MyHolder extends RecyclerView.ViewHolder {
TextView textView1;
public MyHolder(View itemView) {
super(itemView);
textView1 = (TextView)itemView.findViewById(R.id.recyclerview_item_text);
// 设置显示宽高
float[] size = getDeviceDisplaySize(itemView.getContext());
itemView.setMinimumWidth((int) size[0]);
}publicfloat[] getDeviceDisplaySize(Context context) {
Resources resources = context.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
float[] size = new float[2];
size[0] = width;
size[1] = height;
return size;
}
}
}