AndroidRecyclerView实现水平、垂直方向分割线-创新互联

android RecyclerView不像过去的ListView那样随意的设置水平方向的分割线,如果要实现RecyclerView的水平/垂直分割线,则需要继承自RecyclerView.ItemDecoration重写getItemOffsets方法,从而增加水平/垂直分割线。

网站制作、建网站找专业网站制作公司成都创新互联公司:定制网站、模板网站、仿站、小程序定制开发、软件开发、重庆APP开发公司等。做网站价格咨询成都创新互联公司:服务完善、10余年建站、值得信赖!网站制作电话:18980820575

写一个例子。


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 {
    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;
    }
  }
}

网站名称:AndroidRecyclerView实现水平、垂直方向分割线-创新互联
文章转载:http://pwwzsj.com/article/eppsc.html