├── sample
├── .gitignore
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── styles.xml
│ │ │ └── layout
│ │ │ │ ├── item_vertical_brand1.xml
│ │ │ │ ├── item_vertical_brand2.xml
│ │ │ │ ├── activity_linear.xml
│ │ │ │ ├── activity_staggered_recycler.xml
│ │ │ │ ├── activity_grid_recycler.xml
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── bosong
│ │ │ │ └── sample
│ │ │ │ ├── model
│ │ │ │ └── BrandData.java
│ │ │ │ ├── Utils.java
│ │ │ │ ├── viewholder
│ │ │ │ ├── VerticalBrandViewHolder2.java
│ │ │ │ ├── VerticalBrandViewHolder1.java
│ │ │ │ └── SViewHolderBase.java
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── adapter
│ │ │ │ ├── VerticalAdapter.java
│ │ │ │ └── StaggeredAdapter.java
│ │ │ │ └── activity
│ │ │ │ ├── LinearActivity.java
│ │ │ │ ├── VerticalGridRecyclerActivity.java
│ │ │ │ └── StaggeredRecyclerActivity.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── bosong
│ │ │ └── sample
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── bosong
│ │ └── sample
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
├── build.gradle
├── gradlew.bat
└── gradlew
├── library
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ └── values
│ │ │ │ └── strings.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── bosong
│ │ │ └── commonitemdecoration
│ │ │ └── SCommonItemDecoration.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── bosong
│ │ │ └── commonitemdecoration
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── bosong
│ │ └── commonitemdecoration
│ │ └── ExampleInstrumentedTest.java
├── build.gradle
└── proguard-rules.pro
├── demo.gif
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── README.md
├── gradlew.bat
├── README_zh.md
├── gradlew
└── LICENSE.txt
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/demo.gif
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':library', ':sample'
2 | project(':sample').projectDir = new File('sample')
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CommonItemDecoration
3 |
4 |
--------------------------------------------------------------------------------
/sample/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ibosong/CommonItemDecoration/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Sep 16 14:21:22 CST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/sample/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Mar 22 16:50:35 CST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/model/BrandData.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample.model;
2 |
3 | /**
4 | * Created by boson on 2017/3/21.
5 | */
6 |
7 | public class BrandData {
8 | public BrandData(String brandName){
9 | this.brandName = brandName;
10 | }
11 | public String brandName;
12 | }
13 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CommonItemDecoration
3 | VerticalGridRecyclerActivity
4 | StaggeredRecyclerActivity
5 | LinearActivity
6 |
7 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/Utils.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample;
2 |
3 | import android.content.Context;
4 |
5 | /**
6 | * Created by boson on 2017/3/10.
7 | */
8 |
9 | public class Utils {
10 | private Utils(){}
11 |
12 | public static int dip2px(Context context, float dpValue) {
13 | final float scale = context.getApplicationContext().getResources().getDisplayMetrics().density;
14 | return (int) (dpValue * scale + 0.5f);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/sample/src/test/java/com/bosong/sample/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/item_vertical_brand1.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
11 |
12 |
--------------------------------------------------------------------------------
/library/src/test/java/com/bosong/commonitemdecoration/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.bosong.commonitemdecoration;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/item_vertical_brand2.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
13 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/viewholder/VerticalBrandViewHolder2.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample.viewholder;
2 |
3 | import android.view.ViewGroup;
4 | import android.widget.TextView;
5 |
6 | import com.bosong.sample.model.BrandData;
7 | import com.bosong.sample.R;
8 |
9 | /**
10 | * Created by boson on 2017/3/12.
11 | */
12 |
13 | public class VerticalBrandViewHolder2 extends SViewHolderBase {
14 | public TextView brandNameTv;
15 |
16 | public VerticalBrandViewHolder2(ViewGroup parent) {
17 | super(parent, R.layout.item_vertical_brand2);
18 | brandNameTv = findViewById(R.id.tv_preheat_brand);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/viewholder/VerticalBrandViewHolder1.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample.viewholder;
2 |
3 | import android.view.ViewGroup;
4 | import android.widget.TextView;
5 |
6 | import com.bosong.sample.model.BrandData;
7 | import com.bosong.sample.R;
8 |
9 | /**
10 | * Created by boson on 2017/3/10.
11 | */
12 |
13 | public class VerticalBrandViewHolder1 extends SViewHolderBase {
14 |
15 | public volatile TextView brandNameTv;
16 |
17 | public VerticalBrandViewHolder1(ViewGroup itemView) {
18 | super(itemView, R.layout.item_vertical_brand1);
19 | brandNameTv = findViewById(R.id.tv_brand);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | #built application files
2 | *.apk
3 | *.ap_
4 |
5 |
6 | # files for the dex VM
7 | *.dex
8 |
9 |
10 | # Java class files
11 | *.class
12 |
13 |
14 | # generated files
15 | bin/
16 | gen/
17 |
18 |
19 | # Local configuration file (sdk path, etc)
20 | local.properties
21 |
22 |
23 | # Windows thumbnail db
24 | Thumbs.db
25 |
26 |
27 | # OSX files
28 | .DS_Store
29 |
30 |
31 | # Eclipse project files
32 | .classpath
33 | .project
34 |
35 |
36 | # Android Studio
37 | .idea/
38 | captures/
39 | #.idea/workspace.xml - remove # and delete .idea if it better suit your needs.
40 | .gradle
41 | build/
42 |
43 |
44 | # Signing files
45 | .signing/
46 |
47 |
48 | # User-specific configurations
49 | *.iml
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_linear.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_staggered_recycler.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/viewholder/SViewHolderBase.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample.viewholder;
2 |
3 | import android.support.annotation.IdRes;
4 | import android.support.v7.widget.RecyclerView;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 |
9 | /**
10 | * Created by boson on 2017/3/10.
11 | */
12 |
13 | public class SViewHolderBase extends RecyclerView.ViewHolder{
14 | public SViewHolderBase(View itemView) {
15 | super(itemView);
16 | }
17 |
18 | public SViewHolderBase(ViewGroup parent, int layoutId) {
19 | super(LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false));
20 | }
21 |
22 | protected T findViewById(@IdRes int id){
23 | return (T) itemView.findViewById(id);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/sample/src/androidTest/java/com/bosong/sample/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.bosong.brandlistdemo", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/com/bosong/commonitemdecoration/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.bosong.commonitemdecoration;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.bosong.commonitemdecoration.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_grid_recycler.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 28
5 | buildToolsVersion "28.0.3"
6 |
7 | defaultConfig {
8 | minSdkVersion 15
9 | targetSdkVersion 28
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 |
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | compile fileTree(dir: 'libs', include: ['*.jar'])
26 | androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.2', {
27 | exclude group: 'com.android.support', module: 'support-annotations'
28 | })
29 | compile 'com.android.support:appcompat-v7:28.0.0'
30 | compile 'com.android.support:recyclerview-v7:28.0.0'
31 | testCompile 'junit:junit:4.12'
32 | }
33 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Program\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Program\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
15 |
20 |
25 |
26 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 | buildToolsVersion "28.0.3"
6 | defaultConfig {
7 | applicationId 'com.bosong.sample'
8 | minSdkVersion 15
9 | targetSdkVersion 28
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | productFlavors {
21 | }
22 | }
23 |
24 | dependencies {
25 | compile fileTree(include: ['*.jar'], dir: 'libs')
26 | androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.2', {
27 | exclude group: 'com.android.support', module: 'support-annotations'
28 | })
29 | compile project(':library')
30 | compile 'com.android.support:appcompat-v7:28.0.0'
31 | compile 'com.android.support.constraint:constraint-layout:2.0.0-beta2'
32 | testCompile 'junit:junit:4.12'
33 | }
34 |
35 | repositories {
36 | google()
37 | }
38 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
22 |
24 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # A custom ItemDecoration which appends dividers(with same thickness) between items(with same dimension) for RecyclerView
2 |
3 | [中文版](README_zh.md)
4 |
5 | When using RecyclerView, we often need set dividers between items. Usually, we set right_margin to the root layout of each item. In this way, you hava to set a left_margin to the RecyclerView to make the list looks symmetric. There's another way to do this. We can customize ItemDecoration and override the getItemOffsets method. Also, set `right` to the parameter `outRect` to each item. And add `left` to the first item. In this way, you will find that the width between the first and other items are not the same.
6 |
7 | So this `SCommonItemDecoration` is the best way. It supports LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager, also supports different orientation.
8 |
9 | ### Usage
10 |
11 | ``` java
12 | mRecyclerView.addItemDecoration(
13 | SCommonItemDecoration.builder()
14 | .type(TYPE_1)
15 | .prop(verticalSpace, horizaontalSpace, hasVerticalEdge, hasHorizontalEdge)
16 | .buildType()
17 | .type(TYPE_2)
18 | .prop(verticalSpace, horizaontalSpace, hasVerticalEdge, hasHorizontalEdge)
19 | .buildType()
20 | .build()
21 | );
22 | ```
23 |
24 | That's all, enjoy youself.
25 |
26 | 
27 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample;
2 |
3 | import android.content.Intent;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.view.View;
7 |
8 | import com.bosong.sample.activity.LinearActivity;
9 | import com.bosong.sample.activity.StaggeredRecyclerActivity;
10 | import com.bosong.sample.activity.VerticalGridRecyclerActivity;
11 |
12 | public class MainActivity extends AppCompatActivity {
13 |
14 | @Override
15 | protected void onCreate(Bundle savedInstanceState) {
16 | super.onCreate(savedInstanceState);
17 | setContentView(R.layout.activity_main);
18 |
19 | findViewById(R.id.btn_vertical_recycler).setOnClickListener(new View.OnClickListener() {
20 | @Override
21 | public void onClick(View v) {
22 | onVerticalRecyclerClick();
23 | }
24 | });
25 |
26 | findViewById(R.id.btn_staggered_recycler).setOnClickListener(new View.OnClickListener() {
27 | @Override
28 | public void onClick(View v) {
29 | onStaggeredRecyclerClick();
30 | }
31 | });
32 |
33 | findViewById(R.id.btn_linear_recycler).setOnClickListener(new View.OnClickListener() {
34 | @Override
35 | public void onClick(View v) {
36 | onLinearRecyclerClick();
37 | }
38 | });
39 | }
40 |
41 | private void onVerticalRecyclerClick(){
42 | Intent it = new Intent();
43 | it.setClass(this, VerticalGridRecyclerActivity.class);
44 | startActivity(it);
45 | }
46 |
47 | private void onStaggeredRecyclerClick(){
48 | Intent it = new Intent();
49 | it.setClass(this, StaggeredRecyclerActivity.class);
50 | startActivity(it);
51 | }
52 |
53 | private void onLinearRecyclerClick() {
54 | Intent it = new Intent();
55 | it.setClass(this, LinearActivity.class);
56 | startActivity(it);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/adapter/VerticalAdapter.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample.adapter;
2 |
3 | import android.support.v7.widget.RecyclerView;
4 | import android.view.View;
5 | import android.view.ViewGroup;
6 |
7 | import com.bosong.sample.model.BrandData;
8 | import com.bosong.sample.viewholder.VerticalBrandViewHolder1;
9 | import com.bosong.sample.viewholder.VerticalBrandViewHolder2;
10 |
11 | import java.util.List;
12 |
13 | /**
14 | * Created by boson on 2017/3/21.
15 | */
16 |
17 | public class VerticalAdapter extends RecyclerView.Adapter {
18 | public static final int TYPE_1 = 0;
19 | public static final int TYPE_2 = 1;
20 | private List mData;
21 | public VerticalAdapter(List data){
22 | mData = data;
23 | }
24 |
25 | @Override
26 | public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
27 | if(viewType == 0){
28 |
29 | return new VerticalBrandViewHolder1(parent);
30 | }else{
31 | return new VerticalBrandViewHolder2(parent);
32 | }
33 | }
34 |
35 | @Override
36 | public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
37 | if(mData == null || mData.size() <= position){
38 | return;
39 | }
40 |
41 | if(holder instanceof VerticalBrandViewHolder1){
42 | final VerticalBrandViewHolder1 holder1 = (VerticalBrandViewHolder1) holder;
43 | holder1.brandNameTv.setText(mData.get(position).brandName);
44 | }else{
45 | VerticalBrandViewHolder2 holder2 = (VerticalBrandViewHolder2) holder;
46 | holder2.brandNameTv.setText(mData.get(position).brandName);
47 | }
48 | }
49 |
50 | @Override
51 | public int getItemCount() {
52 | return mData != null ? mData.size() : 0;
53 | }
54 |
55 | @Override
56 | public int getItemViewType(int position) {
57 | if(position < 10){
58 | return TYPE_1;
59 | }else{
60 | return TYPE_2;
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/activity/LinearActivity.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample.activity;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.support.v7.widget.LinearLayoutManager;
6 | import android.support.v7.widget.RecyclerView;
7 |
8 | import com.bosong.commonitemdecoration.SCommonItemDecoration;
9 | import com.bosong.sample.R;
10 | import com.bosong.sample.Utils;
11 | import com.bosong.sample.adapter.VerticalAdapter;
12 | import com.bosong.sample.model.BrandData;
13 |
14 | import java.util.ArrayList;
15 | import java.util.List;
16 |
17 | public class LinearActivity extends AppCompatActivity {
18 | private RecyclerView mBrandRecyclerView;
19 | VerticalAdapter mMyAdapter;
20 | @Override
21 | protected void onCreate(Bundle savedInstanceState) {
22 | super.onCreate(savedInstanceState);
23 | setContentView(R.layout.activity_linear);
24 | mBrandRecyclerView = findViewById(R.id.rv_brand_list);
25 |
26 | initNormalAdapter();
27 | }
28 |
29 | private void initNormalAdapter(){
30 | List data = new ArrayList<>();
31 | for(int i = 0; i < 20; i++){
32 | BrandData brand = new BrandData("brand " + i);
33 | data.add(brand);
34 | }
35 |
36 | LinearLayoutManager manager = new LinearLayoutManager(this);
37 | mBrandRecyclerView.setLayoutManager(manager);
38 |
39 | mMyAdapter = new VerticalAdapter(data);
40 | mBrandRecyclerView.setAdapter(mMyAdapter);
41 |
42 | int verticalSpace = Utils.dip2px(this, 15);
43 | int horizontalSpace = Utils.dip2px(this, 25);
44 |
45 |
46 | mBrandRecyclerView.addItemDecoration(
47 | SCommonItemDecoration.builder()
48 | .type(VerticalAdapter.TYPE_1)
49 | .prop(verticalSpace, horizontalSpace, true, false)
50 | .buildType()
51 | .type(VerticalAdapter.TYPE_2)
52 | .prop(Utils.dip2px(this, 5), Utils.dip2px(this, 5), true, true)
53 | .buildType()
54 | .build());
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/activity/VerticalGridRecyclerActivity.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample.activity;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.support.v7.widget.GridLayoutManager;
6 | import android.support.v7.widget.RecyclerView;
7 |
8 | import com.bosong.commonitemdecoration.SCommonItemDecoration;
9 | import com.bosong.sample.R;
10 | import com.bosong.sample.Utils;
11 | import com.bosong.sample.adapter.VerticalAdapter;
12 | import com.bosong.sample.model.BrandData;
13 |
14 | import java.util.ArrayList;
15 | import java.util.List;
16 |
17 | public class VerticalGridRecyclerActivity extends AppCompatActivity {
18 | private RecyclerView mBrandRecyclerView;
19 | VerticalAdapter mMyAdapter;
20 | @Override
21 | protected void onCreate(Bundle savedInstanceState) {
22 | super.onCreate(savedInstanceState);
23 | setContentView(R.layout.activity_grid_recycler);
24 |
25 | mBrandRecyclerView = findViewById(R.id.rv_brand_list);
26 |
27 | initNormalAdapter();
28 | }
29 |
30 | private void initNormalAdapter(){
31 | List data = new ArrayList<>();
32 | for(int i = 0; i < 20; i++){
33 | BrandData brand = new BrandData("brand " + i);
34 | data.add(brand);
35 | }
36 |
37 | GridLayoutManager manager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
38 | manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
39 | @Override
40 | public int getSpanSize(int position) {
41 | if(position == 1 || position == 2){
42 | return 2;
43 | }
44 | if(position == 10){
45 | return 2;
46 | }
47 | return 1;
48 | }
49 | });
50 | mBrandRecyclerView.setLayoutManager(manager);
51 |
52 | mMyAdapter = new VerticalAdapter(data);
53 | mBrandRecyclerView.setAdapter(mMyAdapter);
54 |
55 | mBrandRecyclerView.addItemDecoration(
56 | SCommonItemDecoration.builder()
57 | .type(VerticalAdapter.TYPE_1)
58 | .prop(Utils.dip2px(this, 15), Utils.dip2px(this, 25), true, true)
59 | .buildType()
60 | .type(VerticalAdapter.TYPE_2)
61 | .prop(Utils.dip2px(this, 5), Utils.dip2px(this, 5), true, true)
62 | .buildType()
63 | .build()
64 | );
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/activity/StaggeredRecyclerActivity.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample.activity;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.NonNull;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.support.v7.widget.RecyclerView;
7 | import android.support.v7.widget.StaggeredGridLayoutManager;
8 |
9 | import com.bosong.commonitemdecoration.SCommonItemDecoration;
10 | import com.bosong.sample.R;
11 | import com.bosong.sample.Utils;
12 | import com.bosong.sample.adapter.StaggeredAdapter;
13 | import com.bosong.sample.adapter.VerticalAdapter;
14 | import com.bosong.sample.model.BrandData;
15 |
16 | import java.util.ArrayList;
17 | import java.util.List;
18 |
19 | public class StaggeredRecyclerActivity extends AppCompatActivity {
20 | private RecyclerView mBrandRecyclerView;
21 | private StaggeredAdapter mMyAdapter;
22 | @Override
23 | protected void onCreate(Bundle savedInstanceState) {
24 | super.onCreate(savedInstanceState);
25 | setContentView(R.layout.activity_staggered_recycler);
26 | mBrandRecyclerView = findViewById(R.id.rv_brand_list);
27 |
28 | initNormalAdapter();
29 | }
30 |
31 | private void initNormalAdapter(){
32 | List data = new ArrayList<>();
33 | for(int i = 0; i < 20; i++){
34 | BrandData brand = new BrandData("brand " + i);
35 | data.add(brand);
36 | }
37 |
38 | mMyAdapter = new StaggeredAdapter(data);
39 | mBrandRecyclerView.setAdapter(mMyAdapter);
40 | StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
41 | mBrandRecyclerView.setLayoutManager(manager);
42 |
43 | mBrandRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
44 | @Override
45 | public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
46 | if(newState == RecyclerView.SCROLL_STATE_IDLE){
47 | // 在item重排后,重新计算边框
48 | mBrandRecyclerView.invalidateItemDecorations();
49 | }
50 | }
51 | });
52 |
53 | mBrandRecyclerView.addItemDecoration(
54 | SCommonItemDecoration.builder()
55 | .type(VerticalAdapter.TYPE_1)
56 | .prop(Utils.dip2px(this, 15), Utils.dip2px(this, 25), true, true)
57 | .buildType()
58 | .type(VerticalAdapter.TYPE_2)
59 | .prop(Utils.dip2px(this, 5), Utils.dip2px(this, 5), true, true)
60 | .buildType()
61 | .build()
62 | );
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/sample/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/bosong/sample/adapter/StaggeredAdapter.java:
--------------------------------------------------------------------------------
1 | package com.bosong.sample.adapter;
2 |
3 | import android.support.v7.widget.RecyclerView;
4 | import android.support.v7.widget.StaggeredGridLayoutManager;
5 | import android.view.ViewGroup;
6 |
7 | import com.bosong.sample.model.BrandData;
8 | import com.bosong.sample.viewholder.VerticalBrandViewHolder1;
9 | import com.bosong.sample.viewholder.VerticalBrandViewHolder2;
10 |
11 | import java.util.List;
12 | import java.util.Random;
13 |
14 | /**
15 | * Created by boson on 2017/3/22.
16 | */
17 |
18 | public class StaggeredAdapter extends RecyclerView.Adapter {
19 | public static final int TYPE_1 = 0;
20 | public static final int TYPE_2 = 1;
21 | private List mData;
22 | private Random mRandom = new Random();
23 | public StaggeredAdapter(List data){
24 | mData = data;
25 | }
26 |
27 | @Override
28 | public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
29 | if(viewType == 0){
30 | VerticalBrandViewHolder1 holder1 = new VerticalBrandViewHolder1(parent);
31 | holder1.brandNameTv.getLayoutParams().height = getRandomIntInRange(200, 400);
32 | return holder1;
33 | }else{
34 | VerticalBrandViewHolder2 holder2 = new VerticalBrandViewHolder2(parent);
35 | holder2.brandNameTv.getLayoutParams().height = getRandomIntInRange(200, 400);
36 | return holder2;
37 | }
38 | }
39 |
40 | @Override
41 | public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
42 | if(mData == null || mData.size() <= position){
43 | return;
44 | }
45 |
46 | if(holder instanceof VerticalBrandViewHolder1){
47 | VerticalBrandViewHolder1 normalHolder = (VerticalBrandViewHolder1) holder;
48 |
49 | normalHolder.brandNameTv.setText(mData.get(position).brandName);
50 | }else{
51 | VerticalBrandViewHolder2 preheatHolder = (VerticalBrandViewHolder2) holder;
52 | preheatHolder.brandNameTv.setText(mData.get(position).brandName);
53 | }
54 |
55 | StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
56 | if(position == 0){
57 | layoutParams.setFullSpan(true);
58 | }else{
59 | layoutParams.setFullSpan(false);
60 | }
61 | }
62 |
63 | @Override
64 | public int getItemCount() {
65 | return mData != null ? mData.size() : 0;
66 | }
67 |
68 | @Override
69 | public int getItemViewType(int position) {
70 | if(position < 10){
71 | return TYPE_1;
72 | }else{
73 | return TYPE_2;
74 | }
75 | }
76 |
77 | // Custom method to get a random number between a range
78 | protected int getRandomIntInRange(int max, int min){
79 | return mRandom.nextInt((max-min)+min)+min;
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/README_zh.md:
--------------------------------------------------------------------------------
1 | # 为RecyclerView设置相同的item间距(自定义ItemDecoration)
2 |
3 | 项目中经常碰到列表当中的每一项之间需要设置间距(分割线)的问题,对于RecyclerView来说,官方没有提供专门的方法实现。因此传统的办法是,通过给列表中每一项的根布局设置margin值来实现,例如需要左右间距时,可以给每一项设置right_margin。这种方法下,对于整个列表来说,它的左边没有边距,而右边有一个right_margin大小的边距,这样对于列表来说UI不对称。解决的办法是,给整个列表设置与right_margin同样大小的left_margin。但是,这样的方法并不优雅、不全面,比如如果这个列表左右两边不需要边距,这样的方法是实现不了的。
4 |
5 | 其实,官方为RecyclerView提供了ItemDecoration的概念,我们可以通过自定义ItemDecoration为item之间设置分割线。想要item间的左右间距都相同,通常的做法也类似于上面提到的办法,在getItemOffsets方法中给每一行的每个item的outRect设置相同的`right`,在这一行的最后一项不设置right或者给第一项设置left。这样的方法,比上面的方法优雅一些,因为可以判断一行当中第一项或者最后一项,并作区分处理。但是,在ItemDecoration方法中通过outRect设置的间距,都是占用item本身的空间,所以如果每个item设置的outRect不一样,则item本身显示出来的宽高也会不一样,比如如果一行的最后一项没设置right或第一项多设置left,则这一项和其他项宽度就不一致。所以我们来探索新的方式,使每个item的宽度维持一致并且间距也相同。
6 |
7 | 这里面需要推算一下。假设我们要处理的是纵向滚动的列表,每一行的item个数为spanCount,item间的间距(纵向)相同为space。则这一行中除去item占用的空间,剩下的空间为(假设最左边和最右边都有间距):
8 |
9 | `totalSpace=(spanCount+1)*space`
10 |
11 | 这样,为了保证每个item的宽度相同且间距相同,每一个item所需要提供给间距的宽度是
12 |
13 | ```
14 | itemSpace = totalSpace/spanCount
15 | = (spanCount+1)*space/spanCount
16 | = space + space/spanCount
17 | ```
18 |
19 | 对于一行当中的第一个item,左边的间距是
20 |
21 | `left1 = space`
22 |
23 | 可以计算出右边的间距是
24 |
25 | ```
26 | right1 = itemSpace - left1
27 | = space + space/spanCount - space
28 | = space/spanCount
29 | ```
30 |
31 | 对于一行当中的第二个item,左边的间距是
32 |
33 | ```
34 | left2 = space - right1
35 | = space - space/spanCount
36 | = space*(spanCount - 1)/spanCount
37 | ```
38 |
39 | 右边的边距是
40 |
41 | ```
42 | right2 = itemSpace - left2
43 | = space + space/spanCount - (space - space/spanCount)
44 | = 2*space/spanCount
45 | ```
46 |
47 | 对于第三个item,左边的间距是
48 |
49 | ```
50 | left3 = space - right2
51 | = space - 2*space/spanCount
52 | = space*(spanCount - 2)/spanCount
53 | ```
54 |
55 | 右边的边距是
56 |
57 | ```
58 | right3 = itemSpace - left3
59 | = space + space/spanCount - (space - 2*space/spanCount)
60 | = 3*space/spanCount
61 | ```
62 |
63 | 这样我们可以发现一些规律,假设一行当中item的索引为spanIndex(从0开始),则对于这个item来说,左边的间距是
64 |
65 | ```
66 | left = space*(spanCount - spanIndex)/spanCount
67 | ```
68 |
69 | 右间距是
70 |
71 | ```
72 | right = (spanIndex + 1)*space/spanCount
73 | ```
74 |
75 | 对于RecyclerView来说,spanIndex和spanCount都可以获取到。
76 |
77 |
78 | GridLayoutManager:
79 |
80 | ```
81 | GridLayoutManager.LayoutParams lp = (GridLayoutManager.LayoutParams) view.getLayoutParams();
82 | spanIndex = lp.getSpanIndex();
83 | GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
84 | spanCount = layoutManager.getSpanCount();
85 | ```
86 |
87 | StaggeredGridLayoutManager:
88 |
89 | ```
90 | StaggeredGridLayoutManager.LayoutParams lp = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
91 | spanIndex = lp.getSpanIndex();
92 | StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) parent.getLayoutManager();
93 | spanCount = layoutManager.getSpanCount();
94 | ```
95 |
96 | LinearLayoutManager:
97 |
98 | ```
99 | spanIndex = 0;
100 | spanCount = 1;
101 | ```
102 |
103 | 同理,我们可以推出很多其他情况,例如横向排列,例如去掉最边上的间距,例如item占据的列不止一列……
104 |
105 | 根据上面的理论,我实现了一个自定义ItemDecoration:SCommonItemDecoration,包含了上面及其他所有情况,可以设置横向和纵向列表的间距,同时可以设置边缘是否也设置间距。支持LinearLayoutManager,GridLayoutManager和StaggeredGridLayoutManager,也支持不同的orientation。同时,SCommonItemDecoration还支持为不同的item type设置不同的间距。
106 |
107 | ### 用法
108 |
109 | ``` java
110 | mRecyclerView.addItemDecoration(
111 | SCommonItemDecoration.builder()
112 | .type(TYPE_1)
113 | .prop(verticalSpace, horizaontalSpace, hasVerticalEdge, hasHorizontalEdge)
114 | .buildType()
115 | .type(TYPE_2)
116 | .prop(verticalSpace, horizaontalSpace, hasVerticalEdge, hasHorizontalEdge)
117 | .buildType()
118 | .build()
119 | );
120 | ```
121 |
122 | 不多说了,不懂的看sample吧。
123 |
124 | 
125 |
126 |
127 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/sample/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Copyright 2017 Bo Song
3 |
4 | Apache License
5 | Version 2.0, January 2004
6 | http://www.apache.org/licenses/
7 |
8 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9 |
10 | 1. Definitions.
11 |
12 | "License" shall mean the terms and conditions for use, reproduction,
13 | and distribution as defined by Sections 1 through 9 of this document.
14 |
15 | "Licensor" shall mean the copyright owner or entity authorized by
16 | the copyright owner that is granting the License.
17 |
18 | "Legal Entity" shall mean the union of the acting entity and all
19 | other entities that control, are controlled by, or are under common
20 | control with that entity. For the purposes of this definition,
21 | "control" means (i) the power, direct or indirect, to cause the
22 | direction or management of such entity, whether by contract or
23 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
24 | outstanding shares, or (iii) beneficial ownership of such entity.
25 |
26 | "You" (or "Your") shall mean an individual or Legal Entity
27 | exercising permissions granted by this License.
28 |
29 | "Source" form shall mean the preferred form for making modifications,
30 | including but not limited to software source code, documentation
31 | source, and configuration files.
32 |
33 | "Object" form shall mean any form resulting from mechanical
34 | transformation or translation of a Source form, including but
35 | not limited to compiled object code, generated documentation,
36 | and conversions to other media types.
37 |
38 | "Work" shall mean the work of authorship, whether in Source or
39 | Object form, made available under the License, as indicated by a
40 | copyright notice that is included in or attached to the work
41 | (an example is provided in the Appendix below).
42 |
43 | "Derivative Works" shall mean any work, whether in Source or Object
44 | form, that is based on (or derived from) the Work and for which the
45 | editorial revisions, annotations, elaborations, or other modifications
46 | represent, as a whole, an original work of authorship. For the purposes
47 | of this License, Derivative Works shall not include works that remain
48 | separable from, or merely link (or bind by name) to the interfaces of,
49 | the Work and Derivative Works thereof.
50 |
51 | "Contribution" shall mean any work of authorship, including
52 | the original version of the Work and any modifications or additions
53 | to that Work or Derivative Works thereof, that is intentionally
54 | submitted to Licensor for inclusion in the Work by the copyright owner
55 | or by an individual or Legal Entity authorized to submit on behalf of
56 | the copyright owner. For the purposes of this definition, "submitted"
57 | means any form of electronic, verbal, or written communication sent
58 | to the Licensor or its representatives, including but not limited to
59 | communication on electronic mailing lists, source code control systems,
60 | and issue tracking systems that are managed by, or on behalf of, the
61 | Licensor for the purpose of discussing and improving the Work, but
62 | excluding communication that is conspicuously marked or otherwise
63 | designated in writing by the copyright owner as "Not a Contribution."
64 |
65 | "Contributor" shall mean Licensor and any individual or Legal Entity
66 | on behalf of whom a Contribution has been received by Licensor and
67 | subsequently incorporated within the Work.
68 |
69 | 2. Grant of Copyright License. Subject to the terms and conditions of
70 | this License, each Contributor hereby grants to You a perpetual,
71 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72 | copyright license to reproduce, prepare Derivative Works of,
73 | publicly display, publicly perform, sublicense, and distribute the
74 | Work and such Derivative Works in Source or Object form.
75 |
76 | 3. Grant of Patent License. Subject to the terms and conditions of
77 | this License, each Contributor hereby grants to You a perpetual,
78 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79 | (except as stated in this section) patent license to make, have made,
80 | use, offer to sell, sell, import, and otherwise transfer the Work,
81 | where such license applies only to those patent claims licensable
82 | by such Contributor that are necessarily infringed by their
83 | Contribution(s) alone or by combination of their Contribution(s)
84 | with the Work to which such Contribution(s) was submitted. If You
85 | institute patent litigation against any entity (including a
86 | cross-claim or counterclaim in a lawsuit) alleging that the Work
87 | or a Contribution incorporated within the Work constitutes direct
88 | or contributory patent infringement, then any patent licenses
89 | granted to You under this License for that Work shall terminate
90 | as of the date such litigation is filed.
91 |
92 | 4. Redistribution. You may reproduce and distribute copies of the
93 | Work or Derivative Works thereof in any medium, with or without
94 | modifications, and in Source or Object form, provided that You
95 | meet the following conditions:
96 |
97 | (a) You must give any other recipients of the Work or
98 | Derivative Works a copy of this License; and
99 |
100 | (b) You must cause any modified files to carry prominent notices
101 | stating that You changed the files; and
102 |
103 | (c) You must retain, in the Source form of any Derivative Works
104 | that You distribute, all copyright, patent, trademark, and
105 | attribution notices from the Source form of the Work,
106 | excluding those notices that do not pertain to any part of
107 | the Derivative Works; and
108 |
109 | (d) If the Work includes a "NOTICE" text file as part of its
110 | distribution, then any Derivative Works that You distribute must
111 | include a readable copy of the attribution notices contained
112 | within such NOTICE file, excluding those notices that do not
113 | pertain to any part of the Derivative Works, in at least one
114 | of the following places: within a NOTICE text file distributed
115 | as part of the Derivative Works; within the Source form or
116 | documentation, if provided along with the Derivative Works; or,
117 | within a display generated by the Derivative Works, if and
118 | wherever such third-party notices normally appear. The contents
119 | of the NOTICE file are for informational purposes only and
120 | do not modify the License. You may add Your own attribution
121 | notices within Derivative Works that You distribute, alongside
122 | or as an addendum to the NOTICE text from the Work, provided
123 | that such additional attribution notices cannot be construed
124 | as modifying the License.
125 |
126 | You may add Your own copyright statement to Your modifications and
127 | may provide additional or different license terms and conditions
128 | for use, reproduction, or distribution of Your modifications, or
129 | for any such Derivative Works as a whole, provided Your use,
130 | reproduction, and distribution of the Work otherwise complies with
131 | the conditions stated in this License.
132 |
133 | 5. Submission of Contributions. Unless You explicitly state otherwise,
134 | any Contribution intentionally submitted for inclusion in the Work
135 | by You to the Licensor shall be under the terms and conditions of
136 | this License, without any additional terms or conditions.
137 | Notwithstanding the above, nothing herein shall supersede or modify
138 | the terms of any separate license agreement you may have executed
139 | with Licensor regarding such Contributions.
140 |
141 | 6. Trademarks. This License does not grant permission to use the trade
142 | names, trademarks, service marks, or product names of the Licensor,
143 | except as required for reasonable and customary use in describing the
144 | origin of the Work and reproducing the content of the NOTICE file.
145 |
146 | 7. Disclaimer of Warranty. Unless required by applicable law or
147 | agreed to in writing, Licensor provides the Work (and each
148 | Contributor provides its Contributions) on an "AS IS" BASIS,
149 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150 | implied, including, without limitation, any warranties or conditions
151 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152 | PARTICULAR PURPOSE. You are solely responsible for determining the
153 | appropriateness of using or redistributing the Work and assume any
154 | risks associated with Your exercise of permissions under this License.
155 |
156 | 8. Limitation of Liability. In no event and under no legal theory,
157 | whether in tort (including negligence), contract, or otherwise,
158 | unless required by applicable law (such as deliberate and grossly
159 | negligent acts) or agreed to in writing, shall any Contributor be
160 | liable to You for damages, including any direct, indirect, special,
161 | incidental, or consequential damages of any character arising as a
162 | result of this License or out of the use or inability to use the
163 | Work (including but not limited to damages for loss of goodwill,
164 | work stoppage, computer failure or malfunction, or any and all
165 | other commercial damages or losses), even if such Contributor
166 | has been advised of the possibility of such damages.
167 |
168 | 9. Accepting Warranty or Additional Liability. While redistributing
169 | the Work or Derivative Works thereof, You may choose to offer,
170 | and charge a fee for, acceptance of support, warranty, indemnity,
171 | or other liability obligations and/or rights consistent with this
172 | License. However, in accepting such obligations, You may act only
173 | on Your own behalf and on Your sole responsibility, not on behalf
174 | of any other Contributor, and only if You agree to indemnify,
175 | defend, and hold each Contributor harmless for any liability
176 | incurred by, or claims asserted against, such Contributor by reason
177 | of your accepting any such warranty or additional liability.
178 |
179 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/library/src/main/java/com/bosong/commonitemdecoration/SCommonItemDecoration.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2017 Bo Song
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.bosong.commonitemdecoration;
18 |
19 | import android.graphics.Rect;
20 | import android.support.annotation.NonNull;
21 | import android.support.v7.widget.GridLayoutManager;
22 | import android.support.v7.widget.OrientationHelper;
23 | import android.support.v7.widget.RecyclerView;
24 | import android.support.v7.widget.StaggeredGridLayoutManager;
25 | import android.util.SparseArray;
26 | import android.view.View;
27 |
28 | /**
29 | * Set dividers' properties(horizontal and vertical space...) of item with type.
30 | * 通过item type 设置边框属性
31 | * Created by bosong on 2017/3/10.
32 | */
33 |
34 | public class SCommonItemDecoration extends RecyclerView.ItemDecoration {
35 |
36 | public static ItemDecorationBuilder builder() {
37 | return new ItemDecorationBuilder();
38 | }
39 |
40 | private SparseArray mPropMap; // itemType -> prop
41 |
42 | SCommonItemDecoration(SparseArray propMap) {
43 | mPropMap = propMap;
44 | }
45 |
46 | SparseArray getPropMap() {
47 | return mPropMap;
48 | }
49 |
50 | @Override
51 | public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
52 | @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
53 | int position = parent.getChildAdapterPosition(view);
54 | RecyclerView.Adapter adapter = parent.getAdapter();
55 | if (adapter == null) {
56 | return;
57 | }
58 | int itemType = adapter.getItemViewType(position);
59 |
60 | ItemDecorationProps props;
61 | if (mPropMap != null) {
62 | props = mPropMap.get(itemType);
63 | } else {
64 | return;
65 | }
66 | if (props == null) {
67 | return;
68 | }
69 | int spanIndex = 0;
70 | int spanSize = 1;
71 | int spanCount = 1;
72 | int orientation = RecyclerView.VERTICAL;
73 | if(parent.getLayoutManager() instanceof GridLayoutManager){
74 | GridLayoutManager.LayoutParams lp = (GridLayoutManager.LayoutParams) view.getLayoutParams();
75 | spanIndex = lp.getSpanIndex();
76 | spanSize = lp.getSpanSize();
77 | GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
78 | spanCount = layoutManager.getSpanCount(); // Assume that there're spanCount items in this row/column.
79 | orientation = layoutManager.getOrientation();
80 | }else if(parent.getLayoutManager() instanceof StaggeredGridLayoutManager){
81 | StaggeredGridLayoutManager.LayoutParams lp = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
82 | spanIndex = lp.getSpanIndex();
83 | StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) parent.getLayoutManager();
84 | spanCount = layoutManager.getSpanCount(); // Assume that there're spanCount items in this row/column.
85 | spanSize = lp.isFullSpan() ? spanCount : 1;
86 | orientation = layoutManager.getOrientation();
87 | }
88 |
89 | boolean isFirstRowOrColumn, isLastRowOrColumn;
90 | int prePos = position > 0 ? position - 1 : -1;
91 | int nextPos = position < adapter.getItemCount() - 1 ? position + 1 : -1;
92 | // Last position on the last row 上一行的最后一个位置
93 | int preRowPos = position > spanIndex ? position - (1 + spanIndex) : -1;
94 | // First position on the next row 下一行的第一个位置
95 | int nextRowPos = position < adapter.getItemCount() - (spanCount - spanIndex) ? position + (spanCount - spanIndex) - spanSize + 1 : -1;
96 | isFirstRowOrColumn = position == 0 || prePos == -1 || itemType != adapter.getItemViewType(prePos) ||
97 | preRowPos == -1 || itemType != adapter.getItemViewType(preRowPos);
98 | isLastRowOrColumn = position == adapter.getItemCount() - 1 || nextPos == -1 || itemType != adapter.getItemViewType(nextPos) ||
99 | nextRowPos == -1 || itemType != adapter.getItemViewType(nextRowPos);
100 |
101 | int left = 0, top = 0, right = 0, bottom = 0;
102 |
103 | if (orientation == GridLayoutManager.VERTICAL) {
104 |
105 | if (props.getHasLeftRightEdge()) {
106 | left = props.getLeftRightSpace() * (spanCount - spanIndex) / spanCount;
107 | right = props.getLeftRightSpace() * (spanIndex + (spanSize - 1) + 1) / spanCount;
108 | } else {
109 | left = props.getLeftRightSpace() * spanIndex / spanCount;
110 | right = props.getLeftRightSpace() * (spanCount - (spanIndex + spanSize - 1) - 1) / spanCount;
111 | }
112 |
113 | if (isFirstRowOrColumn) { // First row
114 | if (props.getHasTopBottomEdge()) {
115 | top = props.getTopBottomSpace();
116 | }
117 | }
118 | if (isLastRowOrColumn) { // Last row
119 | if (props.getHasTopBottomEdge()) {
120 | bottom = props.getTopBottomSpace();
121 | }
122 | } else {
123 | bottom = props.getTopBottomSpace();
124 | }
125 | } else {
126 |
127 | if (props.getHasTopBottomEdge()) {
128 | top = props.getTopBottomSpace() * (spanCount - spanIndex) / spanCount;
129 | bottom = props.getTopBottomSpace() * (spanIndex + (spanSize - 1) + 1) / spanCount;
130 | } else {
131 | top = props.getTopBottomSpace() * spanIndex / spanCount;
132 | bottom = props.getTopBottomSpace() * (spanCount - (spanIndex + spanSize - 1) - 1) / spanCount;
133 | }
134 |
135 | if (isFirstRowOrColumn) { // First column
136 | if (props.getHasLeftRightEdge()) {
137 | left = props.getLeftRightSpace();
138 | }
139 | }
140 | if (isLastRowOrColumn) { // Last column
141 | if (props.getHasLeftRightEdge()) {
142 | right = props.getLeftRightSpace();
143 | }
144 | } else {
145 | right = props.getLeftRightSpace();
146 | }
147 | }
148 |
149 | outRect.set(left, top, right, bottom);
150 | }
151 |
152 | public static class ItemDecorationProps {
153 | /**
154 | * Space in left or right between items
155 | * 左右间距
156 | */
157 | private int mLeftRightSpace;
158 | /**
159 | * Space in top or bottom between items
160 | * 上下间距
161 | */
162 | private int mTopBottomSpace;
163 | /**
164 | * If this type of items has left and right space
165 | * 是否包含左右边距
166 | */
167 | private boolean mHasLeftRightEdge;
168 | /**
169 | * If this type of items has top and bottom space
170 | * 是否包含上下边距
171 | */
172 | private boolean mHasTopBottomEdge;
173 |
174 | ItemDecorationProps() {
175 |
176 | }
177 |
178 | public ItemDecorationProps(int topBottomSpace, int leftRightSpace, boolean hasTopBottomEdge, boolean hasLeftRightEdge) {
179 | this.mLeftRightSpace = leftRightSpace;
180 | this.mTopBottomSpace = topBottomSpace;
181 | this.mHasTopBottomEdge = hasTopBottomEdge;
182 | this.mHasLeftRightEdge = hasLeftRightEdge;
183 | }
184 |
185 | int getTopBottomSpace() {
186 | return this.mTopBottomSpace;
187 | }
188 |
189 | int getLeftRightSpace() {
190 | return this.mLeftRightSpace;
191 | }
192 |
193 | boolean getHasTopBottomEdge() {
194 | return this.mHasTopBottomEdge;
195 | }
196 |
197 | boolean getHasLeftRightEdge() {
198 | return this.mHasLeftRightEdge;
199 | }
200 |
201 | void setLeftRightSpace(int leftRightSpace) {
202 | mLeftRightSpace = leftRightSpace;
203 | }
204 |
205 | void setTopBottomSpace(int topBottomSpace) {
206 | mTopBottomSpace = topBottomSpace;
207 | }
208 |
209 | void setHasLeftRightEdge(boolean hasLeftRightEdge) {
210 | mHasLeftRightEdge = hasLeftRightEdge;
211 | }
212 |
213 | void setHasTopBottomEdge(boolean hasTopBottomEdge) {
214 | mHasTopBottomEdge = hasTopBottomEdge;
215 | }
216 | }
217 |
218 | public static class ItemDecorationBuilder {
219 | private SparseArray mPropMap = new SparseArray<>(); // itemType -> prop
220 |
221 | SparseArray getPropMap() {
222 | return mPropMap;
223 | }
224 |
225 | public ItemType type(int type) {
226 | return new ItemType(type, this);
227 | }
228 |
229 | public SCommonItemDecoration build() {
230 | return new SCommonItemDecoration(mPropMap);
231 | }
232 | }
233 |
234 | public static class ItemType {
235 | private int mType;
236 | private ItemDecorationProps mProps = new ItemDecorationProps();
237 |
238 | private ItemDecorationBuilder mBuilder;
239 |
240 | ItemType(int type, ItemDecorationBuilder builder) {
241 | mType = type;
242 | mBuilder = builder;
243 | }
244 |
245 | public ItemType prop(int leftRightSpace, int topBottomSpace, boolean hasLeftRightEdge, boolean hasTopBottomEdge) {
246 | mProps.setLeftRightSpace(leftRightSpace);
247 | mProps.setTopBottomSpace(topBottomSpace);
248 | mProps.setHasLeftRightEdge(hasLeftRightEdge);
249 | mProps.setHasTopBottomEdge(hasTopBottomEdge);
250 | return this;
251 | }
252 |
253 | public ItemType leftRightSpace(int space) {
254 | mProps.setLeftRightSpace(space);
255 | return this;
256 | }
257 |
258 | public ItemType topBottomSpace(int space) {
259 | mProps.setTopBottomSpace(space);
260 | return this;
261 | }
262 |
263 | public ItemType hasLeftRightEdge(boolean hasEdge) {
264 | mProps.setHasLeftRightEdge(hasEdge);
265 | return this;
266 | }
267 |
268 | public ItemType hasTopBottomEdge(boolean hasEdge) {
269 | mProps.setHasTopBottomEdge(hasEdge);
270 | return this;
271 | }
272 |
273 | public ItemDecorationBuilder buildType() {
274 | mBuilder.getPropMap().put(mType, mProps);
275 | return mBuilder;
276 | }
277 | }
278 | }
279 |
--------------------------------------------------------------------------------