设置适配器来设置RecyclerView的表现形式


public class RecycleViewActivity extends Activity {
@BindView(R.id.recycleview)
RecyclerView recycleview;
List<People> DataList;
@BindView(R.id.removeButton)
Button removeButton;
@BindView(R.id.addButton)
Button addButton;

//定义适配器
private MyAdapter adapter;

public void onCreate(Bundle bunle) {
super.onCreate( bunle );
setContentView( R.layout.recycleviewlayout );
ButterKnife.bind( this );

//初始化子项数组数据
DataList = new ArrayList<People>();
initData();
//设置适配器,同时传入数据
adapter = new MyAdapter( this, DataList );
recycleview.setAdapter( adapter );
//创建LinearLayoutManager 对象 这里使用 LinearLayoutManager 是线性布局的意思
LinearLayoutManager layoutmanager = new LinearLayoutManager( this );

//滚动至索引值处的子项,此方法需要使用new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false )构造方法
//第二个参数指定布局垂直或水平,false为是否倒序
//LinearLayoutManager layoutmanager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false );
//layoutmanager.scrollToPosition( 19 );

//设置子项布局为横向
//layoutmanager.setOrientation( LinearLayoutManager.HORIZONTAL );

//设置RecyclerView 布局
recycleview.setLayoutManager( layoutmanager );

//使用网格布局,第二个参数为每行拥有的子项数
//GridLayoutManager gridLayoutManager=new GridLayoutManager( this,4,GridLayoutManager.HORIZONTAL,false);
//recycleview.setLayoutManager(gridLayoutManager);

//添加分割线,第一个参数上下文,第二个参数为布局方向
recycleview.addItemDecoration( new DividerItemDecoration( this, DividerItemDecoration.VERTICAL ) );

//使用自定义接口在外部设置点击事件
adapter.setItemClickListener( new MyAdapter.ItemClickListener() {
@Override
public void onItemClick(int position) {
if (position > 2) {
Toast.makeText( RecycleViewActivity.this, "我是大于3的地方", Toast.LENGTH_SHORT ).show();
} else if (position == 2) {
Toast.makeText( RecycleViewActivity.this, "我是=于3的地方", Toast.LENGTH_SHORT ).show();
} else
Toast.makeText( RecycleViewActivity.this, "我是小于3的地方", Toast.LENGTH_SHORT ).show();
}
} );
}


//初始化数据方法,同时传入适配器
private void initData() {
for (int i = 0; i < 6; i++) {
DataList.add( new People( "真理惟一可靠的标准就是永远自相符合。 —— 欧文", R.drawable.ouwen ) );
DataList.add( new People( "土地是以它的肥沃和收获而被估价的;才能也是土地,不过它生产的不是" +
"粮食,而是真理。如果只能滋生瞑想和幻想的话,即使再大的才能也只是砂地或盐池,那上面连小草也长不出来的。"
, R.drawable.bielin ) );
}
}
//添加子项和删除子项
@OnClick({R.id.removeButton, R.id.addButton})
public void onViewClicked(View view) {
switch (view.getId(http://www.my516.com)) {
case R.id.removeButton:
adapter.removeItem( 0 );
break;
case R.id.addButton:
adapter.addItem( 0, new People( "添加的数据", R.drawable.bielin ) );
//还需要滚动至添加位置
recycleview.scrollToPosition( 0 );
break;
}
}
}

posted @ 2019-08-18 17:33  水至清明  阅读(396)  评论(0编辑  收藏  举报