Android RecyclerView不像过去的ListView那样随意的设置水平方向的分割线,如果要实现RecyclerView的水平/垂直分割线,则需要继承自RecyclerView.ItemDecoration重写getItemOf
Android RecyclerView不像过去的ListView那样随意的设置水平方向的分割线,如果要实现RecyclerView的水平/垂直分割线,则需要继承自RecyclerView.ItemDecoration重写getItemOffsets方法,从而增加水平/垂直分割线。
写一个例子。
MainActivity.Java:
package zhangphil.app;import android.content.Context;import android.graphics.Color;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.StaggeredGridLayoutManager;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView); // 两列 int spanCount = 2; // StaggeredGridLayoutManager管理RecyclerView的布局。 StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(mLayoutManager); //为RecyclerView增加分割线,水平和垂直方向都有。增加分割线值比如为32。 RecyclerViewItemDecoration decoration = new RecyclerViewItemDecoration(32); mRecyclerView.addItemDecoration(decoration); RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(this); mRecyclerView.setAdapter(mAdapter); } private class ItemViewHolder extends RecyclerView.ViewHolder { private TextView text; public ItemViewHolder(View itemView) { super(itemView); text = (TextView) itemView.findViewById(android.R.id.text1); text.setTextColor(Color.WHITE); } } public class RecyclerViewAdapter extends RecyclerView.Adapter<ItemViewHolder> { private Context context; public RecyclerViewAdapter(Context context) { super(); this.context = context; } @Override public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { View view = View.inflate(context, android.R.layout.simple_list_item_1, null); view.setBackgroundColor(Color.RED); ItemViewHolder holder = new ItemViewHolder(view); return holder; } @Override public void onBindViewHolder(ItemViewHolder viewHolder, int pos) { viewHolder.text.setText(String.valueOf(pos)); } @Override public int getItemCount() { return 15; } }}
--结束END--
本文标题: Android RecyclerView实现水平、垂直方向分割线
本文链接: https://lsjlt.com/news/222258.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0