Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

android - How to indent the divider in a linear layout RecyclerView (ie, add padding, margin, or an inset only to the ItemDecoration)

Following this answer I was able to get a divider between the items of a vertical RecyclerView. However, I also wanted to slightly indent the divider lines.

I was able to do it by hard coding in an INDENT value in the RecyclerView.ItemDecoration subclass.

int INDENT = 20;

@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { 

    int left = parent.getPaddingLeft() + INDENT;
    int right = parent.getWidth() - parent.getPaddingRight() - INDENT;

    // ...

        divider.setBounds(left, top, right, bottom);

    // ...
} 

However, then I would have had to also mess with density independant pixels.

I finally found a solution similar to how it was done with ListView so I am sharing that as an answer below.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use inset

drawable/my_divider.xml

<inset xmlns:android="http://schemas.android.com/apk/res/android"
       android:insetLeft="40dp"
       android:insetRight="40dp" >

    <shape>
        <size android:height="1dp"/>
        <solid android:color="@color/recyclerview_divider" />
    </shape>

</inset>

Using the constructor that takes a resource id as shown in this answer, we can supply the id of our custom divider xml file.

recyclerView.addItemDecoration(
        new DividerItemDecoration(getActivity(), R.drawable.my_divider));

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...