file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
TestJniLib/src/main/java/com/yc/testjnilib/HelloCallBack.java | Java | package com.yc.testjnilib;
import android.util.Log;
public class HelloCallBack {
String name = "HelloCallBack";
void updateName(String name){
this.name = name;
Log.d("TestJni","你成功调用了HelloCallBack的方法:" + name);
}
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
TestJniLib/src/main/java/com/yc/testjnilib/NativeLib.java | Java | package com.yc.testjnilib;
public class NativeLib {
private static NativeLib instance;
// Used to load the 'testjnilib' library on application startup.
static {
System.loadLibrary("testjnilib");
}
public static NativeLib getInstance() {
if (instance == null) {
synchronized (NativeLib.class) {
if (instance == null) {
instance = new NativeLib();
}
}
}
return instance;
}
/**
* java调用native代码,java调用c/c++
*/
public native String stringFromJNI();
/**
* 打开定义native方法的java类,如下所示:是红色警告。
* 原因是,C++代码层没有对应的遵循特定JNI格式的JNI函数。
* 其实这个项目没有使用静态注册方法,而是使用了动态注册方法。
*
* @return
*/
public native String getNameFromJNI();
public native String getMd5(String str);
public native void initLib(String version);
public native String callThirdSoMethod();
} | yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
build.gradle | Gradle | // Top-level build file where you can add configuration options common to all sub-projects/modules.
apply from: "yc.gradle"
buildscript {
apply from: 'yc.gradle'
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
//添加阿里云镜像
maven { url "https://maven.aliyun.com/repository/public" }
maven { url "https://maven.aliyun.com/repository/google" }
maven { url "https://maven.aliyun.com/repository/jcenter" }
maven { url 'https://jitpack.io' }
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:$buildVersion"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
//jitpack
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.31"
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
//添加阿里云镜像
maven { url "https://maven.aliyun.com/repository/public" }
maven { url "https://maven.aliyun.com/repository/google" }
maven { url "https://maven.aliyun.com/repository/jcenter" }
maven { url 'https://jitpack.io' }
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
demo/build.gradle | Gradle | apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
applicationId "com.yc.jnidemo"
minSdkVersion 17
targetSdkVersion 29
versionCode 1
versionName "1.0"
ndk {
abiFilters 'armeabi-v7a'
}
}
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
//implementation project(':ReLinker')
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
demo/src/main/java/com/yc/demo/App.java | Java | package com.yc.demo;
import android.app.Application;
import com.yc.testjnilib.NativeLib;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
NativeLib.getInstance().init(this);
}
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
demo/src/main/java/com/yc/demo/DemoActivity.java | Java | package com.yc.demo;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.yc.testjnilib.NativeLib;
public class DemoActivity extends AppCompatActivity {
private TextView tv;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_main);
tv = findViewById(R.id.tv_content);
findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
String fromJNI = NativeLib.getInstance().stringFromJNI();
String md5 = NativeLib.getInstance().getMd5("yc");
NativeLib.getInstance().initLib("db");
tv.setText("" + md5);
}
});
}
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
demo/src/main/java/com/yc/testjnilib/NativeLib.java | Java | package com.yc.testjnilib;
import android.content.Context;
import com.getkeepsafe.relinker.ReLinker;
public class NativeLib {
private static NativeLib instance;
static {
//System.loadLibrary("testjnilib");
}
public static NativeLib getInstance() {
if (instance == null) {
synchronized (NativeLib.class) {
if (instance == null) {
instance = new NativeLib();
}
}
}
return instance;
}
public void init(Context context){
//ReLinker.loadLibrary(context,"testjnilib");
ReLinker.loadLibrary(context, "testjnilib", new ReLinker.LoadListener() {
@Override
public void success() {
}
@Override
public void failure(Throwable t) {
}
});
}
/**
* java调用native代码,java调用c/c++
*/
public native String stringFromJNI();
public native String getMd5(String str);
public native void initLib(String version);
} | yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
settings.gradle | Gradle | include ':AppJni'
include ':demo'
include ':CallJniLib'
//include ':MoonerJniLib'
include ':EpicJniLib'
include ':TestJniLib'
include ':SafetyJniLib'
include ':SignalHooker'
include ':ReLinker'
//include ':MmkvLib'
//include ':Mmkvdemo'
include ':CrashDumper'
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
yc.gradle | Gradle | ext {
android = [
compileSdkVersion: 30,
buildToolsVersion: "29.0.0",
minSdkVersion : 17,
targetSdkVersion : 29,
versionCode : 23,
versionName : "1.8.3" //必须是int或者float,否则影响线上升级
]
//Android统一build环境
buildVersion = '4.1.0'
//AndroidX系列
appcompatVersion = '1.2.0'
annotationVersion = '1.2.0'
cardviewVersion = '1.0.0'
mediaVersion = '1.0.1'
swiperefreshlayoutVersion = '1.0.0'
materialVersion = '1.0.0-rc01'
coordinatorlayoutVersion = '1.0.0'
constraintlayoutVersion = '1.1.3'
recyclerviewVersion = '1.0.0'
multidexVersion = '1.0.2'
viewpagerVersion = '1.0.0'
//AndroidX系列ktx
activityKtx = '1.4.0'
//kotlin系列
kotlin_version = '1.4.31'
kotlinxVersion = '1.0.1'
//jetpack系列
coreVersion = '1.0.0'
databindingVersion = '3.2.1'
archLifecycleVersion = '2.2.0'
roomVersion = '2.0.0'
workVersion = '2.0.0'
//第三方库系列
retrofitSdkVersion = "2.4.0"
glideSdkVersion = "4.9.0"
okhttpVersion = "4.7.2"
gsonVersion = "2.8.5"
permissionsVersion = "1.0.1"
dependencies = [
//AndroidX系列
appcompat : "androidx.appcompat:appcompat:${appcompatVersion}",
annotation : "androidx.annotation:annotation:${annotationVersion}",
percentlayout : "androidx.percentlayout:percentlayout:${viewpagerVersion}",
constraintlayout : "androidx.constraintlayout:constraintlayout:${constraintlayoutVersion}",
coordinatorlayout : "androidx.coordinatorlayout:coordinatorlayout:${coordinatorlayoutVersion}",
cardview : "androidx.cardview:cardview:${cardviewVersion}",
recyclerview : "androidx.recyclerview:recyclerview:${recyclerviewVersion}",
media : "androidx.media:media:${mediaVersion}",
material : "com.google.android.material:material:${materialVersion}",
swiperefreshlayout : "androidx.swiperefreshlayout:swiperefreshlayout:${swiperefreshlayoutVersion}",
"multidex" : "com.android.support:multidex:$multidexVersion",
viewpager2 : "androidx.viewpager2:viewpager2:${viewpagerVersion}",
//jetpack系列
core : "androidx.core:core:${coreVersion}",
coreKtx : "androidx.core:core-ktx:${coreVersion}",
roomRuntime : "androidx.room:room-runtime:${roomVersion}",
roomCompiler : "androidx.room:room-compiler:${roomVersion}",
databinding : "androidx.databinding:databinding-common:${databindingVersion}",
lifecycle : "androidx.lifecycle:lifecycle-extensions:${archLifecycleVersion}",
lifecycleCompiler : "androidx.lifecycle:lifecycle-common:${archLifecycleVersion}",
lifecycleRuntime : "androidx.lifecycle:lifecycle-runtime:${archLifecycleVersion}",
livedataCore : "androidx.lifecycle:lifecycle-livedata-core:${archLifecycleVersion}",
workKtx : "androidx.work:work-runtime-ktx:${workVersion}",
activityKtx : "androidx.activity:activity-ktx:${activityKtx}",
navigationFragment : "androidx.navigation:navigation-fragment:${archLifecycleVersion}",
navigationFragmentKtx : "androidx.navigation:navigation-fragment-ktx:${archLifecycleVersion}",
navigationUiKtx : "androidx.navigation:navigation-ui-ktx:${archLifecycleVersion}",
activityKtx : "androidx.activity:activity-ktx:${activityKtx}",
datastore : "androidx.datastore:datastore-preferences:${coreVersion}",
//将 Kotlin 协程与生命周期感知型组件一起使用
//https://developer.android.com/topic/libraries/architecture/coroutines
lifecycleKtx : "androidx.lifecycle:lifecycle-runtime-ktx:${archLifecycleVersion}",
livedataKtx : "androidx.lifecycle:lifecycle-livedata-ktx:${archLifecycleVersion}",
viewmodelKtx : "androidx.lifecycle:lifecycle-viewmodel-ktx:${archLifecycleVersion}",
//kotlin
kotlinxCoroutinesCore : "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinxVersion",
kotlinxCoroutinesAndroid : "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlinxVersion",
kotlinxJdk : "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version",
//network
retrofit : "com.squareup.retrofit2:retrofit:$retrofitSdkVersion",
"retrofit-converter-gson" : "com.squareup.retrofit2:converter-gson:$retrofitSdkVersion",
"retrofit-adapter-rxjava2": "com.squareup.retrofit2:adapter-rxjava2:$retrofitSdkVersion",
okhttp : "com.squareup.okhttp3:okhttp:$okhttpVersion",
gson : "com.google.code.gson:gson:$gsonVersion",
glide : "com.github.bumptech.glide:glide:$glideSdkVersion",
"glide-compiler" : "com.github.bumptech.glide:compiler:$glideSdkVersion",
//widget库
//https://github.com/yangchong211/YCWidgetLib
"ShadowConfig" : "com.github.yangchong211.YCWidgetLib:ShadowConfig:1.0.5",
"RedDotView" : "com.github.yangchong211.YCWidgetLib:RedDotView:1.0.5",
"ExpandPager" : "com.github.yangchong211.YCWidgetLib:ExpandPager:1.0.5",
"ExpandLib" : "com.github.yangchong211.YCWidgetLib:ExpandLib:1.0.5",
"CardViewLib" : "com.github.yangchong211.YCWidgetLib:CardViewLib:1.0.5",
"RoundCorners" : "com.github.yangchong211.YCWidgetLib:RoundCorners:1.0.5",
//线程池
//https://github.com/yangchong211/YCThreadPool
"ThreadPoolLib" : "com.github.yangchong211.YCThreadPool:ThreadPoolLib:1.3.7",
"ThreadTaskLib" : "com.github.yangchong211.YCThreadPool:ThreadTaskLib:1.3.7",
"EasyExecutor" : "com.github.yangchong211.YCThreadPool:EasyExecutor:1.3.8",
//效率优化
//https://github.com/yangchong211/YCEfficient
"AppStartLib" : "com.github.yangchong211.YCEfficient:AppStartLib:1.3.1",
"AppProcessLib" : "com.github.yangchong211.YCEfficient:AppProcessLib:1.3.1",
"AutoCloserLib" : "com.github.yangchong211.YCEfficient:AutoCloserLib:1.3.1",
//tools
"easypermissions" : "pub.devrel:easypermissions:$permissionsVersion",
]
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
NotificationLib/build.gradle | Gradle | apply plugin: 'com.android.library'
//迁移到jitpack
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotificationLib/src/main/java/com/ycbjie/notificationlib/NotificationParams.java | Java | package com.ycbjie.notificationlib;
import android.app.PendingIntent;
import android.net.Uri;
import android.widget.RemoteViews;
import static android.app.Notification.PRIORITY_DEFAULT;
/**
* <pre>
* @author yangchong
* blog : https://www.jianshu.com/p/514eb6193a06
* time : 2018/2/10
* desc : 通知栏参数设置
* revise:
* </pre>
*/
public final class NotificationParams {
public boolean ongoing = false;
public RemoteViews remoteViews = null;
public PendingIntent intent = null;
public String ticker = "";
public int priority = PRIORITY_DEFAULT;
public boolean onlyAlertOnce = false;
public long when = 0;
public Uri sound = null;
public int defaults = 0;
public long[] pattern = null;
public int[] flags;
public NotificationParams(){
this.ongoing = false;
this.remoteViews = null;
this.intent = null;
this.ticker = "";
this.priority = PRIORITY_DEFAULT;
this.when = 0;
this.sound = null;
}
/**
* 让通知左右滑的时候是否可以取消通知
* @param ongoing 是否可以取消通知
* @return
*/
public NotificationParams setOngoing(boolean ongoing){
this.ongoing = ongoing;
return this;
}
/**
* 设置自定义view通知栏布局
* @param remoteViews view
* @return
*/
public NotificationParams setContent(RemoteViews remoteViews){
this.remoteViews = remoteViews;
return this;
}
/**
* 设置内容点击
* @param intent intent
* @return
*/
public NotificationParams setContentIntent(PendingIntent intent){
this.intent = intent;
return this;
}
/**
* 设置状态栏的标题
* @param ticker 状态栏的标题
* @return
*/
public NotificationParams setTicker(String ticker){
this.ticker = ticker;
return this;
}
/**
* 设置优先级
* 注意:
* Android 8.0以及上,在 NotificationChannel 的构造函数中指定,总共要五个级别;
* Android 7.1(API 25)及以下的设备,还得调用NotificationCompat 的 setPriority方法来设置
*
* @param priority 优先级,默认是Notification.PRIORITY_DEFAULT
* @return
*/
public NotificationParams setPriority(int priority){
this.priority = priority;
return this;
}
/**
* 是否提示一次.true - 如果Notification已经存在状态栏即使在调用notify函数也不会更新
* @param onlyAlertOnce 是否只提示一次,默认是false
* @return
*/
public NotificationParams setOnlyAlertOnce(boolean onlyAlertOnce){
this.onlyAlertOnce = onlyAlertOnce;
return this;
}
/**
* 设置通知时间,默认为系统发出通知的时间,通常不用设置
* @param when when
* @return
*/
public NotificationParams setWhen(long when){
this.when = when;
return this;
}
/**
* 设置sound
* @param sound sound
* @return
*/
public NotificationParams setSound(Uri sound){
this.sound = sound;
return this;
}
/**
* 设置默认的提示音
* @param defaults defaults
* @return
*/
public NotificationParams setDefaults(int defaults){
this.defaults = defaults;
return this;
}
/**
* 自定义震动效果
* @param pattern pattern
* @return
*/
public NotificationParams setVibrate(long[] pattern){
this.pattern = pattern;
return this;
}
/**
* 设置flag标签
* @param flags flags
* @return
*/
public NotificationParams setFlags(int... flags){
this.flags = flags;
return this;
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotificationLib/src/main/java/com/ycbjie/notificationlib/NotificationUtils.java | Java | package com.ycbjie.notificationlib;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import java.util.List;
import static android.app.Notification.PRIORITY_DEFAULT;
/**
* <pre>
* @author yangchong
* blog : https://www.jianshu.com/p/514eb6193a06
* time : 2018/2/10
* desc : 通知栏工具类
* revise:
* </pre>
*/
public class NotificationUtils extends ContextWrapper {
private static String CHANNEL_ID = "default";
private static String CHANNEL_NAME = "Default_Channel";
private NotificationManager mManager;
private NotificationChannel channel;
public NotificationUtils(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//android 8.0以上需要特殊处理,也就是targetSDKVersion为26以上
createNotificationChannel(null,null);
}
}
public NotificationUtils(Context base , String channelId) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//android 8.0以上需要特殊处理,也就是targetSDKVersion为26以上
createNotificationChannel(channelId,null);
}
}
public NotificationUtils(Context base ,String channelId, String channelName) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//android 8.0以上需要特殊处理,也就是targetSDKVersion为26以上
createNotificationChannel(channelId,channelName);
}
}
/**
* 8.0以上需要创建通知栏渠道channel
*/
@TargetApi(Build.VERSION_CODES.O)
private NotificationChannel createNotificationChannel(String channelId , String channelName) {
//第一个参数:channel_id
//第二个参数:channel_name,这个是用来展示给用户看的
//第三个参数:设置通知重要性级别
//注意:该级别必须要在 NotificationChannel 的构造函数中指定,总共要五个级别;
//范围是从 NotificationManager.IMPORTANCE_NONE(0) ~ NotificationManager.IMPORTANCE_HIGH(4)
if (!TextUtils.isEmpty(channelId)){
CHANNEL_ID = channelId;
}
if (!TextUtils.isEmpty(channelName)){
CHANNEL_NAME = channelName;
}
channel = new NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
/*channel.canBypassDnd();//是否绕过请勿打扰模式
channel.enableLights(true);//闪光灯
channel.setLockscreenVisibility(VISIBILITY_SECRET);//锁屏显示通知
channel.setLightColor(Color.RED);//闪关灯的灯光颜色
channel.canShowBadge();//桌面launcher的消息角标
channel.enableVibration(true);//是否允许震动
channel.getAudioAttributes();//获取系统通知响铃声音的配置
channel.getGroup();//获取通知取到组
channel.setBypassDnd(true);//设置可绕过 请勿打扰模式
channel.setVibrationPattern(new long[]{100, 100, 200});//设置震动模式
channel.shouldShowLights();//是否会有灯光*/
getManager().createNotificationChannel(channel);
return channel;
}
/**
* 获取创建一个NotificationManager的对象
* @return NotificationManager对象
*/
public NotificationManager getManager() {
if (mManager == null) {
mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return mManager;
}
/**
* 获取创建一个NotificationChannel的对象
* @return NotificationChannel对象
*/
public NotificationChannel getNotificationChannel(){
if (channel == null){
channel = createNotificationChannel(null,null);
}
return channel;
}
/**
* 获取创建一个NotificationChannel的对象
* @return NotificationChannel对象
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public NotificationChannel getNotificationChannel(String channelId){
if (TextUtils.isEmpty(channelId)){
return getNotificationChannel();
}
NotificationManager manager = getManager();
return manager.getNotificationChannel(channelId);
}
/**
* 清空所有的通知
*/
public void clearNotification(){
getManager().cancelAll();
}
/**
* 清空特定的通知
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void clearNotificationChannel(String channelId){
if (channelId == null || channelId.length() == 0){
return;
}
NotificationManager manager = getManager();
manager.deleteNotificationChannel(channelId);
}
/**
* 清空所有的通知
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void clearAllNotification(){
NotificationManager manager = getManager();
List<NotificationChannel> notificationChannels = manager.getNotificationChannels();
if (notificationChannels!=null){
for (int i=0 ; i<notificationChannels.size() ; i++){
NotificationChannel notificationChannel = notificationChannels.get(i);
if (notificationChannel == null){
continue;
}
String id = notificationChannel.getId();
CharSequence name = notificationChannel.getName();
Log.d("notification channel " , id + " , " + name);
manager.deleteNotificationChannel(id);
}
}
}
/**
* 清空所有的通知
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void clearAllGroupNotification(){
NotificationManager manager = getManager();
List<NotificationChannelGroup> notificationChannelGroups = manager.getNotificationChannelGroups();
if (notificationChannelGroups!=null){
for (int i=0 ; i<notificationChannelGroups.size() ; i++){
NotificationChannelGroup notificationChannelGroup = notificationChannelGroups.get(i);
if (notificationChannelGroup == null){
continue;
}
String id = notificationChannelGroup.getId();
CharSequence name = notificationChannelGroup.getName();
Log.d("notification group " , id + " , " + name);
manager.deleteNotificationChannel(id);
}
}
}
/**
* 获取Notification
* @param title title
* @param content content
*/
public Notification getNotification(String title, String content , int icon){
Notification build;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//android 8.0以上需要特殊处理,也就是targetSDKVersion为26以上
//通知用到NotificationCompat()这个V4库中的方法。但是在实际使用时发现书上的代码已经过时并且Android8.0已经不支持这种写法
Notification.Builder builder = getNotificationV4(title, content, icon);
build = builder.build();
} else {
NotificationCompat.Builder builder = getNotificationCompat(title, content, icon);
build = builder.build();
}
NotificationParams notificationParams = getNotificationParams();
if (notificationParams.flags!=null && notificationParams.flags.length>0){
for (int a=0 ; a<notificationParams.flags.length ; a++){
build.flags |= notificationParams.flags[a];
}
}
return build;
}
/**
* 建议使用这个发送通知
* 调用该方法可以发送通知
* @param notifyId notifyId
* @param title title
* @param content content
*/
public void sendNotification(int notifyId, String title, String content , int icon) {
Notification build;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//android 8.0以上需要特殊处理,也就是targetSDKVersion为26以上
//通知用到NotificationCompat()这个V4库中的方法。但是在实际使用时发现书上的代码已经过时并且Android8.0已经不支持这种写法
Notification.Builder builder = getNotificationV4(title, content, icon);
build = builder.build();
} else {
NotificationCompat.Builder builder = getNotificationCompat(title, content, icon);
build = builder.build();
}
NotificationParams notificationParams = getNotificationParams();
if (notificationParams.flags!=null && notificationParams.flags.length>0){
for (int a=0 ; a<notificationParams.flags.length ; a++){
build.flags |= notificationParams.flags[a];
}
}
getManager().notify(notifyId, build);
}
/**
* 调用该方法可以发送通知
* @param notifyId notifyId
* @param title title
* @param content content
*/
public void sendNotificationCompat(int notifyId, String title, String content , int icon) {
NotificationCompat.Builder builder = getNotificationCompat(title, content, icon);
Notification build = builder.build();
NotificationParams notificationParams = getNotificationParams();
if (notificationParams.flags!=null && notificationParams.flags.length>0){
for (int a=0 ; a<notificationParams.flags.length ; a++){
build.flags |= notificationParams.flags[a];
}
}
getManager().notify(notifyId, build);
}
private NotificationCompat.Builder getNotificationCompat(String title, String content, int icon) {
NotificationCompat.Builder builder;
NotificationParams notificationParams = getNotificationParams();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
} else {
//注意用下面这个方法,在8.0以上无法出现通知栏。8.0之前是正常的。这里需要增强判断逻辑
builder = new NotificationCompat.Builder(getApplicationContext());
builder.setPriority(PRIORITY_DEFAULT);
}
builder.setContentTitle(title);
builder.setContentText(content);
builder.setSmallIcon(icon);
//设置优先级
builder.setPriority(notificationParams.priority);
//是否提示一次.true - 如果Notification已经存在状态栏即使在调用notify函数也不会更新
builder.setOnlyAlertOnce(notificationParams.onlyAlertOnce);
//让通知左右滑的时候是否可以取消通知
builder.setOngoing(notificationParams.ongoing);
if (notificationParams.remoteViews!=null){
builder.setContent(notificationParams.remoteViews);
}
if (notificationParams.intent!=null){
builder.setContentIntent(notificationParams.intent);
}
if (notificationParams.ticker!=null && notificationParams.ticker.length()>0){
builder.setTicker(notificationParams.ticker);
}
if (notificationParams.when!=0){
builder.setWhen(notificationParams.when);
}
if (notificationParams.sound!=null){
builder.setSound(notificationParams.sound);
}
if (notificationParams.defaults!=0){
builder.setDefaults(notificationParams.defaults);
}
//点击自动删除通知
builder.setAutoCancel(true);
return builder;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private Notification.Builder getNotificationV4(String title, String content, int icon){
NotificationParams notificationParams = getNotificationParams();
Notification.Builder builder = new Notification.Builder(getApplicationContext(), CHANNEL_ID);
Notification.Builder notificationBuilder = builder
//设置标题
.setContentTitle(title)
//消息内容
.setContentText(content)
//设置通知的图标
.setSmallIcon(icon)
//让通知左右滑的时候是否可以取消通知
.setOngoing(notificationParams.ongoing)
//设置优先级
.setPriority(notificationParams.priority)
//是否提示一次.true - 如果Notification已经存在状态栏即使在调用notify函数也不会更新
.setOnlyAlertOnce(notificationParams.onlyAlertOnce)
.setAutoCancel(true);
if (notificationParams.remoteViews!=null){
//设置自定义view通知栏
notificationBuilder.setContent(notificationParams.remoteViews);
}
if (notificationParams.intent!=null){
notificationBuilder.setContentIntent(notificationParams.intent);
}
if (notificationParams.ticker!=null && notificationParams.ticker.length()>0){
//设置状态栏的标题
notificationBuilder.setTicker(notificationParams.ticker);
}
if (notificationParams.when!=0){
//设置通知时间,默认为系统发出通知的时间,通常不用设置
notificationBuilder.setWhen(notificationParams.when);
}
if (notificationParams.sound!=null){
//设置sound
notificationBuilder.setSound(notificationParams.sound);
}
if (notificationParams.defaults!=0){
//设置默认的提示音
notificationBuilder.setDefaults(notificationParams.defaults);
}
if (notificationParams.pattern!=null){
//自定义震动效果
notificationBuilder.setVibrate(notificationParams.pattern);
}
return notificationBuilder;
}
private NotificationParams params;
public NotificationParams getNotificationParams() {
if (params == null){
return new NotificationParams();
}
return params;
}
public NotificationUtils setNotificationParams(NotificationParams params) {
this.params = params;
return this;
}
/**
* 判断通知是否是静默不重要的通知。
* 主要是该类通知被用户手动给关闭
* @param channel 通知栏channel
* @return
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public boolean isNoImportance(NotificationChannel channel){
if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE){
return true;
}
return false;
}
/**
* 判断通知是否是静默不重要的通知。
* 主要是该类通知被用户手动给关闭
* @param channelId 通知栏channelId
* @return
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public boolean isNoImportance(String channelId){
NotificationChannel channel = getNotificationChannel(channelId);
return isNoImportance(channel);
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void openChannelSetting(String channelId){
NotificationChannel channel = getNotificationChannel(channelId);
openChannelSetting(channel);
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void openChannelSetting(NotificationChannel channel){
if (channel == null){
return;
}
if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel.getId());
startActivity(intent);
}
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/build.gradle | Gradle | plugins {
id 'com.android.library'
}
//迁移到jitpack
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
} | yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/CustomNotification.java | Java | package com.yc.notifymessage;
import android.app.Activity;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.Nullable;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/11/9
* desc : 用于展示顶部样式
* revise:
* </pre>
*/
public class CustomNotification<T> implements Parcelable {
public static final Creator<CustomNotification> CREATOR = new Creator<CustomNotification>() {
@Override
public CustomNotification createFromParcel(Parcel in) {
return new CustomNotification(in);
}
@Override
public CustomNotification[] newArray(int size) {
return new CustomNotification[size];
}
};
private static final int TYPE_UNKNOWN = -1;
// 显示的通知 View
NotificationView<T> mView;
// 自动隐藏时间
int mTimeout = 0;
// 显示优先级
int mPriority = 0;
// 是否常驻
boolean mIsPin;
// 是否可被上划收起
boolean mIsCollapsible;
// 是否可被覆盖(暂时无用)
boolean mIsOverride = true;
//通知类型(必须设置)
int mType = TYPE_UNKNOWN;
// 与 view 绑定的 data 类
T mData;
public CustomNotification() {
}
protected CustomNotification(Parcel in) {
mTimeout = in.readInt();
mPriority = in.readInt();
mIsPin = in.readByte() != 0;
mIsCollapsible = in.readByte() != 0;
mIsOverride = in.readByte() != 0;
mType = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mTimeout);
dest.writeInt(mPriority);
dest.writeByte((byte) (mIsPin ? 1 : 0));
dest.writeByte((byte) (mIsCollapsible ? 1 : 0));
dest.writeByte((byte) (mIsOverride ? 1 : 0));
dest.writeInt(mType);
}
@Override
public int describeContents() {
return 0;
}
public CustomNotification<T> setTimeOut(int timeOut) {
this.mTimeout = timeOut;
return this;
}
public CustomNotification<T> setPin(boolean isPin) {
this.mIsPin = isPin;
return this;
}
public CustomNotification<T> setPriority(int priority) {
this.mPriority = priority;
return this;
}
public CustomNotification<T> setType(int type) {
this.mType = type;
return this;
}
public CustomNotification<T> setCollapsible(boolean bool) {
this.mIsCollapsible = bool;
return this;
}
public CustomNotification<T> setOverride(boolean bool) {
this.mIsOverride = bool;
return this;
}
public CustomNotification<T> setNotificationView(NotificationView<T> view) {
this.mView = view;
return this;
}
public CustomNotification<T> setData(T data) {
mData = data;
return this;
}
public CustomNotification<T> setData(T data, boolean rebind) {
mData = data;
if (rebind) {
getNotificationView().bindNotification(this);
}
return this;
}
public NotificationView<T> getNotificationView() {
return mView;
}
public int getTimeout() {
return mTimeout;
}
public int getPriority() {
return mPriority;
}
public boolean isPin() {
return mIsPin;
}
public boolean isCollapsible() {
return mIsCollapsible;
}
public boolean isOverride() {
return mIsOverride;
}
@Nullable
public Activity getActivity() {
return mView == null ? null : mView.getActivity();
}
@Nullable
public T getData() {
return mData;
}
/**
* 显示当前设置的通知,注意:通知类型必须设置
*/
public void show() {
checkArgument();
if (mView != null) {
mView.bindNotification(this);
}
NotificationManager.getInstance().notify(this);
}
/**
* 检查参数是否正确,主要检查通知类型是否设置
*/
private void checkArgument() {
if (mType == TYPE_UNKNOWN) {
throw new IllegalArgumentException("type should be set");
}
}
public static void cancel(int type) {
NotificationManager.getInstance().cancel(type);
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/INotificationService.java | Java | package com.yc.notifymessage;
import android.animation.Animator;
/**
* <pre>
* @author yangchong
* blog : https://www.jianshu.com/p/514eb6193a06
* time : 2018/2/10
* desc : 接口
* revise:
* </pre>
*/
public interface INotificationService<T> {
/**
* 有新通知需要展示
*/
void show(T notification);
/**
* 需要移除指定的通知
*/
void cancel(T notification , Animator.AnimatorListener listener);
/**
* 判断是否在展示状态
* @return
*/
boolean isShowing();
/**
* 设置是否展示状态
* @param isShowing
*/
void changeIsShowing(boolean isShowing);
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/LoggerUtils.java | Java | package com.yc.notifymessage;
import android.util.Log;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/11/9
* desc : 日志工具类
* revise:
* </pre>
*/
public final class LoggerUtils {
private static Logger sLogger = null;
public static void log(String content) {
if (sLogger == null) {
return;
}
log("",content);
}
public static void log(Object object, String content) {
if (sLogger == null) {
return;
}
String instance = "";
if (object != null) {
instance = object.toString();
}
String fullLog = instance + " " + content;
sLogger.log(fullLog);
if (sLogger.debugLogEnable()) {
Log.i("LoggerUtils", fullLog);
}
}
public static void setLogger(Logger logger) {
sLogger = logger;
}
public static Logger getLogger() {
return sLogger;
}
public interface Logger {
/**
* 在回调中打日志。这个地方的日志,暴露给开发者调用
* @param content 日志
*/
void log(String content);
/**
* 开启后容器内部会通过 Log.i 打日志
* 建议初期在线上开启,方便出统计上相关信息
* @return true表示开启
*/
boolean debugLogEnable();
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/MyHandler.java | Java | package com.yc.notifymessage;
import android.os.Handler;
import android.os.Message;
import java.lang.ref.WeakReference;
public class MyHandler extends Handler {
private final WeakReference<NotificationManager> mWeakReference;
public MyHandler(NotificationManager notificationManager) {
mWeakReference = new WeakReference<>(notificationManager);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mWeakReference == null || mWeakReference.get() == null) {
return;
}
int action = msg.what;
if (action == NotificationManager.MSG_SHOW) {
CustomNotification notification = msg.getData()
.getParcelable(NotificationManager.BUNDLE_NOTIFICATION);
if (notification != null) {
mWeakReference.get().showNotification(notification);
}
} else {
int type = action - NotificationManager.MSG_HIDE;
mWeakReference.get().hideNotification(type);
}
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/NotificationManager.java | Java | package com.yc.notifymessage;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.os.Bundle;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Iterator;
import java.util.LinkedList;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/11/9
* desc : 通知栏manager类
* revise:
* </pre>
*/
public class NotificationManager {
public static final int MSG_SHOW = 1;
public static final int MSG_HIDE = 2;
public static final String BUNDLE_NOTIFICATION = "notification";
public static final String BUNDLE_TYPE = "type";
private static volatile NotificationManager sInstance;
private final LinkedList<NotificationNode> mNodeLinkedList = new LinkedList<>();
private final MyHandler mHandler = new MyHandler(this);
private NotificationManager() {
}
public static NotificationManager getInstance() {
if (sInstance == null) {
synchronized (NotificationManager.class) {
if (sInstance == null) {
sInstance = new NotificationManager();
}
}
}
return sInstance;
}
void notify(final CustomNotification notification) {
sendMessageShow(notification);
}
/**
* 隐藏某类型消息
*
* @param type 消息类型
*/
public void cancel(int type) {
sendMessageHide(type);
}
protected void hideNotification() {
if (mNodeLinkedList.isEmpty()) {
return;
}
hideNotification(mNodeLinkedList.getFirst());
}
/**
* 隐藏某通知
*
* @param notificationNode 需要被隐藏的通知
*/
private void hideNotification(NotificationNode notificationNode) {
if (mNodeLinkedList.isEmpty() || notificationNode == null) {
return;
}
boolean isHead = notificationNode == mNodeLinkedList.getFirst();
removeNotificationNode(notificationNode);
notificationNode.changeIsShowing(false);
if (isHead) {
notificationNode.handleHide(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (!mNodeLinkedList.isEmpty()) {
showNotification(mNodeLinkedList.getFirst().mNotification);
}
}
});
}
}
/**
* 依据 type 隐藏某通知
*
* @param type 通知类型
*/
protected void hideNotification(int type) {
NotificationNode notificationNode = findNodeByType(type);
if (notificationNode != null) {
hideNotification(notificationNode);
}
}
/**
* 通过 type 在当前显示队列里查找 NotificationNode
*
* @param type 通知类型
* @return 该类型的通知节点
*/
@Nullable
private NotificationNode findNodeByType(int type) {
for (NotificationNode node : mNodeLinkedList) {
if (node.mNotification != null && type == node.mNotification.mType) {
return node;
}
}
return null;
}
/**
* 开始自动消失的计时消息
*
* @param type 某通知的类型
* @param timeout 自动消失的时间
*/
protected void startTimeout(int type, int timeout) {
if (mHandler != null && timeout != 0) {
mHandler.removeMessages(MSG_HIDE + type);
mHandler.sendEmptyMessageDelayed(MSG_HIDE + type, timeout);
}
}
/**
* 执行某通知的展示逻辑
*
* @param notification 某通知
*/
protected void showNotification(@NonNull final CustomNotification notification) {
try {
if (mNodeLinkedList.isEmpty()) {
//链表如果是空的,则插入数据,并获取第一个展示
insertNotificationLocked(notification);
mNodeLinkedList.getFirst().handleShow();
} else {
if (notification.mType == mNodeLinkedList.getFirst().mNotification.mType) {
insertNotificationLocked(notification);
NotificationNode first = mNodeLinkedList.getFirst();
if (!first.isShowing()) {
// 如果当前 notification 还没有展示,则展示
first.handleShow();
}
} else {
//判断改通知的优先级是否比当前队头的通知高
boolean showImmediately = isHigherPriority(notification);
if (showImmediately) {
final NotificationNode oldFirst = mNodeLinkedList.getFirst();
insertNotificationLocked(notification);
mHandler.post(new Runnable() {
@Override
public void run() {
oldFirst.handleHide(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (!mNodeLinkedList.isEmpty()) {
mNodeLinkedList.getFirst().handleShow();
}
}
});
}
});
} else {
insertNotificationLocked(notification);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 判断改通知的优先级是否比当前队头的通知高
*
* @param notification 需要判别的通知
*/
private boolean isHigherPriority(CustomNotification notification) {
return mNodeLinkedList.isEmpty() || mNodeLinkedList.getFirst().mNotification == null
|| mNodeLinkedList.getFirst().getPriority() < notification.getPriority();
}
/**
* 将新的通知加入到通知队列
*
* @param notification 待入队的通知
*/
private void insertNotificationLocked(@NonNull CustomNotification notification) {
NotificationNode node = new NotificationNode(notification,this);
if (mNodeLinkedList.isEmpty()) {
// 如果当前链表为空,则直接赋值给 headNode
mNodeLinkedList.offerFirst(node);
} else if (mNodeLinkedList.contains(node)) {
// 如果该 type 的通知已经在队列内,则直接更改通知信息并更新 UI
NotificationNode exist = mNodeLinkedList.get(mNodeLinkedList.indexOf(node));
exist.getNotification().setData(notification.getData(), true);
} else if (isHigherPriority(notification)) {
// 如果比队列头部的优先级高,则插入到链表头部
mNodeLinkedList.offerFirst(node);
} else {
// 找到合适的位置,插入到队列中
NotificationNode found = null;
Iterator<NotificationNode> iterator = mNodeLinkedList.iterator();
NotificationNode tmp = iterator.next();
while (tmp != null) {
if (node.compareTo(tmp) == NotificationNode.GREATER) {
found = tmp;
break;
}
if (iterator.hasNext()) {
tmp = iterator.next();
} else {
break;
}
}
if (found == null) {
mNodeLinkedList.offerLast(node);
} else {
mNodeLinkedList.add(mNodeLinkedList.indexOf(found), node);
}
}
}
/**
* 将某 NotificationNode 从链表中去除
*
* @param removeNode 需要移除的 node
*/
private void removeNotificationNode(NotificationNode removeNode) {
if (removeNode == null) {
return;
}
mNodeLinkedList.remove(removeNode);
}
/**
* 发送显示通知的消息
*
* @param notification 需要显示的通知
*/
private void sendMessageShow(CustomNotification notification) {
if (mHandler == null) {
return;
}
Message msg = mHandler.obtainMessage(MSG_SHOW);
Bundle bundle = new Bundle();
bundle.putParcelable(BUNDLE_NOTIFICATION, notification);
msg.setData(bundle);
msg.sendToTarget();
}
/**
* 发送隐藏通知的消息
*
* @param type 需要隐藏的通知类型
*/
private void sendMessageHide(int type) {
if (mHandler == null) {
return;
}
// 这里 message type 加上了通知的 type,是为了能够在 handleHide 时得到需要隐藏的 type,
// 实现不同的通知执行各自的隐藏时间
Message msg = mHandler.obtainMessage(MSG_HIDE + type);
Bundle bundle = new Bundle();
bundle.putInt(BUNDLE_TYPE, type);
msg.setData(bundle);
msg.sendToTarget();
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/NotificationNode.java | Java | package com.yc.notifymessage;
import android.animation.Animator;
import androidx.annotation.NonNull;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/11/9
* desc : 通知栏 通知链表节点
* revise:
* </pre>
*/
public class NotificationNode {
static final int EQUALS = 0;
static final int ERROR = -1;
static final int GREATER = 1;
static final int SMALLER = 2;
public static final int ANIM_DURATION = 200;
protected CustomNotification mNotification;
private final INotificationService<CustomNotification> notificationService;
public NotificationNode(CustomNotification notification,
NotificationManager notificationManager) {
notificationService = new NotificationServiceImpl(notificationManager);
mNotification = notification;
}
int getPriority() {
return mNotification == null ? -1 : mNotification.mPriority;
}
boolean isShowing() {
return notificationService.isShowing();
}
void changeIsShowing(boolean isShowing){
notificationService.changeIsShowing(isShowing);
}
CustomNotification getNotification() {
return mNotification;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof NotificationNode)) {
return false;
}
CustomNotification notification = ((NotificationNode) obj).mNotification;
return notification != null && getNotification() != null
&& notification.mType == getNotification().mType || super.equals(obj);
}
@Override
public int hashCode() {
return mNotification == null ? -1 : mNotification.mType;
}
int compareTo(@NonNull NotificationNode o) {
if (getNotification() == null || o.getNotification() == null) {
return ERROR;
}
int result = getNotification().mPriority - o.getNotification().mPriority;
return result > 0 ? GREATER : result < 0 ? SMALLER : EQUALS;
}
protected void handleShow() {
notificationService.show(mNotification);
}
protected void handleHide(final Animator.AnimatorListener listener) {
notificationService.cancel(mNotification,listener);
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/NotificationServiceImpl.java | Java | package com.yc.notifymessage;
import android.animation.Animator;
import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import androidx.annotation.Nullable;
public class NotificationServiceImpl implements INotificationService<CustomNotification> {
private NotifyContainerView mNotificationContainerView;
@Nullable
private WindowManager mWindowManager;
@Nullable
private WindowManager.LayoutParams mLayoutParams;
private final NotificationManager mNotificationManager;
// 用于标志改 Notification 是否展示
public boolean mIsShowing;
public NotificationServiceImpl(NotificationManager notificationManager){
mNotificationManager = notificationManager;
}
@Override
public void show(CustomNotification notification) {
try {
if (notification == null || notification.getActivity() == null) {
LoggerUtils.log("handleShow returned: mNotification == null || mNotification.getActivity() == null");
return;
}
initNotificationView(notification);
if (mNotificationContainerView == null
|| mNotificationContainerView.getParent() != null
|| mWindowManager == null
|| mLayoutParams == null) {
String reason = "unknown";
if (mNotificationContainerView == null) {
reason = "mNotificationContainerView == null";
} else if (mNotificationContainerView.getParent() != null) {
reason = "mNotificationContainerView.getParent() != null";
} else if (mWindowManager == null) {
reason = "mWindowManager == null";
} else if (mLayoutParams == null) {
reason = "mLayoutParams == null";
}
LoggerUtils.log("handleShow returned: " + reason);
return;
}
if (NotificationUtils.isActivityNotAlive(mNotificationContainerView.getActivity())) {
LoggerUtils.log("handleShow returned: activity is finishing or destroyed!");
return;
}
LoggerUtils.log("handleShow before addView: mLayoutParams.token" + mNotificationContainerView.getWindowToken());
mLayoutParams.token = mNotificationContainerView.getWindowToken();
mWindowManager.addView(mNotificationContainerView, mLayoutParams);
LoggerUtils.log("handleShow after addView");
changeIsShowing(true);
mNotificationContainerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (mNotificationContainerView == null) {
LoggerUtils.log("handleShow animation: mNotificationContainerView == null");
return;
} else if (NotificationUtils.isActivityNotAlive(mNotificationContainerView.getActivity())) {
LoggerUtils.log("handleShow animation: mNotificationContainerView.getActivity() is not alive : "
+ mNotificationContainerView.getActivity());
return;
} else if (notification == null) {
LoggerUtils.log("handleShow animation: mNotification == null");
return;
}
resetAnimation(mNotificationContainerView);
mNotificationContainerView.animate().translationY(0).setDuration(NotificationNode.ANIM_DURATION).start();
mNotificationManager.startTimeout(notification.mType, notification.getTimeout());
mNotificationContainerView.removeOnLayoutChangeListener(this);
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void cancel(CustomNotification notification , Animator.AnimatorListener listener) {
if (mNotificationContainerView == null) {
return;
}
resetAnimation(mNotificationContainerView);
mNotificationContainerView.animate().translationY(-mNotificationContainerView.getHeight()).setDuration(NotificationNode.ANIM_DURATION);
mNotificationContainerView.animate().setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
if (listener != null) {
listener.onAnimationStart(animation);
}
}
@Override
public void onAnimationEnd(Animator animation) {
if (mWindowManager != null && mNotificationContainerView != null
&& mNotificationContainerView.getParent() != null) {
mWindowManager.removeViewImmediate(mNotificationContainerView);
}
if (listener != null) {
listener.onAnimationEnd(animation);
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (listener != null) {
listener.onAnimationCancel(animation);
}
}
@Override
public void onAnimationRepeat(Animator animation) {
if (listener != null) {
listener.onAnimationRepeat(animation);
}
}
});
mNotificationContainerView.animate().start();
changeIsShowing(false);
}
@Override
public boolean isShowing() {
return mIsShowing;
}
@Override
public void changeIsShowing(boolean isShowing) {
mIsShowing = isShowing;
}
private void initNotificationView(CustomNotification notification) {
Context context = notification.getActivity();
if (notification.getNotificationView().getView() == null
|| notification.getNotificationView().getView().getParent() != null) {
return;
}
if (context == null){
return;
}
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
mLayoutParams.format = PixelFormat.TRANSLUCENT;
mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayoutParams.gravity = Gravity.TOP;
mLayoutParams.x = 0;
mLayoutParams.y = NotificationUtils.getNotificationLocationY(context);
mNotificationContainerView = new NotifyContainerView(context);
ViewGroup.LayoutParams vl = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mNotificationContainerView.setLayoutParams(vl);
mNotificationContainerView.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
mNotificationManager.hideNotification();
}
});
mNotificationContainerView.addView(notification.getNotificationView().getView());
mNotificationContainerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
mNotificationContainerView.setTranslationY(-mNotificationContainerView.getHeight());
mNotificationContainerView.removeOnLayoutChangeListener(this);
}
});
mNotificationContainerView.setCollapsible(notification.mIsCollapsible);
}
/**
* 取消当前的动画
*/
private void resetAnimation(View view) {
if (view == null) {
return;
}
view.animate().cancel();
view.animate().setListener(null);
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/NotificationUtils.java | Java | package com.yc.notifymessage;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.view.Window;
public final class NotificationUtils {
public static int getNotificationLocationY(Context context) {
if (context instanceof Activity) {
Activity activity = (Activity) context;
Window window = activity.getWindow();
if (window == null) {
return 0;
}
View view = window.findViewById(android.R.id.content);
if (view == null) {
return 0;
}
int[] location = new int[2];
view.getLocationOnScreen(location);
return location[1];
} else {
return 0;
}
}
public static boolean isActivityNotAlive(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return !(context instanceof Activity) || ((Activity) context).isFinishing()
|| ((Activity) context).isDestroyed();
}
return !(context instanceof Activity) || ((Activity) context).isFinishing();
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/NotificationView.java | Java | package com.yc.notifymessage;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import androidx.annotation.CallSuper;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/11/9
* desc : 通知栏 提供通知样式的 View 的类
* revise:
* </pre>
*/
public abstract class NotificationView<T> {
private View mView; // 实际显示的通知的 View
private final Activity mActivity;
private CustomNotification<T> mNotification; // 通知的配置类
public NotificationView(@NonNull Activity activity) {
mActivity = activity;
initView();
}
private void initView() {
int layoutRes = provideLayoutResourceId();
if (layoutRes == 0) {
throw new IllegalArgumentException("layout res is illegal!");
}
mView = LayoutInflater.from(mActivity).inflate(layoutRes, null);
setView(mView);
setClickableViewListener(mView);
}
/**
* view相关操作
* @param view view
*/
private void setView(View view) {
}
public View getView() {
return mView;
}
/**
* 子类需复写来提供 View 的 layout id
* @return
*/
@LayoutRes
public abstract int provideLayoutResourceId();
/**
* 子类复写,来指定那些 View 可以响应 OnClick 事件。
* @return
*/
public abstract int[] provideClickableViewArray();
@CallSuper
public void bindNotification(CustomNotification<T> notification) {
this.mNotification = notification;
}
public Activity getActivity() {
return mActivity;
}
protected <T extends View> T findViewById(@IdRes int id) {
if (mView == null) {
throw new NullPointerException("View is not created!");
}
return mView.findViewById(id);
}
private void setClickableViewListener(View view) {
if (view == null) {
return;
}
int[] clickableViewArray = provideClickableViewArray();
for (int id : clickableViewArray) {
if (id != 0) {
setClickListener(view.findViewById(id));
}
}
}
private void setClickListener(View view) {
if (view == null) {
return;
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (NotificationView.this.onClick(v, v.getId())) {
NotificationView.this.hide();
}
}
});
}
private void hide() {
NotificationManager.getInstance().cancel(mNotification.mType);
}
/**
* view 中的点击事件
* @param view 任意 view 控件
* @param id view 的 id
* @return 点击后是否要收起 Notification view,true:主动收起,false:不主动收起,按照配置自主进行
*/
protected boolean onClick(View view, int id) {
return false;
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/NotifyContainerView.java | Java | package com.yc.notifymessage;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/11/9
* desc : 上划隐藏的布局
* revise:
* </pre>
*/
public class NotifyContainerView extends FrameLayout {
private static final int SLOP = 10;
private float mLastY;
private boolean mIsCollapsible;
private boolean mIsConsumeTouchEvent;
private OnDismissListener mOnDismissListener;
public NotifyContainerView(@NonNull Context context) {
this(context,null);
}
public NotifyContainerView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public NotifyContainerView(@NonNull Context context,
@Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setCollapsible(boolean collapsible) {
mIsCollapsible = collapsible;
}
public void setOnDismissListener(OnDismissListener onDismissListener) {
mOnDismissListener = onDismissListener;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (!mIsCollapsible) {
return super.dispatchTouchEvent(event);
}
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mLastY = event.getY();
mIsConsumeTouchEvent = false;
break;
case MotionEvent.ACTION_MOVE:
if (mIsConsumeTouchEvent) {
break;
}
float mCurrentY = event.getY();
if (mLastY - mCurrentY > SLOP) {
View child = getChildAt(0);
if (child != null) {
if (mOnDismissListener != null) {
mOnDismissListener.onDismiss();
}
mIsConsumeTouchEvent = true;
return true;
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsConsumeTouchEvent = false;
break;
}
return super.dispatchTouchEvent(event);
}
@Nullable
public Activity getActivity() {
return getContext() instanceof Activity ? (Activity) getContext() : null;
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
NotifyMessage/src/main/java/com/yc/notifymessage/OnDismissListener.java | Java | package com.yc.notifymessage;
public interface OnDismissListener {
void onDismiss();
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/build.gradle | Gradle | apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
applicationId "com.yc.cn.ycnotification"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.github.yangchong211.YCNotification:NotificationLib:1.0.4'
implementation 'com.github.yangchong211.YCNotification:NotifyMessage:1.0.4'
// implementation project(path: ':NotificationLib')
// implementation project(path: ':NotifyMessage')
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/HomeActivity.java | Java | package com.yc.cn.ycnotification;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.yc.cn.ycnotification.service.ServiceActivity;
public class HomeActivity extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tv1 = findViewById(R.id.tv_1);
tv2 = findViewById(R.id.tv_2);
tv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this,MainActivity.class));
}
});
tv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this, ServiceActivity.class));
}
});
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/MainActivity.java | Java | package com.yc.cn.ycnotification;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.yc.notifymessage.CustomNotification;
import com.ycbjie.notificationlib.NotificationParams;
import com.ycbjie.notificationlib.NotificationUtils;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private NotificationManager mNotificationManager;
private TextView tv_1;
private TextView tv_2;
private TextView tv_3;
private TextView tv_4;
private TextView tv_5;
private TextView tv_6;
private TextView tv_7;
private TextView tv_8;
private TextView tv_9;
private TextView tv_10;
private TextView tv_11;
private TextView tv_12;
private TextView tv_13;
private TextView tv_14;
private TextView tv_15;
private TextView tv_16;
private TextView tv_17;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
initView();
initListener();
initNotificationManager();
}
private void initView() {
tv_1 = (TextView) findViewById(R.id.tv_1);
tv_2 = (TextView) findViewById(R.id.tv_2);
tv_3 = (TextView) findViewById(R.id.tv_3);
tv_4 = (TextView) findViewById(R.id.tv_4);
tv_5 = (TextView) findViewById(R.id.tv_5);
tv_6 = (TextView) findViewById(R.id.tv_6);
tv_7 = (TextView) findViewById(R.id.tv_7);
tv_8 = (TextView) findViewById(R.id.tv_8);
tv_9 = (TextView) findViewById(R.id.tv_9);
tv_10 = (TextView) findViewById(R.id.tv_10);
tv_11 = (TextView) findViewById(R.id.tv_11);
tv_12 = (TextView) findViewById(R.id.tv_12);
tv_13 = (TextView) findViewById(R.id.tv_13);
tv_14 = (TextView) findViewById(R.id.tv_14);
tv_15 = (TextView) findViewById(R.id.tv_15);
tv_16= (TextView) findViewById(R.id.tv_16);
tv_17= (TextView) findViewById(R.id.tv_17);
}
private void initListener() {
tv_1.setOnClickListener(this);
tv_2.setOnClickListener(this);
tv_3.setOnClickListener(this);
tv_4.setOnClickListener(this);
tv_5.setOnClickListener(this);
tv_6.setOnClickListener(this);
tv_7.setOnClickListener(this);
tv_8.setOnClickListener(this);
tv_9.setOnClickListener(this);
tv_10.setOnClickListener(this);
tv_11.setOnClickListener(this);
tv_12.setOnClickListener(this);
tv_13.setOnClickListener(this);
tv_14.setOnClickListener(this);
tv_15.setOnClickListener(this);
tv_16.setOnClickListener(this);
tv_17.setOnClickListener(this);
}
private void initNotificationManager() {
// 创建一个NotificationManager的引用
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_1:
cancelAllNotification();
break;
case R.id.tv_2:
sendNotification1();
break;
case R.id.tv_3:
sendNotification2();
break;
case R.id.tv_4:
sendNotification3();
break;
case R.id.tv_5:
sendNotification4();
break;
case R.id.tv_6:
Intent intent = new Intent(this,ReminderReceiver.class);
sendBroadcast(intent);
break;
case R.id.tv_7:
break;
case R.id.tv_8:
sendNotification8();
break;
case R.id.tv_9:
sendNotification9();
break;
case R.id.tv_10:
sendNotification10();
break;
case R.id.tv_11:
sendNotification11();
break;
case R.id.tv_12:
sendNotification12();
break;
case R.id.tv_13:
sendNotification13();
break;
case R.id.tv_14:
sendNotification14();
break;
case R.id.tv_15:
sendNotification15();
break;
case R.id.tv_16:
sendNotification16();
break;
case R.id.tv_17:
sendNotification17();
break;
default:
break;
}
}
private void cancelAllNotification() {
NotificationUtils notificationUtils = new NotificationUtils(this);
notificationUtils.clearNotification();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationUtils.getManager().deleteNotificationChannel("channel_1");
}
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// //判断通知是否是静默不重要的通知
// boolean isNoImportance = notificationUtils.isNoImportance("channel_id");
// //跳转设置中心
// notificationUtils.openChannelSetting("channel_id");
// //清空特定渠道的通知
// notificationUtils.clearNotificationChannel("channel");
// //清空所有的通知
// notificationUtils.clearAllNotification();
// }
}
private void sendNotification1() {
//这三个属性是必须要的,否则异常
NotificationUtils notificationUtils = new NotificationUtils(
this,"channel_1","通知1");
notificationUtils.sendNotification(1,
"这个是标题","这个是内容",R.mipmap.ic_launcher);
}
private void sendNotification2() {
//处理点击Notification的逻辑
//创建intent
Intent resultIntent = new Intent(this, TestActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //添加为栈顶Activity
resultIntent.putExtra("what",2);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,2,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
// 定义Notification的各种属性
NotificationUtils notificationUtils = new NotificationUtils(
this,"channel_2","通知2");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel =
notificationUtils.getNotificationChannel("channel_2");
if (notificationUtils.isNoImportance(notificationChannel)){
notificationUtils.openChannelSetting(notificationChannel);
}
}
NotificationParams notificationParams = new NotificationParams();
notificationParams.setContentIntent(resultPendingIntent);
notificationUtils
.setNotificationParams(notificationParams)
.sendNotificationCompat(2,"这个是标题2", "这个是内容2", R.mipmap.ic_launcher);
}
private void sendNotification3() {
long[] vibrate = new long[]{0, 500, 1000, 1500};
//处理点击Notification的逻辑
//创建intent
Intent resultIntent = new Intent(this, TestActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //添加为栈顶Activity
resultIntent.putExtra("what",3);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,3,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//发送pendingIntent
NotificationUtils notificationUtils = new NotificationUtils(
this,"channel_3","通知3");
NotificationParams notificationParams = new NotificationParams();
notificationParams
//让通知左右滑的时候是否可以取消通知
.setOngoing(true)
//设置内容点击处理intent
.setContentIntent(resultPendingIntent)
//设置状态栏的标题
.setTicker("来通知消息啦")
//设置自定义view通知栏布局
.setContent(getRemoteViews())
//设置sound
.setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
//设置优先级
.setPriority(Notification.PRIORITY_DEFAULT)
//自定义震动效果
.setVibrate(vibrate);
//必须设置的属性,发送通知
notificationUtils.setNotificationParams(notificationParams)
.sendNotification(3,"这个是标题3", "这个是内容3", R.mipmap.ic_launcher);
}
private void sendNotification4() {
NotificationUtils notificationUtils = new NotificationUtils(this);
NotificationParams notificationParams = new NotificationParams();
notificationParams.setContent(getRemoteViews());
notificationUtils.setNotificationParams(notificationParams);
Notification notification = notificationUtils.getNotification("这个是标题4", "这个是内容4", R.mipmap.ic_launcher);
notificationUtils.getManager().notify(4,notification);
}
private RemoteViews getRemoteViews() {
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_mobile_play);
// 设置 点击通知栏的上一首按钮时要执行的意图
remoteViews.setOnClickPendingIntent(R.id.btn_pre, getActivityPendingIntent(11));
// 设置 点击通知栏的下一首按钮时要执行的意图
remoteViews.setOnClickPendingIntent(R.id.btn_next, getActivityPendingIntent(12));
// 设置 点击通知栏的播放暂停按钮时要执行的意图
remoteViews.setOnClickPendingIntent(R.id.btn_start, getActivityPendingIntent(13));
// 设置 点击通知栏的根容器时要执行的意图
remoteViews.setOnClickPendingIntent(R.id.ll_root, getActivityPendingIntent(14));
remoteViews.setTextViewText(R.id.tv_title, "标题"); // 设置通知栏上标题
remoteViews.setTextViewText(R.id.tv_artist, "艺术家"); // 设置通知栏上艺术家
return remoteViews;
}
/** 获取一个Activity类型的PendingIntent对象 */
private PendingIntent getActivityPendingIntent(int what) {
Intent intent = new Intent(this, TestActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //添加为栈顶Activity
intent.putExtra("what", what);
PendingIntent pendingIntent = PendingIntent.getActivity(this, what, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
private void sendNotification8() {
for(int a=0 ; a<3 ; a++){
//这三个属性是必须要的,否则异常
NotificationUtils notificationUtils = new NotificationUtils(this);
notificationUtils.sendNotification(8,"这个是标题8","这个是内容8",R.mipmap.ic_launcher);
}
}
private void sendNotification9() {
NotificationUtils notificationUtils = new NotificationUtils(this);
NotificationParams notificationParams = new NotificationParams();
NotificationParams params = notificationParams
//让通知左右滑的时候是否可以取消通知
.setOngoing(true)
//设置状态栏的标题
.setTicker("有新消息呢9")
//设置自定义view通知栏布局
.setContent(getRemoteViews())
//设置sound
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
//设置优先级
.setPriority(Notification.PRIORITY_DEFAULT)
//自定义震动效果
.setFlags(Notification.FLAG_NO_CLEAR);
//必须设置的属性,发送通知
notificationUtils
.setNotificationParams(params)
.sendNotification(9,"有新消息呢9",
"这个是标题9", R.mipmap.ic_launcher);
}
private void sendNotification10() {
//处理点击Notification的逻辑
//创建intent
Intent resultIntent = new Intent(this, TestActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //添加为栈顶Activity
resultIntent.putExtra("what",10);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,10,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//设置 Notification 的 flags = FLAG_NO_CLEAR
//FLAG_NO_CLEAR 表示该通知不能被状态栏的清除按钮给清除掉,也不能被手动清除,但能通过 cancel() 方法清除
//flags 可以通过 |= 运算叠加效果
NotificationUtils notificationUtils = new NotificationUtils(this);
NotificationParams notificationParams = new NotificationParams();
notificationParams
//让通知左右滑的时候是否可以取消通知
.setOngoing(true)
.setContentIntent(resultPendingIntent)
//设置状态栏的标题
.setTicker("有新消息呢10")
//设置自定义view通知栏布局
.setContent(getRemoteViews())
.setDefaults(Notification.DEFAULT_ALL)
//设置sound
.setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
//设置优先级
.setPriority(Notification.PRIORITY_DEFAULT)
//自定义震动效果
.setFlags(Notification.FLAG_AUTO_CANCEL);
//必须设置的属性,发送通知
notificationUtils.setNotificationParams(notificationParams)
.sendNotification(10,"有新消息呢10", "这个是标题10", R.mipmap.ic_launcher);
}
private void sendNotification11() {
NotificationUtils notificationUtils = new NotificationUtils(this);
NotificationParams notificationParams = new NotificationParams();
notificationParams
.setOngoing(false)
.setTicker("来通知消息啦")
.setContent(getRemoteViews())
//.setSound(Uri.parse("android.resource://com.yc.cn.ycnotification/" + R.raw.hah))
.setSound(Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"2"))
.setPriority(Notification.PRIORITY_DEFAULT);
notificationUtils.setNotificationParams(notificationParams).sendNotification(11,"我是伴有铃声效果的通知11", "美妙么?安静听~11", R.mipmap.ic_launcher);
}
private void sendNotification12() {
//震动也有两种设置方法,与设置铃声一样,在此不再赘述
long[] vibrate = new long[]{0, 500, 1000, 1500};
// Notification.Builder builder = new Notification.Builder(this)
// .setSmallIcon(R.mipmap.ic_launcher)
// .setContentTitle("我是伴有震动效果的通知")
// .setContentText("颤抖吧,逗比哈哈哈哈哈~")
// //使用系统默认的震动参数,会与自定义的冲突
// //.setDefaults(Notification.DEFAULT_VIBRATE)
// //自定义震动效果
// .setVibrate(vibrate);
// //另一种设置震动的方法
// //Notification notify = builder.build();
// //调用系统默认震动
// //notify.defaults = Notification.DEFAULT_VIBRATE;
// //调用自己设置的震动
// //notify.vibrate = vibrate;
// //mManager.notify(3,notify);
// mNotificationManager.notify(12, builder.build());
NotificationUtils notificationUtils = new NotificationUtils(this);
NotificationParams notificationParams = new NotificationParams();
notificationParams
.setPriority(Notification.PRIORITY_DEFAULT)
.setVibrate(vibrate);
notificationUtils.setNotificationParams(notificationParams);
notificationUtils.sendNotification(12,"我是伴有震动效果的通知", "颤抖吧,逗比哈哈哈哈哈~", R.mipmap.ic_launcher);
}
private void sendNotification13() {
NotificationUtils notificationUtils = new NotificationUtils(this);
NotificationParams notificationParams = new NotificationParams();
notificationParams
.setDefaults(Notification.DEFAULT_ALL)
.setFlags(Notification.FLAG_ONLY_ALERT_ONCE);
notificationUtils.setNotificationParams(notificationParams)
.sendNotification(13,"仔细看,我就执行一遍","好了,已经一遍了~",R.mipmap.ic_launcher);
}
private void sendNotification14() {
NotificationUtils notificationUtils = new NotificationUtils(this);
NotificationParams notificationParams = new NotificationParams();
notificationParams
.setDefaults(Notification.DEFAULT_ALL)
.setFlags(Notification.FLAG_ONLY_ALERT_ONCE);
notificationUtils.setNotificationParams(notificationParams).sendNotification(14,"显示进度条14","显示进度条内容,自定定义",R.mipmap.ic_launcher);
}
/**
* 错误代码
*/
private void ssendNotification151() {
String id = "channel_1";
String description = "123";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(id, "123", importance);
// mChannel.setDescription(description);
// mChannel.enableLights(true);
// mChannel.setLightColor(Color.RED);
// mChannel.enableVibration(true);
// mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
Notification notification = new Notification.Builder(this, id)
.setContentTitle("Title")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle("您有一条新通知")
.setContentText("这是一条逗你玩的消息")
.setAutoCancel(true)
// .setContentIntent(pintent)
.build();
mNotificationManager.notify(1, notification);
}
}
private void sendNotification15() {
NotificationUtils notificationUtils = new NotificationUtils(this);
notificationUtils.sendNotification(15,"新消息来了","周末到了,不用上班了",R.mipmap.ic_launcher);
}
private void sendNotification16(){
new CustomNotification<Void>()
.setType(1)
.setCollapsible(false)
.setTimeOut(3000)
.setPriority(100)
.setNotificationView(new MyNotifyView(this))
.show();
}
private void sendNotification17(){
new CustomNotification<Void>()
.setType(1)
.setCollapsible(false)
.setTimeOut(5000)
.setPriority(60)
.setNotificationView(new MyNotifyView2(this))
.show();
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/MyNotifyView.java | Java | package com.yc.cn.ycnotification;
import android.app.Activity;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.yc.notifymessage.CustomNotification;
import com.yc.notifymessage.NotificationView;
public class MyNotifyView extends NotificationView<Void> {
public MyNotifyView(@NonNull Activity activity) {
super(activity);
}
@Override
public int provideLayoutResourceId() {
return R.layout.notify_custom_view;
}
@Override
public int[] provideClickableViewArray() {
return new int[]{R.id.btn_click};
}
@Override
protected boolean onClick(View view, int id) {
switch (id) {
case R.id.btn_click:
Toast.makeText(view.getContext(),"点击吐司",Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
@Override
public void bindNotification(CustomNotification<Void> notification) {
super.bindNotification(notification);
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/MyNotifyView2.java | Java | package com.yc.cn.ycnotification;
import android.app.Activity;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.yc.notifymessage.CustomNotification;
import com.yc.notifymessage.NotificationView;
public class MyNotifyView2 extends NotificationView<Void> {
public MyNotifyView2(@NonNull Activity activity) {
super(activity);
}
@Override
public int provideLayoutResourceId() {
return R.layout.notify_custom_view2;
}
@Override
public int[] provideClickableViewArray() {
return new int[]{R.id.btn_click};
}
@Override
protected boolean onClick(View view, int id) {
switch (id) {
case R.id.btn_click:
Toast.makeText(view.getContext(),"点击吐司",Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
@Override
public void bindNotification(CustomNotification<Void> notification) {
super.bindNotification(notification);
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/NotificationUtil.java | Java | package com.yc.cn.ycnotification;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.util.Log;
import android.widget.RemoteViews;
import androidx.core.app.NotificationCompat;
import java.util.Timer;
import java.util.TimerTask;
/**
* 显示通知栏工具类
* Created by Administrator on 2016-11-14.
*/
public class NotificationUtil {
/**
* 显示一个普通的通知
*
* @param context 上下文
*/
public static void showNotification(Context context) {
Notification notification = new NotificationCompat.Builder(context)
/**设置通知左边的大图标**/
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
/**设置通知右边的小图标**/
.setSmallIcon(R.mipmap.ic_launcher)
/**通知首次出现在通知栏,带上升动画效果的**/
.setTicker("通知来了")
/**设置通知的标题**/
.setContentTitle("这是一个通知的标题")
/**设置通知的内容**/
.setContentText("这是一个通知的内容这是一个通知的内容")
/**通知产生的时间,会在通知信息里显示**/
.setWhen(System.currentTimeMillis())
/**设置该通知优先级**/
.setPriority(Notification.PRIORITY_DEFAULT)
/**设置这个标志当用户单击面板就可以让通知将自动取消**/
.setAutoCancel(true)
/**设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)**/
.setOngoing(false)
/**向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合:**/
.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
.setContentIntent(PendingIntent.getActivity(context, 1, new Intent(context, MainActivity.class), PendingIntent.FLAG_CANCEL_CURRENT))
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
/**发起通知**/
notificationManager.notify(0, notification);
}
/**
* 显示一个下载带进度条的通知
*
* @param context 上下文
*/
public static void showNotificationProgress(Context context) {
//进度条通知
final NotificationCompat.Builder builderProgress = new NotificationCompat.Builder(context);
builderProgress.setContentTitle("下载中");
builderProgress.setSmallIcon(R.mipmap.ic_launcher);
builderProgress.setTicker("进度条通知");
builderProgress.setProgress(100, 0, false);
final Notification notification = builderProgress.build();
final NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
//发送一个通知
notificationManager.notify(2, notification);
/**创建一个计时器,模拟下载进度**/
Timer timer = new Timer();
timer.schedule(new TimerTask() {
int progress = 0;
@Override
public void run() {
Log.i("progress", progress + "");
while (progress <= 100) {
progress++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//更新进度条
builderProgress.setProgress(100, progress, false);
//再次通知
notificationManager.notify(2, builderProgress.build());
}
//计时器退出
this.cancel();
//进度条退出
notificationManager.cancel(2);
return;//结束方法
}
}, 0);
}
/**
* 悬挂式,支持6.0以上系统
*
* @param context
*/
public static void showFullScreen(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/itachi85/"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mIntent, 0);
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
builder.setAutoCancel(true);
builder.setContentTitle("悬挂式通知");
//设置点击跳转
Intent hangIntent = new Intent();
hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
hangIntent.setClass(context, MainActivity.class);
//如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的
PendingIntent hangPendingIntent = PendingIntent.getActivity(context, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setFullScreenIntent(hangPendingIntent, true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(3, builder.build());
}
/**
* 折叠式
*
* @param context
*/
public static void shwoNotify(Context context) {
//先设定RemoteViews
RemoteViews view_custom = new RemoteViews(context.getPackageName(), R.layout.view_custom);
//设置对应IMAGEVIEW的ID的资源图片
view_custom.setImageViewResource(R.id.custom_icon, R.mipmap.icon);
view_custom.setTextViewText(R.id.tv_custom_title, "今日头条");
view_custom.setTextColor(R.id.tv_custom_title, Color.BLACK);
view_custom.setTextViewText(R.id.tv_custom_content, "金州勇士官方宣布球队已经解雇了主帅马克-杰克逊,随后宣布了最后的结果。");
view_custom.setTextColor(R.id.tv_custom_content, Color.BLACK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContent(view_custom)
.setContentIntent(PendingIntent.getActivity(context, 4, new Intent(context, MainActivity.class), PendingIntent.FLAG_CANCEL_CURRENT))
.setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示
.setTicker("有新资讯")
.setPriority(Notification.PRIORITY_HIGH)// 设置该通知优先级
.setOngoing(false)//不是正在进行的 true为正在进行 效果和.flag一样
.setSmallIcon(R.mipmap.icon);
Notification notify = mBuilder.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(4, notify);
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/ReminderReceiver.java | Java | package com.yc.cn.ycnotification;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ReminderReceiver extends BroadcastReceiver {
private static final String TAG = "ReminderReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "ReminderReceiver");
//Calendar now = GregorianCalendar.getInstance();
Notification.Builder mBuilder = new Notification.Builder(context)
.setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("广播接受者标题,小杨")
.setContentText("广播接受者内容,扯犊子")
.setAutoCancel(true);
Log.i(TAG, "onReceive: intent" + intent.getClass().getName());
Intent resultIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
//将该Activity添加为栈顶
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/TestActivity.java | Java | package com.yc.cn.ycnotification;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
/**
* Created by PC on 2017/12/7.
* 作者:PC
*/
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
TextView tv = (TextView) findViewById(R.id.tv);
int what = getIntent().getIntExtra("what", 0);
switch (what){
case 1:
tv.setText("2.在Activity中发送通知1,最简单的通知");
break;
case 2:
tv.setText("3.在Activity中发送通知2,添加action");
break;
case 3:
tv.setText("4.在Activity中发送通知3,设置通知栏左右滑动不删除");
break;
case 4:
tv.setText("点击通知栏的根容器时要执行的意图");
break;
case 5:
tv.setText("在Activity中发送通知");
break;
case 6:
tv.setText("在广播中发送通知");
break;
case 7:
tv.setText("在广播中发送通知");
break;
case 8:
break;
case 9:
tv.setText("9.在Activity中发通知,设置通知不能被状态栏的清除按钮给清除掉,也不能被手动清除,但能通过 cancel() 方法清除");
break;
case 10:
tv.setText("10.在Activity中发通知,设置用户单击通知后自动消失");
break;
case 11:
tv.setText("上一首");
break;
case 12:
tv.setText("下一首");
break;
case 13:
tv.setText("播放暂停");
break;
case 14:
tv.setText("点击通知栏的根容器时要执行的意图");
break;
default:
break;
}
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/service/BaseService.java | Java | package com.yc.cn.ycnotification.service;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.Nullable;
/**
* Service 基类
* IntentService 在任务执行完后会自动关闭。这里将它的行为修改一下,关闭前判断条件
*/
public abstract class BaseService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
protected final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent) msg.obj);
if (canStopSelf()) {
stopSelf(msg.arg1);
}
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public BaseService(String name) {
super();
mName = name;
}
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see Service#onStartCommand
*/
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
mServiceLooper.quit();
}
public ServiceHandler getServiceHandler() {
return mServiceHandler;
}
protected abstract void onHandleIntent(Intent intent);
protected abstract boolean canStopSelf();
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/service/MyForegroundService.java | Java | package com.yc.cn.ycnotification.service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.yc.cn.ycnotification.HomeActivity;
import com.yc.cn.ycnotification.R;
public class MyForegroundService extends Service {
private final String channelId = "yc_delivery_service";
public static final int NOTIFICATION_ID_SERVICE = 104;
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d("Service","MyForegroundService onBind");
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("Service","MyForegroundService onCreate");
startForeground("yangchong") ;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Service","MyForegroundService onDestroy");
//如果设置成ture,则会移除通知栏
stopForeground(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private void startForeground(String title){
Log.d("Service","MyForegroundService startForeground : " +title);
try {
createNotificationChannel(channelId, "测试");
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
Intent intentMainActivity = new Intent(this, HomeActivity.class);
intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0,
intentMainActivity, 0);
builder.setContentIntent(pi)
.setSmallIcon(R.drawable.ic_notification_music_logo)
.setContentTitle("setContentTitle")
.setContentText(title);
Notification notification = builder.build();
////把该service创建为前台service
////把该service创建为前台service
startForeground(NOTIFICATION_ID_SERVICE, notification);
} catch (Exception e) {
Log.d("Service","MyForegroundService startForeground : " +e.getMessage());
}
}
/**
* Android8.0之后必须要有channel
*/
private void createNotificationChannel(String channelId, CharSequence channelName) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = notificationManager.getNotificationChannel(channelId);
if (null == channel) {
channel = new NotificationChannel(channelId, channelName,
NotificationManager.IMPORTANCE_DEFAULT);
}
notificationManager.createNotificationChannel(channel);
}
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/service/MyForegroundService2.java | Java | package com.yc.cn.ycnotification.service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.yc.cn.ycnotification.HomeActivity;
import com.yc.cn.ycnotification.R;
public class MyForegroundService2 extends Service {
private final String channelId = "yc_delivery_service";
public static final int NOTIFICATION_ID_SERVICE = 104;
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d("Service2","MyForegroundService onBind");
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("Service2","MyForegroundService onCreate");
startForeground("yangchong2") ;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Service2","MyForegroundService onDestroy");
//如果设置成ture,则会移除通知栏
stopForeground(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private void startForeground(String title){
Log.d("Service2","MyForegroundService startForeground : " +title);
try {
createNotificationChannel(channelId, "测试");
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
Intent intentMainActivity = new Intent(this, HomeActivity.class);
intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0,
intentMainActivity, 0);
builder.setContentIntent(pi)
.setSmallIcon(R.drawable.btn_audio_pre_normal)
.setContentTitle("setContentTitle")
.setContentText(title);
Notification notification = builder.build();
////把该service创建为前台service
////把该service创建为前台service
startForeground(NOTIFICATION_ID_SERVICE, notification);
} catch (Exception e) {
Log.d("Service2","MyForegroundService startForeground : " +e.getMessage());
}
}
/**
* Android8.0之后必须要有channel
*/
private void createNotificationChannel(String channelId, CharSequence channelName) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = notificationManager.getNotificationChannel(channelId);
if (null == channel) {
channel = new NotificationChannel(channelId, channelName,
NotificationManager.IMPORTANCE_DEFAULT);
}
notificationManager.createNotificationChannel(channel);
}
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/service/MyService.java | Java | package com.yc.cn.ycnotification.service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
public class MyService extends BaseService {
public MyService(String name) {
//super(name);
super("MyService");
Log.d("Service","MyService MyService : " +name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d("Service","MyService onHandleIntent");
}
@Override
protected boolean canStopSelf() {
return false;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d("Service","MyService onBind");
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("Service","MyService onCreate");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Service","MyService onDestroy");
}
public static void startRiderService(Context context) {
Log.d("Service","MyService startRiderService");
Intent intent = new Intent(context, MyForegroundService.class);
ContextCompat.startForegroundService(context, intent);
}
public static void stopRiderService(Context context) {
Log.d("Service","MyService stopRiderService");
Intent intent = new Intent(context, MyForegroundService.class);
context.stopService(intent);
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/service/MyService2.java | Java | package com.yc.cn.ycnotification.service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
public class MyService2 extends BaseService {
public MyService2(String name) {
//super(name);
super("MyService2");
Log.d("Service2","MyService MyService : " +name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d("Service2","MyService onHandleIntent");
}
@Override
protected boolean canStopSelf() {
return false;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d("Service2","MyService onBind");
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("Service2","MyService onCreate");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Service2","MyService onDestroy");
}
public static void startRiderService(Context context) {
Log.d("Service2","MyService startRiderService");
Intent intent = new Intent(context, MyForegroundService2.class);
ContextCompat.startForegroundService(context, intent);
}
public static void stopRiderService(Context context) {
Log.d("Service2","MyService stopRiderService");
Intent intent = new Intent(context, MyForegroundService2.class);
context.stopService(intent);
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/com/yc/cn/ycnotification/service/ServiceActivity.java | Java | package com.yc.cn.ycnotification.service;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import com.yc.cn.ycnotification.MainActivity;
import com.yc.cn.ycnotification.R;
import com.yc.cn.ycnotification.TestActivity;
import java.util.List;
public class ServiceActivity extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
private TextView tv3;
private TextView tv4;
private TextView tv5;
private TextView tv6;
private TextView tv7;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
tv1 = findViewById(R.id.tv_1);
tv2 = findViewById(R.id.tv_2);
tv3 = findViewById(R.id.tv_3);
tv4 = findViewById(R.id.tv_4);
tv5 = findViewById(R.id.tv_5);
tv6 = findViewById(R.id.tv_6);
tv7 = findViewById(R.id.tv_7);
tv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyService.startRiderService(ServiceActivity.this);
}
});
tv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyService.stopRiderService(ServiceActivity.this);
}
});
tv3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyService2.startRiderService(ServiceActivity.this);
}
});
tv4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyService2.stopRiderService(ServiceActivity.this);
}
});
tv5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
send();
// createChannel();
}
});
tv6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mNotificationManager!=null){
mNotificationManager.cancel(DIALOG_TIME_SEC);
}
}
});
tv7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mNotificationManager!=null){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// mNotificationManager.deleteNotificationChannel(LOCAL_CHANNEL_ID);
test();
}
}
}
});
}
private NotificationManager mNotificationManager;
private static final String LOCAL_CHANNEL_ID = "RIDER_LOCAL_CHANNEL_ID";
public static final int DIALOG_TIME_SEC = 2;
private void send(){
// 创建一个NotificationManager的引用
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(LOCAL_CHANNEL_ID,
"Channel Notifications", NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
}
Intent intent = new Intent(this, TestActivity.class);
//添加为栈顶Activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, LOCAL_CHANNEL_ID)
.setContentTitle("Title")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle("您有一条新通知")
.setContentText("这是一条逗你玩的消息")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true)
.build();
mNotificationManager.notify(DIALOG_TIME_SEC, notification);
}
private void createChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "chat";
String channelName = "通知消息";
int importance = NotificationManager.IMPORTANCE_HIGH;
createNotificationChannel(channelId, channelName, importance);
channelId = "email";
channelName = "通知邮件";
importance = NotificationManager.IMPORTANCE_DEFAULT;
createNotificationChannel(channelId, channelName, importance);
channelId = "subscribe";
channelName = "通知订阅";
importance = NotificationManager.IMPORTANCE_LOW;
createNotificationChannel(channelId, channelName, importance);
}
}
public void sendChatMsg() {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = manager.getNotificationChannel("chat");
if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel.getId());
startActivity(intent);
Toast.makeText(this, "请手动将通知打开", Toast.LENGTH_SHORT).show();
return;
}
}
Notification notification = new NotificationCompat.Builder(this, "chat")
.setContentTitle("收到聊天消息")
.setContentText("在吗,找你有事情")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_notification_music_logo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification_music_logo))
.setAutoCancel(true)
.build();
manager.notify(1, notification);
}
public void sendSubscribeMsg() {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this, "subscribe")
.setContentTitle("收到订阅消息")
.setContentText("告诉你个好消息!")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_notification_music_logo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification_music_logo))
.setAutoCancel(true)
.build();
manager.notify(2, notification);
}
public void sendEmailMsg() {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this, "subscribe")
.setContentTitle("收到邮件消息")
.setContentText("逗比收到一封邮件")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_notification_music_logo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification_music_logo))
.setAutoCancel(true)
.build();
manager.notify(3, notification);
}
@TargetApi(Build.VERSION_CODES.O)
private void createNotificationChannel(String channelId, String channelName, int importance) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
if (mNotificationManager==null){
mNotificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
}
mNotificationManager.createNotificationChannel(channel);
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void test(){
if (mNotificationManager!=null){
List<NotificationChannelGroup> notificationChannelGroups =
mNotificationManager.getNotificationChannelGroups();
if (notificationChannelGroups!=null){
for (int i=0 ; i<notificationChannelGroups.size() ; i++){
NotificationChannelGroup notificationChannelGroup = notificationChannelGroups.get(i);
if (notificationChannelGroup == null){
continue;
}
String id = notificationChannelGroup.getId();
CharSequence name = notificationChannelGroup.getName();
Log.d("notification group " , id + " , " + name);
}
}
}
if (mNotificationManager!=null){
List<NotificationChannel> notificationChannels = mNotificationManager.getNotificationChannels();
if (notificationChannels!=null){
for (int i=0 ; i<notificationChannels.size() ; i++){
NotificationChannel notificationChannel = notificationChannels.get(i);
if (notificationChannel == null){
continue;
}
String id = notificationChannel.getId();
CharSequence name = notificationChannel.getName();
Log.d("notification channel " , id + " , " + name);
}
}
}
}
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
build.gradle | Gradle | // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
maven { url 'https://jitpack.io' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
//jitpack
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
}
}
allprojects {
repositories {
google()
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
settings.gradle | Gradle | include ':app', ':NotificationLib'
include ':NotifyMessage'
| yangchong211/YCNotification | 379 | 通知栏封装库,强大的通知栏工具类,链式编程调用,解决了8.0以上通知栏不显示问题,支持多种不同的使用场景,兼容老版本。还有自定义通知栏view,可高度定制布局…… | Java | yangchong211 | 杨充 | Tencent |
AppGradle/app.gradle | Gradle | ext {
androidBuildToolsVersion = "29.0.0"
androidMinSdkVersion = 17
androidTargetSdkVersion = 29
androidCompileSdkVersion = 29
constraintLayoutVersion = '1.1.3'
appcompatVersion = '1.2.0'
annotationVersion = '1.1.0'
cardviewVersion = '1.0.0'
mediaVersion = '1.0.1'
recyclerviewVersion = '1.1.0'
swiperefreshlayoutVersion = '1.0.0'
/**主app-start*/
AppDependencies = [
constraintLayout : "androidx.constraintlayout:constraintlayout:${constraintLayoutVersion}",
appcompat : "androidx.appcompat:appcompat:${appcompatVersion}",
annotation : "androidx.annotation:annotation:${annotationVersion}",
cardview : "androidx.cardview:cardview:${cardviewVersion}",
media : "androidx.media:media:${mediaVersion}",
recyclerview : "androidx.recyclerview:recyclerview:${recyclerviewVersion}",
swiperefreshlayout : "androidx.swiperefreshlayout:swiperefreshlayout:${swiperefreshlayoutVersion}",
]
} | yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
EastAdapterLib/build.gradle | Gradle | plugins {
id 'com.android.library'
}
apply from: rootProject.projectDir.absolutePath + "/AppGradle/app.gradle"
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion project.ext.androidCompileSdkVersion
//buildToolsVersion project.ext.androidBuildToolsVersion
defaultConfig {
minSdkVersion project.ext.androidMinSdkVersion
targetSdkVersion project.ext.androidTargetSdkVersion
versionCode 32
versionName "3.0.2"
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project.ext.AppDependencies['appcompat']
implementation project.ext.AppDependencies['annotation']
implementation project.ext.AppDependencies['recyclerview']
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
EastAdapterLib/src/androidTest/java/com/yc/eastadapterlib/ExampleInstrumentedTest.java | Java | package com.yc.eastadapterlib;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.yc.eastadapterlib.test", appContext.getPackageName());
}
} | yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
EastAdapterLib/src/main/java/com/yc/eastadapterlib/BaseRecycleAdapter.java | Java | package com.yc.eastadapterlib;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* @author yangchong
* email : yangchong211@163.com
* time : 2017/07/15
* desc : 抽象适配器
* revise : 原来的baseAdapter
* </pre>
*/
public abstract class BaseRecycleAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
public Context context;
private int layoutId;
private List<T> data;
public MultiTypeSupport<T> multiTypeSupport;
private OnItemClickListener onItemClickListener;
private OnItemLongClickListener onItemLongClickListener;
private final Object mLock = new Object();
//默认可以回收
private boolean isRecycle;
private int position;
private int line;
private BaseRecycleAdapter() {
//默认可以回收
this.isRecycle = true;
}
/**
* 设置座位数据有几行
* @param line
*/
public void setDataLine(int line) {
this.line = line;
}
/**
* 获取座位数据有几行
* @return
*/
public int getLine() {
return line;
}
/**
* 构造方法
* @param layoutId 布局
* @param context 上下文
*/
public BaseRecycleAdapter(Context context , int layoutId) {
this.layoutId = layoutId;
this.context = context;
data = new ArrayList<>();
//默认可以回收
this.isRecycle = true;
}
/**
* 创建一个ViewHolder
*/
@Override
public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (multiTypeSupport != null) {
layoutId = viewType;
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
BaseViewHolder viewHolder = new BaseViewHolder(view);
if (!isRecycle) {
viewHolder.setIsRecyclable(false);
}
setListener(viewHolder);
return viewHolder;
}
/**
* 绑定数据,创建抽象方法,让子类实现
*/
@Override
public void onBindViewHolder(@NonNull BaseViewHolder holder, @SuppressLint("RecyclerView") int position) {
if(data!=null && data.size()>0){
if (!isRecycle) {
holder.setIsRecyclable(false);
}
this.position = position;
bindData(holder, data.get(position));
}
}
/**
* 获取类型
*/
@Override
public int getItemViewType(int position) {
if (multiTypeSupport != null) {
return multiTypeSupport.getLayoutId(data, position);
}
return super.getItemViewType(position);
}
@Override
public int getItemCount() {
return data==null ? 0 : data.size();
}
/**
* 当子类adapter继承此AbsSeatAdapter时,需要子类实现的绑定数据方法
*/
protected abstract void bindData(BaseViewHolder holder, T t);
/*-------------------------------------操作方法-----------------------------------------------*/
public int getViewPosition(){
return position;
}
/**
* 设置点击事件和长按事件
* @param viewHolder viewHolder
*/
private void setListener(final BaseViewHolder viewHolder) {
if (viewHolder.getItemView()==null){
return;
}
viewHolder.getItemView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
int position = viewHolder.getAdapterPosition();
onItemClickListener.onItemClick(v, position);
}
}
});
viewHolder.getItemView().setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (onItemLongClickListener != null) {
int position = viewHolder.getAdapterPosition();
return onItemLongClickListener.onItemLongClick(v, position);
}
return false;
}
});
}
/**
* 设置数据,并且刷新页面
*/
public void setData(List<T> list){
data.clear();
if(list==null || list.size()==0){
return;
}
synchronized (mLock) {
data.addAll(list);
notifyItemRangeChanged(data.size()-list.size(),data.size());
notifyDataSetChanged();
}
}
/**
* 设置数据T,并且刷新页面
*/
public boolean setData(T t) {
if (t == null) {
return false;
}
if (data.contains(t)) {
return false;
}
synchronized (mLock) {
boolean b = data.add(t);
notifyItemInserted(data.size() - 1);
return b;
}
}
/**
* 在索引position处添加数据t并且刷新
* @param position position
* @param t t
* @return
*/
public boolean setData(int position, T t) {
if (t == null){
return false;
}
if (position < 0 || position > data.size()){
return false;
}
if (data.contains(t)){
return false;
}
synchronized (mLock) {
data.add(position, t);
notifyItemInserted(position);
}
return true;
}
/**
* 在索引position处添加数据list集合并且刷新
* @param position position
* @param list list
* @return
*/
public boolean setData(int position, List<T> list) {
if (list == null) {
return false;
}
if (data.contains(list)){
return false;
}
synchronized (mLock) {
data.addAll(position, list);
notifyItemRangeInserted(position, list.size());
}
return true;
}
/**
* 获取数据
*/
public List<T> getData(){
return data;
}
/**
* 清理所有数据,并且刷新页面
*/
public void clearAll(){
data.clear();
notifyDataSetChanged();
}
/**
* 移除数据
*/
public void remove(T t){
if(data.size()==0){
return;
}
synchronized (mLock) {
int index = data.indexOf(t);
remove(index);
notifyItemRemoved(index);
}
}
/**
* 移除数据
*/
public void remove(int position){
if (position < 0 || position >= data.size()) {
return ;
}
synchronized (mLock) {
data.remove(position);
notifyItemRemoved(position);
}
}
/**
* 移除数据
*/
public void remove(int start,int count){
if(data.size()==0){
return;
}
if((start +count) > data.size()){
return;
}
synchronized (mLock) {
data.subList(start,start+count).clear();
notifyItemRangeRemoved(start,count);
}
}
/**
* 更新数据
* @param position 索引
* @return
*/
public boolean updateItem(int position) {
if (position < 0 || position >= data.size()) {
return false;
}
notifyItemChanged(position);
return true;
}
/**
* 更新数据
* @param t t
* @return
*/
public boolean updateItem(T t) {
if (t == null) {
return false;
}
synchronized (mLock) {
int index = data.indexOf(t);
if (index >= 0) {
data.set(index, t);
notifyItemChanged(index);
return true;
}
}
return false;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
this.onItemLongClickListener = onItemLongClickListener;
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
EastAdapterLib/src/main/java/com/yc/eastadapterlib/BaseViewHolder.java | Java | package com.yc.eastadapterlib;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.SparseArray;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.reflect.Field;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/9/18
* desc : 通用的RecyclerView.ViewHolder。提供了根据viewId获取View的方法。
* </pre>
*/
public class BaseViewHolder extends RecyclerView.ViewHolder {
// SparseArray 比 HashMap 更省内存,在某些条件下性能更好,只能存储 key 为 int 类型的数据,
// 用来存放 View 以减少 findViewById 的次数
private SparseArray<View> viewSparseArray;
//这个是item的对象
private View mItemView;
public BaseViewHolder(View itemView) {
super(itemView);
this.mItemView = itemView;
viewSparseArray = new SparseArray<>();
}
/**
* 根据 ID 来获取 View
* @param viewId viewID
* @param <T> 泛型
* @return 将结果强转为 View 或 View 的子类型
*/
public <T extends View> T getView(int viewId) {
// 先从缓存中找,找打的话则直接返回
// 如果找不到则 findViewById ,再把结果存入缓存中
View view = viewSparseArray.get(viewId);
if (view == null) {
view = itemView.findViewById(viewId);
viewSparseArray.put(viewId, view);
}
return (T) view;
}
/**
* 获取item的对象
*/
@Nullable
public View getItemView(){
return mItemView;
}
/**
* 获取数据索引的位置
* @return position
*/
protected int getDataPosition(){
RecyclerView.Adapter adapter = getOwnerAdapter();
if (adapter!=null && adapter instanceof BaseRecycleAdapter){
return ((BaseRecycleAdapter) adapter).getViewPosition();
}
return getAdapterPosition();
}
/**
* 获取adapter对象
* @param <T>
* @return adapter
*/
private <T extends RecyclerView.Adapter> T getOwnerAdapter(){
RecyclerView recyclerView = getOwnerRecyclerView();
//noinspection unchecked
return recyclerView != null ? (T) recyclerView.getAdapter() : null;
}
@Nullable
private RecyclerView getOwnerRecyclerView(){
try {
Field field = RecyclerView.ViewHolder.class.getDeclaredField("mOwnerRecyclerView");
field.setAccessible(true);
return (RecyclerView) field.get(this);
} catch (NoSuchFieldException ignored) {
} catch (IllegalAccessException ignored) {
}
return null;
}
/**
* 添加子控件的点击事件
* @param viewId 控件id
*/
protected void addOnClickListener(@IdRes final int viewId) {
final View view = getView(viewId);
if (view != null) {
if (!view.isClickable()) {
view.setClickable(true);
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(getOwnerAdapter()!=null){
}
}
});
}
}
/**
* 设置TextView的值
*/
public BaseViewHolder setText(int viewId, String text) {
TextView tv = getView(viewId);
tv.setText(text);
return this;
}
/**
* 设置imageView图片
*/
public BaseViewHolder setImageResource(int viewId, int resId) {
ImageView view = getView(viewId);
view.setImageResource(resId);
return this;
}
/**
* 设置imageView图片
*/
public BaseViewHolder setImageBitmap(int viewId, Bitmap bitmap) {
ImageView view = getView(viewId);
view.setImageBitmap(bitmap);
return this;
}
/**
* 设置imageView图片
*/
public BaseViewHolder setImageDrawable(int viewId, Drawable drawable) {
ImageView view = getView(viewId);
view.setImageDrawable(drawable);
return this;
}
/**
* 设置背景颜色
*/
public BaseViewHolder setBackgroundColor(int viewId, int color) {
View view = getView(viewId);
view.setBackgroundColor(color);
return this;
}
/**
* 设置背景颜色
*/
public BaseViewHolder setBackgroundRes(int viewId, int backgroundRes) {
View view = getView(viewId);
view.setBackgroundResource(backgroundRes);
return this;
}
/**
* 设置text颜色
*/
public BaseViewHolder setTextColor(int viewId, int textColor) {
TextView view = getView(viewId);
view.setTextColor(textColor);
return this;
}
/**
* 设置透明度
*/
@SuppressLint("NewApi")
public BaseViewHolder setAlpha(int viewId, float value) {
if (Build.VERSION_CODES.HONEYCOMB <= Build.VERSION.SDK_INT) {
getView(viewId).setAlpha(value);
} else {
// Pre-honeycomb hack to set Alpha value
AlphaAnimation alpha = new AlphaAnimation(value, value);
alpha.setDuration(0);
alpha.setFillAfter(true);
getView(viewId).startAnimation(alpha);
}
return this;
}
/**
* 设置是否可见
*/
public BaseViewHolder setVisible(int viewId, boolean visible) {
View view = getView(viewId);
view.setVisibility(visible ? View.VISIBLE : View.GONE);
return this;
}
public BaseViewHolder setTypeface(Typeface typeface, int... viewIds) {
for (int viewId : viewIds) {
TextView view = getView(viewId);
view.setTypeface(typeface);
view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
return this;
}
public BaseViewHolder setProgress(int viewId, int progress) {
ProgressBar view = getView(viewId);
view.setProgress(progress);
return this;
}
public BaseViewHolder setProgress(int viewId, int progress, int max) {
ProgressBar view = getView(viewId);
view.setMax(max);
view.setProgress(progress);
return this;
}
public BaseViewHolder setMax(int viewId, int max) {
ProgressBar view = getView(viewId);
view.setMax(max);
return this;
}
public BaseViewHolder setRating(int viewId, float rating) {
RatingBar view = getView(viewId);
view.setRating(rating);
return this;
}
public BaseViewHolder setRating(int viewId, float rating, int max) {
RatingBar view = getView(viewId);
view.setMax(max);
view.setRating(rating);
return this;
}
public BaseViewHolder setTag(int viewId, Object tag) {
View view = getView(viewId);
view.setTag(tag);
return this;
}
public BaseViewHolder setTag(int viewId, int key, Object tag) {
View view = getView(viewId);
view.setTag(key, tag);
return this;
}
public BaseViewHolder setChecked(int viewId, boolean checked) {
Checkable view = (Checkable) getView(viewId);
view.setChecked(checked);
return this;
}
/**
* 关于事件的
*/
public BaseViewHolder setOnClickListener(int viewId, View.OnClickListener listener) {
View view = getView(viewId);
if(view==null){
return null;
}
view.setOnClickListener(listener);
return this;
}
public BaseViewHolder setOnTouchListener(int viewId, View.OnTouchListener listener) {
View view = getView(viewId);
if(view==null){
return null;
}
view.setOnTouchListener(listener);
return this;
}
public BaseViewHolder setOnLongClickListener(int viewId, View.OnLongClickListener listener) {
View view = getView(viewId);
if(view==null){
return null;
}
view.setOnLongClickListener(listener);
return this;
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
EastAdapterLib/src/main/java/com/yc/eastadapterlib/MultiTypeSupport.java | Java | package com.yc.eastadapterlib;
import java.util.List;
/**
* <pre>
* @author yangchong
* email : yangchong211@163.com
* time : 2017/07/15
* desc : 接口
* revise:
* </pre>
*/
public interface MultiTypeSupport<T> {
int getLayoutId(List<T> data, int position);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
EastAdapterLib/src/main/java/com/yc/eastadapterlib/OnItemClickListener.java | Java | package com.yc.eastadapterlib;
import android.view.View;
/**
* <pre>
* @author yangchong
* email : yangchong211@163.com
* time : 2017/07/15
* desc : 点击事件
* revise:
* </pre>
*/
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
EastAdapterLib/src/main/java/com/yc/eastadapterlib/OnItemLongClickListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.yc.eastadapterlib;
import android.view.View;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/4/28
* desc : item中长按点击监听接口
* revise:
* </pre>
*/
public interface OnItemLongClickListener {
/**
* item中长按点击监听接口
* @param position 索引
* @return
*/
boolean onItemLongClick(View view, int position);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
EastAdapterLib/src/test/java/com/yc/eastadapterlib/ExampleUnitTest.java | Java | package com.yc.eastadapterlib;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
PhotoCoverLib/build.gradle | Gradle | apply plugin: 'com.android.library'
apply from: rootProject.projectDir.absolutePath + "/AppGradle/app.gradle"
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion project.ext.androidCompileSdkVersion
//buildToolsVersion project.ext.androidBuildToolsVersion
defaultConfig {
minSdkVersion project.ext.androidMinSdkVersion
targetSdkVersion project.ext.androidTargetSdkVersion
versionCode 32
versionName "3.0.2"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project.ext.AppDependencies['appcompat']
implementation project.ext.AppDependencies['recyclerview']
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
PhotoCoverLib/src/main/java/com/yc/cover/CoverLayoutManger.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.yc.cover;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import androidx.recyclerview.widget.RecyclerView;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/9/11
* desc : 自定义LayoutManager
* revise:
* </pre>
*/
public class CoverLayoutManger extends RecyclerView.LayoutManager {
/**滑动总偏移量*/
private int mOffsetAll = 0;
/**Item宽*/
private int mDecoratedChildWidth = 0;
/**Item高*/
private int mDecoratedChildHeight = 0;
/**Item间隔与item宽的比例*/
private float mIntervalRatio = 0.5f;
/**起始ItemX坐标*/
private int mStartX = 0;
/**起始Item Y坐标*/
private int mStartY = 0;
/**保存所有的Item的上下左右的偏移量信息*/
private SparseArray<Rect> mAllItemFrames = new SparseArray<>();
/**记录Item是否出现过屏幕且还没有回收。true表示出现过屏幕上,并且还没被回收*/
private SparseBooleanArray mHasAttachedItems = new SparseBooleanArray();
/**RecyclerView的Item回收器*/
private RecyclerView.Recycler mRecycle;
/**RecyclerView的状态器*/
private RecyclerView.State mState;
/**滚动动画*/
private ValueAnimator mAnimation;
/**正显示在中间的Item*/
private int mSelectPosition = 0;
/**前一个正显示在中间的Item*/
private int mLastSelectPosition = 0;
/**滑动的方向:左*/
private static final int SCROLL_LEFT = 1;
/**滑动的方向:右*/
private static final int SCROLL_RIGHT = 2;
/**
* 选中监听
*/
private OnSelected mSelectedListener;
/**是否为平面滚动,Item之间没有叠加,也没有缩放*/
private boolean mIsFlatFlow = false;
/**是否启动Item灰度值渐变*/
private boolean mItemGradualGrey = false;
/**是否启动Item半透渐变*/
private boolean mItemGradualAlpha = false;
public CoverLayoutManger(boolean isFlat, boolean isGreyItem, boolean isAlphaItem, float cstInterval) {
mIsFlatFlow = isFlat;
mItemGradualGrey = isGreyItem;
mItemGradualAlpha = isAlphaItem;
if (cstInterval >= 0) {
mIntervalRatio = cstInterval;
} else {
if (mIsFlatFlow) {
mIntervalRatio = 1.1f;
}
}
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
//如果没有item,直接返回
//跳过preLayout,preLayout主要用于支持动画
if (getItemCount() <= 0 || state.isPreLayout()) {
mOffsetAll = 0;
return;
}
mAllItemFrames.clear();
mHasAttachedItems.clear();
//得到子view的宽和高,这边的item的宽高都是一样的,所以只需要进行一次测量
View scrap = recycler.getViewForPosition(0);
addView(scrap);
measureChildWithMargins(scrap, 0, 0);
//计算测量布局的宽高
mDecoratedChildWidth = getDecoratedMeasuredWidth(scrap);
mDecoratedChildHeight = getDecoratedMeasuredHeight(scrap);
mStartX = Math.round((getHorizontalSpace() - mDecoratedChildWidth) * 1.0f / 2);
mStartY = Math.round((getVerticalSpace() - mDecoratedChildHeight) *1.0f / 2);
float offset = mStartX;
/**只存{@link MAX_RECT_COUNT}个item具体位置*/
/**
* 最大存储item信息存储数量,
* 超过设置数量,则动态计算来获取
*/
int MAX_RECT_COUNT = 100;
for (int i = 0; i < getItemCount() && i < MAX_RECT_COUNT; i++) {
Rect frame = mAllItemFrames.get(i);
if (frame == null) {
frame = new Rect();
}
frame.set(Math.round(offset), mStartY, Math.round(offset + mDecoratedChildWidth), mStartY + mDecoratedChildHeight);
mAllItemFrames.put(i, frame);
mHasAttachedItems.put(i, false);
offset = offset + getIntervalDistance();
//原始位置累加,否则越后面误差越大
}
detachAndScrapAttachedViews(recycler);
//在布局之前,将所有的子View先Detach掉,放入到Scrap缓存中
//在为初始化前调用smoothScrollToPosition 或者 scrollToPosition,只会记录位置
if ((mRecycle == null || mState == null) && mSelectPosition != 0) {
//所以初始化时需要滚动到对应位置
mOffsetAll = calculateOffsetForPosition(mSelectPosition);
onSelectedCallBack();
}
layoutItems(recycler, state, SCROLL_RIGHT);
mRecycle = recycler;
mState = state;
}
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (mAnimation != null && mAnimation.isRunning()) {
mAnimation.cancel();
}
int travel = dx;
if (dx + mOffsetAll < 0) {
travel = -mOffsetAll;
} else if (dx + mOffsetAll > getMaxOffset()){
travel = (int) (getMaxOffset() - mOffsetAll);
}
mOffsetAll += travel;
//累计偏移量
layoutItems(recycler, state, dx > 0 ? SCROLL_RIGHT : SCROLL_LEFT);
return travel;
}
/**
* 布局Item
* <p>注意:1,先清除已经超出屏幕的item
* <p> 2,再绘制可以显示在屏幕里面的item
*/
private void layoutItems(RecyclerView.Recycler recycler, RecyclerView.State state, int scrollDirection) {
if (state.isPreLayout()) {
return;
}
Rect displayFrame = new Rect(mOffsetAll, 0, mOffsetAll + getHorizontalSpace(), getVerticalSpace());
int position = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child != null) {
position = getPosition(child);
}
Rect rect = getFrame(position);
if (!Rect.intersects(displayFrame, rect)) {
//Item没有在显示区域,就说明需要回收
assert child != null;
removeAndRecycleView(child, recycler);
//回收滑出屏幕的View
mHasAttachedItems.delete(position);
} else {
//Item还在显示区域内,更新滑动后Item的位置
layoutItem(child, rect);
//更新Item位置
mHasAttachedItems.put(position, true);
}
}
if (position == 0) {
position = mSelectPosition;
}
int min = position - 50 >= 0? position - 50 : 0;
int max = position + 50 < getItemCount() ? position + 50 : getItemCount();
for (int i = min; i < max; i++) {
Rect rect = getFrame(i);
if (Rect.intersects(displayFrame, rect) &&
!mHasAttachedItems.get(i)) {
//重新加载可见范围内的Item
View scrap = recycler.getViewForPosition(i);
measureChildWithMargins(scrap, 0, 0);
if (scrollDirection == SCROLL_LEFT || mIsFlatFlow) {
//向左滚动,新增的Item需要添加在最前面
addView(scrap, 0);
} else {
//向右滚动,新增的item要添加在最后面
addView(scrap);
}
layoutItem(scrap, rect);
//将这个Item布局出来
mHasAttachedItems.put(i, true);
}
}
}
/**
* 布局Item位置
* @param child 要布局的Item
* @param frame 位置信息
*/
private void layoutItem(View child, Rect frame) {
layoutDecorated(child, frame.left - mOffsetAll, frame.top, frame.right - mOffsetAll, frame.bottom);
if (!mIsFlatFlow) {
//不是平面普通滚动的情况下才进行缩放
child.setScaleX(computeScale(frame.left - mOffsetAll));
//缩放
child.setScaleY(computeScale(frame.left - mOffsetAll));
//缩放
}
if (mItemGradualAlpha) {
child.setAlpha(computeAlpha(frame.left - mOffsetAll));
}
if (mItemGradualGrey) {
greyItem(child, frame);
}
}
/**
* 动态获取Item的位置信息
* @param index item位置
* @return item的Rect信息
*/
private Rect getFrame(int index) {
Rect frame = mAllItemFrames.get(index);
if (frame == null) {
frame = new Rect();
float offset = mStartX + getIntervalDistance() * index;
//原始位置累加(即累计间隔距离)
frame.set(Math.round(offset), mStartY, Math.round(offset + mDecoratedChildWidth),
mStartY + mDecoratedChildHeight);
}
return frame;
}
/**
* 变化Item的灰度值
* @param child 需要设置灰度值的Item
* @param frame 位置信息
*/
private void greyItem(View child, Rect frame) {
float value = computeGreyScale(frame.left - mOffsetAll);
ColorMatrix cm = new ColorMatrix(new float[]{
value, 0, 0, 0, 120*(1-value),
0, value, 0, 0, 120*(1-value),
0, 0, value, 0, 120*(1-value),
0, 0, 0, 1, 250*(1-value),
});
// cm.setSaturation(0.9f);
// Create a paint object with color matrix
Paint greyPaint = new Paint();
greyPaint.setColorFilter(new ColorMatrixColorFilter(cm));
// Create a hardware layer with the grey paint
child.setLayerType(View.LAYER_TYPE_HARDWARE, greyPaint);
if (value >= 1) {
// Remove the hardware layer
child.setLayerType(View.LAYER_TYPE_NONE, null);
}
}
@Override
public void onScrollStateChanged(int state) {
super.onScrollStateChanged(state);
switch (state){
case RecyclerView.SCROLL_STATE_IDLE:
//滚动停止时
// fixOffsetWhenFinishScroll();
break;
case RecyclerView.SCROLL_STATE_DRAGGING:
//拖拽滚动时
break;
case RecyclerView.SCROLL_STATE_SETTLING:
//动画滚动时
// fixOffsetWhenFinishScroll();
break;
default:
break;
}
}
@Override
public void scrollToPosition(int position) {
if (position < 0 || position > getItemCount() - 1) {
return;
}
mOffsetAll = calculateOffsetForPosition(position);
if (mRecycle == null || mState == null) {
//如果RecyclerView还没初始化完,先记录下要滚动的位置
mSelectPosition = position;
} else {
layoutItems(mRecycle, mState, position > mSelectPosition ? SCROLL_RIGHT : SCROLL_LEFT);
onSelectedCallBack();
}
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
int finalOffset = calculateOffsetForPosition(position);
if (mRecycle == null || mState == null) {
//如果RecyclerView还没初始化完,先记录下要滚动的位置
mSelectPosition = position;
} else {
startScroll(mOffsetAll, finalOffset);
}
}
@Override
public boolean canScrollHorizontally() {
return true;
}
@Override
public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {
removeAllViews();
mRecycle = null;
mState = null;
mOffsetAll = 0;
mSelectPosition = 0;
mLastSelectPosition = 0;
mHasAttachedItems.clear();
mAllItemFrames.clear();
}
/**
* 获取整个布局的水平空间大小
*/
private int getHorizontalSpace() {
return getWidth() - getPaddingRight() - getPaddingLeft();
}
/**
* 获取整个布局的垂直空间大小
*/
private int getVerticalSpace() {
return getHeight() - getPaddingBottom() - getPaddingTop();
}
/**
* 获取最大偏移量
*/
private float getMaxOffset() {
return (getItemCount() - 1) * getIntervalDistance();
}
/**
* 计算Item缩放系数
* @param x Item的偏移量
* @return 缩放系数
*/
private float computeScale(int x) {
float scale = 1 - Math.abs(x - mStartX) * 1.0f / Math.abs(
mStartX + mDecoratedChildWidth / mIntervalRatio);
if (scale < 0) {
scale = 0;
}
if (scale > 1) {
scale = 1;
}
return scale;
}
/**
* 计算Item的灰度值
* @param x Item的偏移量
* @return 灰度系数
*/
private float computeGreyScale(int x) {
float itemMidPos = x + mDecoratedChildWidth / 2.0f;
//item中点x坐标
float itemDx2Mid = Math.abs(itemMidPos - getHorizontalSpace() / 2.0f);
//item中点距离控件中点距离
float value = 1 - itemDx2Mid * 1.0f / (getHorizontalSpace() /2.0f);
if (value < 0.1) {
value = 0.1f;
}
if (value > 1) {
value = 1;
}
value = (float) Math.pow(value,.8);
return value;
}
/**
* 计算Item半透值
* @param x Item的偏移量
* @return 缩放系数
*/
private float computeAlpha(int x) {
float alpha = 1 - Math.abs(x - mStartX) * 1.0f / Math.abs(mStartX + mDecoratedChildWidth / mIntervalRatio);
if (alpha < 0.3f) {
alpha = 0.3f;
}
if (alpha > 1) {
alpha = 1.0f;
}
return alpha;
}
/**
* 计算Item所在的位置偏移
* @param position 要计算Item位置
*/
private int calculateOffsetForPosition(int position) {
return Math.round(getIntervalDistance() * position);
}
/**
* 修正停止滚动后,Item滚动到中间位置
*/
public void fixOffsetWhenFinishScroll() {
int scrollN = (int) (mOffsetAll * 1.0f / getIntervalDistance());
float moreDx = (mOffsetAll % getIntervalDistance());
if (moreDx > (getIntervalDistance() * 0.5)) {
scrollN ++;
}
int finalOffset = (int) (scrollN * getIntervalDistance());
startScroll(mOffsetAll, finalOffset);
mSelectPosition = Math.round (finalOffset * 1.0f / getIntervalDistance());
}
/**
* 滚动到指定X轴位置
* @param from X轴方向起始点的偏移量
* @param to X轴方向终点的偏移量
*/
private void startScroll(int from, int to) {
if (mAnimation != null && mAnimation.isRunning()) {
mAnimation.cancel();
}
final int direction = from < to ? SCROLL_RIGHT : SCROLL_LEFT;
mAnimation = ValueAnimator.ofFloat(from, to);
mAnimation.setDuration(200);
mAnimation.setInterpolator(new DecelerateInterpolator());
mAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mOffsetAll = Math.round((float) animation.getAnimatedValue());
layoutItems(mRecycle, mState, direction);
}
});
mAnimation.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
onSelectedCallBack();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
mAnimation.start();
}
/**
* 获取Item间隔
*/
private float getIntervalDistance() {
return mDecoratedChildWidth * mIntervalRatio;
}
/**
* 计算当前选中位置,并回调
*/
private void onSelectedCallBack() {
mSelectPosition = Math.round (mOffsetAll / getIntervalDistance());
if (mSelectedListener != null && mSelectPosition != mLastSelectPosition) {
mSelectedListener.onItemSelected(mSelectPosition);
}
mLastSelectPosition = mSelectPosition;
}
/**
* 获取第一个可见的Item位置
* <p>Note:该Item为绘制在可见区域的第一个Item,有可能被第二个Item遮挡
*/
public int getFirstVisiblePosition() {
Rect displayFrame = new Rect(mOffsetAll, 0, mOffsetAll + getHorizontalSpace(), getVerticalSpace());
int cur = getCenterPosition();
for (int i = cur - 1; i >= 0; i--) {
Rect rect = getFrame(i);
if (!Rect.intersects(displayFrame, rect)) {
return i + 1;
}
}
return 0;
}
/**
* 获取最后一个可见的Item位置
* <p>Note:该Item为绘制在可见区域的最后一个Item,有可能被倒数第二个Item遮挡
*/
public int getLastVisiblePosition() {
Rect displayFrame = new Rect(mOffsetAll, 0, mOffsetAll + getHorizontalSpace(), getVerticalSpace());
int cur = getCenterPosition();
for (int i = cur + 1; i < getItemCount(); i++) {
Rect rect = getFrame(i);
if (!Rect.intersects(displayFrame, rect)) {
return i - 1;
}
}
return cur;
}
/**
* 获取可见范围内最大的显示Item个数
*/
public int getMaxVisibleCount() {
int oneSide = (int) ((getHorizontalSpace() - mStartX) / (getIntervalDistance()));
return oneSide * 2 + 1;
}
/**
* 获取中间位置
* <p>Note:该方法主要用于{@link CoverRecyclerView#getChildDrawingOrder(int, int)}判断中间位置
* <p>如果需要获取被选中的Item位置,调用{@link #getSelectedPos()}
*/
public int getCenterPosition() {
int pos = (int) (mOffsetAll / getIntervalDistance());
int more = (int) (mOffsetAll % getIntervalDistance());
if (more > getIntervalDistance() * 0.5f) {
pos++;
}
return pos;
}
/**
* 设置选中监听
* @param l 监听接口
*/
public void setOnSelectedListener(OnSelected l) {
mSelectedListener = l;
}
/**
* 获取被选中Item位置
*/
public int getSelectedPos() {
return mSelectPosition;
}
/**
* 选中监听接口
*/
public interface OnSelected {
/**
* 监听选中回调
* @param position 显示在中间的Item的位置
*/
void onItemSelected(int position);
}
public static class Builder {
boolean isFlat = false;
boolean isGreyItem = false;
boolean isAlphaItem = false;
float cstIntervalRatio = -1f;
public Builder setFlat(boolean flat) {
isFlat = flat;
return this;
}
public Builder setGreyItem(boolean greyItem) {
isGreyItem = greyItem;
return this;
}
public Builder setAlphaItem(boolean alphaItem) {
isAlphaItem = alphaItem;
return this;
}
public Builder setIntervalRatio(float ratio) {
cstIntervalRatio = ratio;
return this;
}
public CoverLayoutManger build() {
return new CoverLayoutManger(isFlat, isGreyItem, isAlphaItem, cstIntervalRatio);
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
PhotoCoverLib/src/main/java/com/yc/cover/CoverRecyclerView.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.yc.cover;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/9/11
* desc : 自定义RecyclerView
* revise:
* </pre>
*/
public class CoverRecyclerView extends RecyclerView {
/**
* 按下的X轴坐标
*/
private float mDownX;
/**
* 布局器构建者
*/
private CoverLayoutManger.Builder mManagerBuilder;
public CoverRecyclerView(Context context) {
super(context);
init();
}
public CoverRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CoverRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
createManageBuilder();
this.setLayoutManager(mManagerBuilder.build());
//开启重新排序
this.setChildrenDrawingOrderEnabled(true);
this.setOverScrollMode(OVER_SCROLL_NEVER);
this.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
switch (newState) {
case RecyclerView.SCROLL_STATE_IDLE:
//滚动停止时
break;
case RecyclerView.SCROLL_STATE_DRAGGING:
break;
case RecyclerView.SCROLL_STATE_SETTLING:
break;
default:
break;
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dx != 0) {//去掉奇怪的内存疯涨问题
if (recyclerView.getLayoutManager() instanceof CoverLayoutManger) {
CoverLayoutManger manger = (CoverLayoutManger) recyclerView.getLayoutManager();
manger.fixOffsetWhenFinishScroll();
}
}
}
});
}
/**
* 创建布局构建器
*/
private void createManageBuilder() {
if (mManagerBuilder == null) {
mManagerBuilder = new CoverLayoutManger.Builder();
}
}
/**
* 设置是否为普通平面滚动
* @param isFlat true:平面滚动;false:叠加缩放滚动
*/
public void setFlatFlow(boolean isFlat) {
createManageBuilder();
mManagerBuilder.setFlat(isFlat);
setLayoutManager(mManagerBuilder.build());
}
/**
* 设置Item灰度渐变
* @param greyItem true:Item灰度渐变;false:Item灰度不变
*/
public void setGreyItem(boolean greyItem) {
createManageBuilder();
mManagerBuilder.setGreyItem(greyItem);
setLayoutManager(mManagerBuilder.build());
}
/**
* 设置Item灰度渐变
* @param alphaItem true:Item半透渐变;false:Item透明度不变
*/
public void setAlphaItem(boolean alphaItem) {
createManageBuilder();
mManagerBuilder.setAlphaItem(alphaItem);
setLayoutManager(mManagerBuilder.build());
}
/**
* 设置Item的间隔比例
* @param intervalRatio Item间隔比例。
* 即:item的宽 x intervalRatio
*/
public void setIntervalRatio(float intervalRatio) {
createManageBuilder();
mManagerBuilder.setIntervalRatio(intervalRatio);
setLayoutManager(mManagerBuilder.build());
}
@Override
public void setLayoutManager(LayoutManager layout) {
if (!(layout instanceof CoverLayoutManger)) {
throw new IllegalArgumentException("The layout manager must be CoverLayoutManger");
}
super.setLayoutManager(layout);
}
@Override
protected int getChildDrawingOrder(int childCount, int i) {
int center = getCoverFlowLayout().getCenterPosition() - getCoverFlowLayout().getFirstVisiblePosition();
//计算正在显示的所有Item的中间位置
if (center < 0) {
center = 0;
} else if (center > childCount) {
center = childCount;
}
int order;
if (i == center) {
order = childCount - 1;
} else if (i > center) {
order = center + childCount - 1 - i;
} else {
order = i;
}
return order;
}
/**
* 获取LayoutManger,并强制转换为CoverFlowLayoutManger
*/
public CoverLayoutManger getCoverFlowLayout() {
return ((CoverLayoutManger)getLayoutManager());
}
/**
* 获取被选中的Item位置
*/
public int getSelectedPos() {
CoverLayoutManger coverFlowLayout = getCoverFlowLayout();
if (coverFlowLayout!=null){
int selectedPos = getCoverFlowLayout().getSelectedPos();
return selectedPos;
}
return 0;
}
/**
* 设置选中监听
* @param l 监听接口
*/
public void setOnItemSelectedListener(CoverLayoutManger.OnSelected l) {
if (getCoverFlowLayout()!=null){
getCoverFlowLayout().setOnSelectedListener(l);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getX();
//设置父类不拦截滑动事件
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
int centerPosition = getCoverFlowLayout().getCenterPosition();
int itemCount = getCoverFlowLayout().getItemCount();
if ((ev.getX() > mDownX && centerPosition== 0) ||
(ev.getX() < mDownX && centerPosition == itemCount -1)) {
//如果是滑动到了最前和最后,开放父类滑动事件拦截
getParent().requestDisallowInterceptTouchEvent(false);
} else {
//滑动到中间,设置父类不拦截滑动事件
getParent().requestDisallowInterceptTouchEvent(true);
}
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/build.gradle | Gradle | apply plugin: 'com.android.library'
apply from: rootProject.projectDir.absolutePath + "/AppGradle/app.gradle"
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion project.ext.androidCompileSdkVersion
//buildToolsVersion project.ext.androidBuildToolsVersion
defaultConfig {
minSdkVersion project.ext.androidMinSdkVersion
targetSdkVersion project.ext.androidTargetSdkVersion
versionCode 32
versionName "3.0.2"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project.ext.AppDependencies['recyclerview']
implementation project.ext.AppDependencies['swiperefreshlayout']
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/adapter/DefaultEventDelegate.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.yczbj.ycrefreshviewlib.utils.RefreshLogUtils;
import org.yczbj.ycrefreshviewlib.inter.InterEventDelegate;
import org.yczbj.ycrefreshviewlib.inter.InterItemView;
import org.yczbj.ycrefreshviewlib.inter.OnErrorListener;
import org.yczbj.ycrefreshviewlib.inter.OnMoreListener;
import org.yczbj.ycrefreshviewlib.inter.OnNoMoreListener;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/1/29
* desc : 默认设置数据和加载监听的类
* revise:
* </pre>
*/
public class DefaultEventDelegate implements InterEventDelegate {
private RecyclerArrayAdapter adapter;
private EventFooter footer ;
private OnMoreListener onMoreListener;
private OnNoMoreListener onNoMoreListener;
private OnErrorListener onErrorListener;
private boolean hasData = false;
private boolean isLoadingMore = false;
private boolean hasMore = false;
private boolean hasNoMore = false;
private boolean hasError = false;
private int status = STATUS_INITIAL;
private static final int STATUS_INITIAL = 291;
private static final int STATUS_MORE = 260;
private static final int STATUS_NO_MORE = 408;
private static final int STATUS_ERROR = 732;
DefaultEventDelegate(RecyclerArrayAdapter adapter) {
this.adapter = adapter;
footer = new EventFooter();
adapter.addFooter(footer);
}
private void onMoreViewShowed() {
RefreshLogUtils.d("onMoreViewShowed");
if (!isLoadingMore&& onMoreListener !=null){
isLoadingMore = true;
onMoreListener.onMoreShow();
}
}
private void onMoreViewClicked() {
if (onMoreListener !=null){
onMoreListener.onMoreClick();
}
}
private void onErrorViewShowed() {
if (onErrorListener!=null){
onErrorListener.onErrorShow();
}
}
private void onErrorViewClicked() {
if (onErrorListener!=null){
onErrorListener.onErrorClick();
}
}
private void onNoMoreViewShowed() {
if (onNoMoreListener!=null){
onNoMoreListener.onNoMoreShow();
}
}
private void onNoMoreViewClicked() {
if (onNoMoreListener!=null){
onNoMoreListener.onNoMoreClick();
}
}
//-------------------5个状态触发事件-------------------
@Override
public void addData(int length) {
RefreshLogUtils.d("addData" + length);
if (hasMore){
if (length == 0){
//当添加0个时,认为已结束加载到底
if (status==STATUS_INITIAL || status == STATUS_MORE){
footer.showNoMore();
status = STATUS_NO_MORE;
}
}else {
//当Error或初始时。添加数据,如果有More则还原。
footer.showMore();
status = STATUS_MORE;
hasData = true;
}
}else{
if (hasNoMore){
footer.showNoMore();
status = STATUS_NO_MORE;
}
}
isLoadingMore = false;
}
@Override
public void clear() {
RefreshLogUtils.d("clear");
hasData = false;
status = STATUS_INITIAL;
footer.hide();
isLoadingMore = false;
}
@Override
public void stopLoadMore() {
RefreshLogUtils.d("stopLoadMore");
footer.showNoMore();
status = STATUS_NO_MORE;
isLoadingMore = false;
}
@Override
public void pauseLoadMore() {
RefreshLogUtils.d("pauseLoadMore");
footer.showError();
status = STATUS_ERROR;
isLoadingMore = false;
}
@Override
public void resumeLoadMore() {
isLoadingMore = false;
footer.showMore();
status = STATUS_MORE;
onMoreViewShowed();
}
//-------------------3种View设置-------------------
@Override
public void setMore(View view, OnMoreListener listener) {
this.footer.setMoreView(view);
this.onMoreListener = listener;
hasMore = true;
// 为了处理setMore之前就添加了数据的情况
if (adapter.getCount()>0){
addData(adapter.getCount());
}
RefreshLogUtils.d("setMore");
}
@Override
public void setNoMore(View view, OnNoMoreListener listener) {
this.footer.setNoMoreView(view);
this.onNoMoreListener = listener;
hasNoMore = true;
RefreshLogUtils.d("setNoMore");
}
@Override
public void setErrorMore(View view, OnErrorListener listener) {
this.footer.setErrorView(view);
this.onErrorListener = listener;
hasError = true;
RefreshLogUtils.d("setErrorMore");
}
@Override
public void setMore(int res, OnMoreListener listener) {
this.footer.setMoreViewRes(res);
this.onMoreListener = listener;
hasMore = true;
// 为了处理setMore之前就添加了数据的情况
if (adapter.getCount()>0){
addData(adapter.getCount());
}
RefreshLogUtils.d("setMore");
}
@Override
public void setNoMore(int res, OnNoMoreListener listener) {
this.footer.setNoMoreViewRes(res);
this.onNoMoreListener = listener;
hasNoMore = true;
RefreshLogUtils.d("setNoMore");
}
@Override
public void setErrorMore(int res, OnErrorListener listener) {
this.footer.setErrorViewRes(res);
this.onErrorListener = listener;
hasError = true;
RefreshLogUtils.d("setErrorMore");
}
/**
* 这个是设置上拉加载footer
*/
public class EventFooter implements InterItemView {
private View moreView = null;
private View noMoreView = null;
private View errorView = null;
private int moreViewRes = 0;
private int noMoreViewRes = 0;
private int errorViewRes = 0;
private int flag = HIDE;
static final int HIDE = 520;
private static final int SHOW_MORE = 521;
private static final int SHOW_ERROR = 522;
static final int SHOW_NO_MORE = 523;
/**
* 是否展示error的view
*/
private boolean skipError = false;
/**
* 是否展示noMore的view
*/
private boolean skipNoMore = false;
private EventFooter(){}
@Override
public View onCreateView(ViewGroup parent) {
RefreshLogUtils.d("onCreateView");
return refreshStatus(parent);
}
@Override
public void onBindView(View headerView) {
RefreshLogUtils.d("onBindView");
headerView.post(new Runnable() {
@Override
public void run() {
running(flag);
}
});
}
private void running(int flag) {
switch (flag){
case SHOW_MORE:
onMoreViewShowed();
break;
case SHOW_NO_MORE:
if (!skipNoMore) {
onNoMoreViewShowed();
}
skipNoMore = false;
break;
case SHOW_ERROR:
if (!skipError) {
onErrorViewShowed();
}
skipError = false;
break;
default:
break;
}
}
View refreshStatus(ViewGroup parent){
View view = null;
switch (flag){
case SHOW_MORE:
if (moreView!=null) {
view = moreView;
} else if (moreViewRes!=0) {
view = LayoutInflater.from(parent.getContext())
.inflate(moreViewRes, parent, false);
}
if (view!=null) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onMoreViewClicked();
}
});
}
break;
case SHOW_ERROR:
if (errorView!=null) {
view = errorView;
} else if (errorViewRes!=0) {
view = LayoutInflater.from(parent.getContext())
.inflate(errorViewRes, parent, false);
}
if (view!=null) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onErrorViewClicked();
}
});
}
break;
case SHOW_NO_MORE:
if (noMoreView!=null) {
view = noMoreView;
} else if (noMoreViewRes!=0) {
view = LayoutInflater.from(parent.getContext())
.inflate(noMoreViewRes, parent, false);
}
if (view!=null) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onNoMoreViewClicked();
}
});
}
break;
default:
break;
}
if (view == null) {
view = new FrameLayout(parent.getContext());
}
return view;
}
void showError(){
RefreshLogUtils.d("footer showError");
skipError = true;
flag = SHOW_ERROR;
//noinspection deprecation
if (adapter.getItemCount()>0){
adapter.notifyItemChanged(adapter.getItemCount()-1);
}
}
void showMore(){
RefreshLogUtils.d("footer showMore");
flag = SHOW_MORE;
//noinspection deprecation
if (adapter.getItemCount()>0){
adapter.notifyItemChanged(adapter.getItemCount()-1);
}
}
void showNoMore(){
RefreshLogUtils.d("footer showNoMore");
skipNoMore = true;
flag = SHOW_NO_MORE;
//noinspection deprecation
if (adapter.getItemCount()>0){
adapter.notifyItemChanged(adapter.getItemCount()-1);
}
}
void hide(){
RefreshLogUtils.d("footer hide");
flag = HIDE;
//noinspection deprecation
if (adapter.getItemCount()>0){
adapter.notifyItemChanged(adapter.getItemCount()-1);
}
}
void setMoreView(View moreView) {
this.moreView = moreView;
this.moreViewRes = 0;
}
void setNoMoreView(View noMoreView) {
this.noMoreView = noMoreView;
this.noMoreViewRes = 0;
}
void setErrorView(View errorView) {
this.errorView = errorView;
this.errorViewRes = 0;
}
void setMoreViewRes(int moreViewRes) {
this.moreView = null;
this.moreViewRes = moreViewRes;
}
void setNoMoreViewRes(int noMoreViewRes) {
this.noMoreView = null;
this.noMoreViewRes = noMoreViewRes;
}
void setErrorViewRes(int errorViewRes) {
this.errorView = null;
this.errorViewRes = errorViewRes;
}
@Override
public int hashCode() {
return flag;
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/adapter/RecyclerArrayAdapter.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.adapter;
import android.content.Context;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import org.yczbj.ycrefreshviewlib.inter.InterEventDelegate;
import org.yczbj.ycrefreshviewlib.inter.InterItemView;
import org.yczbj.ycrefreshviewlib.inter.OnErrorListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemLongClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnLoadMoreListener;
import org.yczbj.ycrefreshviewlib.inter.OnMoreListener;
import org.yczbj.ycrefreshviewlib.inter.OnNoMoreListener;
import org.yczbj.ycrefreshviewlib.observer.FixDataObserver;
import org.yczbj.ycrefreshviewlib.span.GridSpanSizeLookup;
import org.yczbj.ycrefreshviewlib.utils.RecyclerUtils;
import org.yczbj.ycrefreshviewlib.utils.RefreshLogUtils;
import org.yczbj.ycrefreshviewlib.holder.BaseViewHolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2017/5/2
* desc : 自定义adapter
* revise: 注意这里使用泛型数据类型
* </pre>
*/
public abstract class RecyclerArrayAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
private List<T> mObjects;
private InterEventDelegate mEventDelegate;
private ArrayList<InterItemView> headers = new ArrayList<>();
private ArrayList<InterItemView> footers = new ArrayList<>();
private OnItemClickListener mItemClickListener;
private OnItemLongClickListener mItemLongClickListener;
private OnItemChildClickListener mOnItemChildClickListener;
private final Object mLock = new Object();
private boolean mNotifyOnChange = true;
private Context mContext;
private boolean mSetHeaderAndFooterSpan = false;
public RecyclerArrayAdapter(Context context) {
RecyclerUtils.checkContent(context);
init(context, new ArrayList<T>());
}
public RecyclerArrayAdapter(Context context, T[] objects) {
RecyclerUtils.checkContent(context);
init(context, Arrays.asList(objects));
}
public RecyclerArrayAdapter(Context context, List<T> objects) {
RecyclerUtils.checkContent(context);
init(context, objects);
}
private void init(Context context , List<T> objects) {
mContext = context;
mObjects = new ArrayList<>(objects);
}
/**
* 页面进入时,显示RecyclerView,调用onAttachedToRecyclerView,做一些注册工作;
* 页面退出时,销毁RecyclerView,调用onDetachedFromRecyclerView,做一些解注册和其他资源回收的操作。
* @param recyclerView recyclerView
*/
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
//增加对RecyclerArrayAdapter奇葩操作的修复措施
registerAdapterDataObserver(new FixDataObserver(recyclerView));
if (mSetHeaderAndFooterSpan){
//下面是处理grid试图上拉加载的问题
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof GridLayoutManager) {
final GridLayoutManager gridManager = ((GridLayoutManager) manager);
gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
// 如果当前是footer的位置,那么该item占据2个单元格,正常情况下占据1个单元格
int itemViewType = getItemViewType(position);
//注意,具体可以看DefaultEventDelegate类中的EventFooter类代码
//如果是头部header或者底部footer,则直接
if (itemViewType>=DefaultEventDelegate.EventFooter.HIDE &&
itemViewType<=DefaultEventDelegate.EventFooter.SHOW_NO_MORE){
RefreshLogUtils.d("onAttachedToRecyclerView----这个是header和footer");
return gridManager.getSpanCount();
}else {
RefreshLogUtils.d("onAttachedToRecyclerView----");
return 1;
}
}
});
}
}
}
/**
* 页面进入时,显示RecyclerView,调用onAttachedToRecyclerView,做一些注册工作;
* 页面退出时,销毁RecyclerView,调用onDetachedFromRecyclerView,做一些解注册和其他资源回收的操作。
* @param recyclerView recyclerView
*/
@Override
public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}
/**
* https://www.jianshu.com/p/4f66c2c71d8c
* 创建viewHolder,主要作用是创建Item视图,并返回相应的ViewHolder
* @param parent parent
* @param viewType type类型
* @return 返回viewHolder
*/
@NonNull
@Override
public final BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = createViewByType(parent, viewType);
if (view!=null){
return new BaseViewHolder(view);
}
final BaseViewHolder viewHolder = OnCreateViewHolder(parent, viewType);
//注意:点击事件放到onCreateViewHolder更好一些,不要放到onBindViewHolder或者ViewHolder中
setOnClickListener(viewHolder);
return viewHolder;
}
/**
* 获取类型,主要作用是用来获取当前项Item(position参数)是哪种类型的布局
* @param position 索引
* @return int
*/
@Deprecated
@Override
public final int getItemViewType(int position) {
if (headers.size()!=0){
if (position<headers.size()) {
return headers.get(position).hashCode();
}
}
if (footers.size()!=0){
/*
eg:
0:header1
1:header2 2
2:object1
3:object2
4:object3
5:object4
6:footer1 6(position) - 2 - 4 = 0
7:footer2
*/
int i = position - headers.size() - mObjects.size();
if (i >= 0){
return footers.get(i).hashCode();
}
}
return getViewType(position-headers.size());
}
public int getViewType(int position){
return 0;
}
/**
* 重写该方法的作用主要是返回该Adapter所持有的Item数量
* 这个函数包含了头部和尾部view的个数,不是真正的item个数。
* 包含item+header头布局数量+footer底布局数量
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
@Override
public final int getItemCount() {
return mObjects.size() + headers.size() + footers.size();
}
/**
* 绑定viewHolder,主要作用是绑定数据到正确的Item视图上。当视图从不可见到可见的时候,会调用这个方法。
* @param holder holder
* @param position 索引
*/
@Override
public final void onBindViewHolder(BaseViewHolder holder, int position) {
holder.itemView.setId(position);
if (headers.size()!=0 && position<headers.size()){
headers.get(position).onBindView(holder.itemView);
return ;
}
int i = position - headers.size() - mObjects.size();
if (footers.size()!=0 && i>=0){
footers.get(i).onBindView(holder.itemView);
return ;
}
OnBindViewHolder(holder,position-headers.size());
}
@Override
public long getItemId(int position) {
return position;
}
/**
* 通过重写 RecyclerView.onViewRecycled(holder) 来回收资源。
* @param holder holder
*/
@Override
public void onViewRecycled(@NonNull BaseViewHolder holder) {
super.onViewRecycled(holder);
}
/*---------------------------------子类需要重写的方法---------------------------------------*/
/**
* 抽象方法,子类继承
*/
public abstract BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType);
@SuppressWarnings("unchecked")
private void OnBindViewHolder(BaseViewHolder holder, final int position){
holder.setData(getItem(position));
}
/**
* 设置多列数据上拉加载更多时
* @param maxCount count
* @return span
*/
public GridSpanSizeLookup obtainGridSpanSizeLookUp(int maxCount){
return new GridSpanSizeLookup(maxCount,headers,footers, (List<Object>) mObjects);
}
/**
* 设置多列的gridView时候,需要设置header和footer,以及上拉加载item占一行操作
* 这个方法需要在setAdapter之前设置
* @param isHeaderAndFooterSpan isHeaderAndFooterSpan
*/
public void setHeaderAndFooterSpan(boolean isHeaderAndFooterSpan){
this.mSetHeaderAndFooterSpan = isHeaderAndFooterSpan;
}
/**
* 停止加载更多
*/
public void stopMore(){
if (mEventDelegate == null) {
throw new NullPointerException("You should invoking setLoadMore() first");
}
mEventDelegate.stopLoadMore();
}
/**
* 暂停加载更多
*/
public void pauseMore(){
if (mEventDelegate == null) {
throw new NullPointerException("You should invoking setLoadMore() first");
}
mEventDelegate.pauseLoadMore();
}
/**
* 恢复加载更多
*/
public void resumeMore(){
if (mEventDelegate == null) {
throw new NullPointerException("You should invoking setLoadMore() first");
}
mEventDelegate.resumeLoadMore();
}
/**
* 添加headerView
* @param view view
*/
public void addHeader(InterItemView view){
if (view==null) {
throw new NullPointerException("InterItemView can't be null");
}
headers.add(view);
notifyItemInserted(headers.size()-1);
}
/**
* 添加footerView
* @param view view
*/
public void addFooter(InterItemView view){
if (view==null) {
throw new NullPointerException("InterItemView can't be null");
}
footers.add(view);
notifyItemInserted(headers.size()+getCount()+footers.size()-1);
}
/**
* 清除所有header
*/
public void removeAllHeader(){
int count = headers.size();
if (count==0){
return;
}
headers.clear();
notifyItemRangeRemoved(0,count);
}
/**
* 清除所有footer
*/
public void removeAllFooter(){
int count = footers.size();
if (count==0){
return;
}
footers.clear();
notifyItemRangeRemoved(headers.size()+getCount(),count);
}
/**
* 获取某个索引处的headerView
* @param index 索引
* @return InterItemView
*/
public InterItemView getHeader(int index){
if (headers!=null && headers.size()>0){
return headers.get(index);
}else {
return null;
}
}
/**
* 获取某个索引处的footerView
* @param index 索引
* @return InterItemView
*/
public InterItemView getFooter(int index){
if (footers!=null && footers.size()>0){
return footers.get(index);
}else {
return null;
}
}
/**
* 获取header的数量
* @return 数量
*/
public int getHeaderCount(){return headers.size();}
/**
* 获取footer的数量
* @return 数量
*/
public int getFooterCount(){return footers.size();}
/**
* 移除某个headerView
* @param view view
*/
public void removeHeader(InterItemView view){
int position = headers.indexOf(view);
headers.remove(view);
notifyItemRemoved(position);
}
/**
* 移除某个footerView
* @param view view
*/
public void removeFooter(InterItemView view){
int position = headers.size()+getCount()+footers.indexOf(view);
footers.remove(view);
notifyItemRemoved(position);
}
private InterEventDelegate getEventDelegate(){
if (mEventDelegate == null) {
mEventDelegate = new DefaultEventDelegate(this);
}
return mEventDelegate;
}
/**
* 设置上拉加载更多的自定义布局和监听
* @param res res布局
* @param listener listener
*/
public void setMore(final int res, final OnLoadMoreListener listener){
getEventDelegate().setMore(res, new OnMoreListener() {
@Override
public void onMoreShow() {
listener.onLoadMore();
}
@Override
public void onMoreClick() {
}
});
}
/**
* 设置上拉加载更多的自定义布局和监听
* @param view view布局
* @param listener listener
*/
public void setMore(final View view,final OnLoadMoreListener listener){
getEventDelegate().setMore(view, new OnMoreListener() {
@Override
public void onMoreShow() {
listener.onLoadMore();
}
@Override
public void onMoreClick() {
}
});
}
/**
* 设置上拉加载更多的自定义布局和
* @param res res布局
* @param listener listener
*/
public void setMore(final int res, final OnMoreListener listener){
getEventDelegate().setMore(res, listener);
}
/**
* 设置上拉加载更多的自定义布局和
* @param view view布局
* @param listener listener
*/
public void setMore(final View view,OnMoreListener listener){
getEventDelegate().setMore(view, listener);
}
/**
* 设置上拉加载没有更多数据布局
* @param res res布局
*/
public void setNoMore(final int res) {
getEventDelegate().setNoMore(res,null);
}
/**
* 设置上拉加载没有更多数据布局
* @param view 没有更多数据布局view
*/
public void setNoMore(final View view) {
getEventDelegate().setNoMore(view,null);
}
/**
* 设置上拉加载没有更多数据监听
* @param view 没有更多数据布局
* @param listener 上拉加载没有更多数据监听
*/
public void setNoMore(final View view , OnNoMoreListener listener) {
getEventDelegate().setNoMore(view,listener);
}
/**
* 设置上拉加载没有更多数据监听
* @param res 没有更多数据布局res
* @param listener 上拉加载没有更多数据监听
*/
public void setNoMore(final @LayoutRes int res , OnNoMoreListener listener) {
getEventDelegate().setNoMore(res,listener);
}
/**
* 设置上拉加载异常的布局
* @param res view
*/
public void setError(final @LayoutRes int res) {
getEventDelegate().setErrorMore(res,null);
}
/**
* 设置上拉加载异常的布局
* @param view view
*/
public void setError(final View view) {
getEventDelegate().setErrorMore(view,null);
}
/**
* 设置上拉加载异常的布局和异常监听
* @param res view
* @param listener 上拉加载更多异常监听
*/
public void setError(final @LayoutRes int res,OnErrorListener listener) {
getEventDelegate().setErrorMore(res,listener);
}
public void setError(final View view,OnErrorListener listener) {
getEventDelegate().setErrorMore(view,listener);
}
/**
* 添加数据
* @param object 数据
*/
public void add(T object) {
if (mEventDelegate!=null) {
mEventDelegate.addData(object == null ? 0 : 1);
}
if (object!=null){
synchronized (mLock) {
mObjects.add(object);
}
}
if (mNotifyOnChange) {
notifyItemInserted(headers.size() + getCount());
}
RefreshLogUtils.d("add notifyItemInserted "+(headers.size()+getCount()));
}
/**
* 添加所有数据
* @param collection Collection集合数据
*/
public void addAll(Collection<? extends T> collection) {
if (mEventDelegate!=null) {
mEventDelegate.addData(collection == null ? 0 : collection.size());
}
if (collection!=null&&collection.size()!=0){
synchronized (mLock) {
mObjects.addAll(collection);
}
}
int dataCount = collection==null?0:collection.size();
if (mNotifyOnChange) {
notifyItemRangeInserted(headers.size() + getCount() - dataCount, dataCount);
}
RefreshLogUtils.d("addAll notifyItemRangeInserted "+(headers.size()+getCount()-dataCount)+","+(dataCount));
}
/**
* 添加所有数据
* @param items 数据
*/
public void addAll(T[] items) {
if (mEventDelegate!=null) {
mEventDelegate.addData(items == null ? 0 : items.length);
}
if (items!=null&&items.length!=0) {
synchronized (mLock) {
Collections.addAll(mObjects, items);
}
}
int dataCount = items==null?0:items.length;
if (mNotifyOnChange) {
notifyItemRangeInserted(headers.size() + getCount() - dataCount, dataCount);
}
RefreshLogUtils.d("addAll notifyItemRangeInserted "+((headers.size()+getCount()-dataCount)+","+(dataCount)));
}
/**
* 插入,不会触发任何事情
* @param object 数据
* @param index 索引
*/
public void insert(T object, int index) {
synchronized (mLock) {
mObjects.add(index, object);
}
if (mNotifyOnChange) {
notifyItemInserted(headers.size() + index);
}
RefreshLogUtils.d("insert notifyItemRangeInserted "+(headers.size()+index));
}
/**
* 插入数组,不会触发任何事情
* @param object 数据
* @param index 索引
*/
public void insertAll(T[] object, int index) {
synchronized (mLock) {
mObjects.addAll(index, Arrays.asList(object));
}
int dataCount = object.length;
if (mNotifyOnChange) {
notifyItemRangeInserted(headers.size() + index, dataCount);
}
RefreshLogUtils.d("insertAll notifyItemRangeInserted "+((headers.size()+index)+","+(dataCount)));
}
/**
* 插入数组,不会触发任何事情
* @param object 数据
* @param index 索引
*/
public void insertAll(Collection<? extends T> object, int index) {
synchronized (mLock) {
mObjects.addAll(index, object);
}
int dataCount = object.size();
if (mNotifyOnChange) {
notifyItemRangeInserted(headers.size() + index, dataCount);
}
RefreshLogUtils.d("insertAll notifyItemRangeInserted "+((headers.size()+index)+","+(dataCount)));
}
/**
* 更新数据
* @param object 数据
* @param pos 索引
*/
public void update(T object,int pos){
synchronized (mLock) {
mObjects.set(pos,object);
}
if (mNotifyOnChange) {
notifyItemChanged(pos);
}
RefreshLogUtils.d("insertAll notifyItemChanged "+pos);
}
/**
* 删除,不会触发任何事情
* @param object 要移除的数据
*/
public void remove(T object) {
int position = mObjects.indexOf(object);
synchronized (mLock) {
if (mObjects.remove(object)){
if (mNotifyOnChange) {
notifyItemRemoved(headers.size() + position);
}
RefreshLogUtils.d("remove notifyItemRemoved "+(headers.size()+position));
}
}
}
/**
* 将某个索引处的数据置顶
* @param position 要移除数据的索引
*/
public void setTop(int position){
T t;
synchronized (mLock) {
t = mObjects.get(position);
mObjects.remove(position);
}
if (mNotifyOnChange) {
notifyItemInserted(headers.size());
}
mObjects.add(0,t);
if (mNotifyOnChange) {
notifyItemRemoved(headers.size() + 1);
}
RefreshLogUtils.d("remove notifyItemRemoved "+(headers.size()+1));
}
/**
* 删除,不会触发任何事情
* @param position 要移除数据的索引
*/
public void remove(int position) {
synchronized (mLock) {
mObjects.remove(position);
}
if (mNotifyOnChange) {
notifyItemRemoved(headers.size() + position);
}
RefreshLogUtils.d("remove notifyItemRemoved "+(headers.size()+position));
}
/**
* 触发清空所有的数据
*/
public void clear() {
int count = mObjects.size();
if (mEventDelegate!=null) {
mEventDelegate.clear();
}
synchronized (mLock) {
mObjects.clear();
}
if (mNotifyOnChange) {
notifyDataSetChanged();
}
RefreshLogUtils.d("clear notifyItemRangeRemoved "+(headers.size())+","+(count));
}
/**
* 使用指定的比较器对此适配器的内容进行排序
*/
public void sort(Comparator<? super T> comparator) {
synchronized (mLock) {
Collections.sort(mObjects, comparator);
}
if (mNotifyOnChange) {
notifyDataSetChanged();
}
}
/**
* 设置操作数据[增删改查]后,是否刷新adapter
* @param notifyOnChange 默认是刷新的true
*/
public void setNotifyOnChange(boolean notifyOnChange) {
mNotifyOnChange = notifyOnChange;
}
/**
* 获取上下文
* @return
*/
public Context getContext() {
return mContext;
}
/**
* 应该使用这个获取item个数
*/
public int getCount(){
return mObjects.size();
}
private View createViewByType(ViewGroup parent, int viewType){
for (InterItemView headerView : headers){
if (headerView.hashCode() == viewType){
View view = headerView.onCreateView(parent);
StaggeredGridLayoutManager.LayoutParams layoutParams;
if (view.getLayoutParams()!=null) {
layoutParams = new StaggeredGridLayoutManager.LayoutParams(view.getLayoutParams());
} else {
layoutParams = new StaggeredGridLayoutManager.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
layoutParams.setFullSpan(true);
view.setLayoutParams(layoutParams);
return view;
}
}
for (InterItemView footerView : footers){
if (footerView.hashCode() == viewType){
View view = footerView.onCreateView(parent);
StaggeredGridLayoutManager.LayoutParams layoutParams;
if (view.getLayoutParams()!=null) {
layoutParams = new StaggeredGridLayoutManager.LayoutParams(view.getLayoutParams());
} else {
layoutParams = new StaggeredGridLayoutManager.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
layoutParams.setFullSpan(true);
view.setLayoutParams(layoutParams);
return view;
}
}
return null;
}
/**
* 获取所有的数据list集合
* @return list结合
*/
public List<T> getAllData(){
return new ArrayList<>(mObjects);
}
/**
* 获取item
*/
protected T getItem(int position) {
return mObjects.get(position);
}
/**
* 获取item索引位置
* @param item item
* @return 索引位置
*/
public int getPosition(T item) {
//搜索
return mObjects.indexOf(item);
}
/**---------------------------------点击事件---------------------------------------------------*/
/**
* 设置item条目点击事件,注意在onCreateViewHolder中设置要优于onBindViewHolder
* @param viewHolder viewHolder
*/
private void setOnClickListener(final BaseViewHolder viewHolder) {
//itemView 的点击事件
if (mItemClickListener!=null) {
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mItemClickListener.onItemClick(
viewHolder.getAdapterPosition()-headers.size());
}
});
}
if (mItemLongClickListener!=null){
viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return mItemLongClickListener.onItemLongClick(
viewHolder.getAdapterPosition()-headers.size());
}
});
}
}
/**
* 设置条目点击事件
* @param listener 监听器
*/
public void setOnItemClickListener(OnItemClickListener listener){
this.mItemClickListener = listener;
}
/**
* 设置条目长按事件
* @param listener 监听器
*/
public void setOnItemLongClickListener(OnItemLongClickListener listener){
this.mItemLongClickListener = listener;
}
/**
* 设置孩子点击事件
* @param listener 监听器
*/
public void setOnItemChildClickListener(OnItemChildClickListener listener) {
this.mOnItemChildClickListener = listener;
}
public OnItemChildClickListener getOnItemChildClickListener() {
return mOnItemChildClickListener;
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/holder/BaseViewHolder.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.holder;
import android.content.Context;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.utils.RefreshLogUtils;
import java.lang.reflect.Field;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/4/22
* desc : ViewHolder的简单封装,M为这个itemView对应的model,使用RecyclerArrayAdapter就一定要用
* 这个ViewHolder
* 推荐子类继承第二个构造函数。并将子类的构造函数设为一个ViewGroup parent
* revise: 参考鸿洋大神的baseAdapter封装库
* 具体可以参考我的adapter封装库:https://github.com/yangchong211/YCBaseAdapter
* </pre>
*/
public class BaseViewHolder<M> extends RecyclerView.ViewHolder {
// SparseArray 比 HashMap 更省内存,在某些条件下性能更好,只能存储 key 为 int 类型的数据,
// 用来存放 View 以减少 findViewById 的次数
private SparseArray<View> viewSparseArray;
public BaseViewHolder(View itemView) {
super(itemView);
if(viewSparseArray==null){
viewSparseArray = new SparseArray<>();
}
}
public BaseViewHolder(ViewGroup parent, @LayoutRes int res) {
super(LayoutInflater.from(parent.getContext()).inflate(res, parent, false));
if(viewSparseArray==null){
viewSparseArray = new SparseArray<>();
}
}
/**
* 子类设置数据方法
* @param data data
*/
public void setData(M data) {}
/**
* findViewById方式
* 根据 ID 来获取 View
* @param viewId viewID
* @param <T> 泛型
* @return 将结果强转为 View 或 View 的子类型
*/
@SuppressWarnings("unchecked")
public <T extends View> T getView(int viewId) {
// 先从缓存中找,找打的话则直接返回
// 如果找不到则 findViewById ,再把结果存入缓存中
View view = viewSparseArray.get(viewId);
if (view == null) {
view = itemView.findViewById(viewId);
viewSparseArray.put(viewId, view);
}
return (T) view;
}
/**
* 获取上下文context
* @return context
*/
protected Context getContext(){
return itemView.getContext();
}
/**
* 获取数据索引的位置
* @return position
*/
protected int getDataPosition(){
RecyclerView.Adapter adapter = getOwnerAdapter();
if (adapter instanceof RecyclerArrayAdapter){
int headerCount = ((RecyclerArrayAdapter) adapter).getHeaderCount();
//注意需要减去header的count,否则造成索引错乱
return getAdapterPosition() - headerCount;
}
return getAdapterPosition();
}
/**
* 获取adapter对象
* @param <T> adapter
* @return adapter
*/
@Nullable
private <T extends RecyclerView.Adapter> T getOwnerAdapter(){
RecyclerView recyclerView = getOwnerRecyclerView();
//noinspection unchecked
return recyclerView != null ? (T) recyclerView.getAdapter() : null;
}
@SuppressWarnings("CatchMayIgnoreException")
@Nullable
private RecyclerView getOwnerRecyclerView(){
try {
//使用反射
Field field = RecyclerView.ViewHolder.class.getDeclaredField("mOwnerRecyclerView");
//设置暴力访问权限
field.setAccessible(true);
return (RecyclerView) field.get(this);
} catch (NoSuchFieldException ignored) {
RefreshLogUtils.e(ignored.getLocalizedMessage());
} catch (IllegalAccessException ignored) {
RefreshLogUtils.e(ignored.getLocalizedMessage());
}
return null;
}
/**
* 添加子控件的点击事件
* @param viewId 控件id
*/
protected void addOnClickListener(@IdRes final int viewId) {
final View view = getView(viewId);
if (view != null) {
if (!view.isClickable()) {
//如果是不可点击,则需要手动设置可以点击
view.setClickable(true);
}
view.setOnClickListener(listener);
}
}
/**
* 创建listener监听,主要是item中的child点击监听
*/
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(getOwnerAdapter()!=null){
OnItemChildClickListener onItemChildClickListener = ((RecyclerArrayAdapter)
getOwnerAdapter()).getOnItemChildClickListener();
if (onItemChildClickListener != null) {
onItemChildClickListener.onItemChildClick(v, getDataPosition());
}
}
}
};
/**
* 设置TextView的值
*/
public BaseViewHolder setText(int viewId, String text) {
TextView tv = getView(viewId);
tv.setText(text);
return this;
}
} | yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/inter/InterEventDelegate.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.inter;
import android.view.View;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/4/28
* desc : 数据处理和加载监听接口
* revise:
* </pre>
*/
public interface InterEventDelegate {
/**
* 添加数据
* @param length 长度
*/
void addData(int length);
/**
* 清除数据
*/
void clear();
/**
* 停止加载更多
*/
void stopLoadMore();
/**
* 暂停加载更多
*/
void pauseLoadMore();
/**
* 恢复加载更多
*/
void resumeLoadMore();
/**
* 设置加载更多监听
* @param view view
* @param listener listener
*/
void setMore(View view, OnMoreListener listener);
/**
* 设置没有更多监听
* @param view view
* @param listener listener
*/
void setNoMore(View view, OnNoMoreListener listener);
/**
* 设置加载更多错误监听
* @param view view
* @param listener listener
*/
void setErrorMore(View view, OnErrorListener listener);
/**
* 设置加载更多监听
* @param res res
* @param listener listener
*/
void setMore(int res, OnMoreListener listener);
/**
* 设置没有更多监听
* @param res res
* @param listener listener
*/
void setNoMore(int res, OnNoMoreListener listener);
/**
* 设置加载更多错误监听
* @param res res
* @param listener listener
*/
void setErrorMore(int res, OnErrorListener listener);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/inter/InterItemView.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.inter;
import android.view.View;
import android.view.ViewGroup;
/**
* <pre>
* @author yangchong
* blog : https://blog.csdn.net/m0_37700275/article/details/80863685
* time : 2017/4/22
* desc :
* revise: 支持多种状态切换;支持上拉加载更多,下拉刷新;支持添加头部或底部view
* </pre>
*/
public interface InterItemView {
/**
* 创建view
* @param parent parent
* @return view
*/
View onCreateView(ViewGroup parent);
/**
* 绑定view
* @param headerView headerView
*/
void onBindView(View headerView);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/inter/OnErrorListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.inter;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/3/13
* desc : 上拉加载更多异常监听
* revise:
* </pre>
*/
public interface OnErrorListener {
/**
* 上拉加载,加载更多数据异常展示,这个方法可以暂停或者停止加载数据
*/
void onErrorShow();
/**
* 这个方法是点击加载更多数据异常展示布局的操作,比如恢复加载更多等等
*/
void onErrorClick();
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/inter/OnItemChildClickListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.inter;
import android.view.View;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/4/28
* desc : item中孩子点击监听接口
* revise:
* </pre>
*/
public interface OnItemChildClickListener {
/**
* item中孩子点击监听接口
* @param view view
* @param position position索引
*/
void onItemChildClick(View view, int position);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/inter/OnItemClickListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.inter;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/4/28
* desc : item中点击监听接口
* revise:
* </pre>
*/
public interface OnItemClickListener {
/**
* item中点击监听接口
* @param position 索引
*/
void onItemClick(int position);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/inter/OnItemLongClickListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.inter;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2016/4/28
* desc : item中长按点击监听接口
* revise:
* </pre>
*/
public interface OnItemLongClickListener {
/**
* item中长按点击监听接口
* @param position 索引
* @return
*/
boolean onItemLongClick(int position);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/inter/OnLoadMoreListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.inter;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/3/13
* desc : 上拉加载更多监听
* revise:
* </pre>
*/
public interface OnLoadMoreListener {
/**
* 上拉加载更多操作
*/
void onLoadMore();
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/inter/OnMoreListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.inter;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/3/13
* desc : 上拉加载更多监听
* revise:
* </pre>
*/
public interface OnMoreListener {
/**
* 上拉加载更多操作
*/
void onMoreShow();
/**
* 上拉加载更多操作,手动触发
*/
void onMoreClick();
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/inter/OnNoMoreListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.inter;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/3/13
* desc : 上拉加载没有更多数据监听
* revise:
* </pre>
*/
public interface OnNoMoreListener {
/**
* 上拉加载,没有更多数据展示,这个方法可以暂停或者停止加载数据
*/
void onNoMoreShow();
/**
* 这个方法是点击没有更多数据展示布局的操作,比如可以做吐司等等
*/
void onNoMoreClick();
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/item/DividerViewItemLine.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.item;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.view.View;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2017/5/2
* desc : list条目的分割线
* revise: 可以设置线条颜色和宽度,并且可以设置距离左右的间距
* </pre>
*/
public class DividerViewItemLine extends RecyclerView.ItemDecoration{
private ColorDrawable mColorDrawable;
/**
* 分割线的高度,单位是像素px
*/
private int mHeight;
/**
* 距离左边的padding值
*/
private int mPaddingLeft;
/**
* 距离右边的padding值
*/
private int mPaddingRight;
/**
* 设置是否绘制最后一条item的分割线
*/
private boolean mDrawLastItem = true;
/**
* 设置是否绘制header和footer的分割线
*/
private boolean mDrawHeaderFooter = false;
public DividerViewItemLine(int color, int height) {
this.mColorDrawable = new ColorDrawable(color);
this.mHeight = height;
}
public DividerViewItemLine(int color, int height, int paddingLeft, int paddingRight) {
this.mColorDrawable = new ColorDrawable(color);
this.mHeight = height;
this.mPaddingLeft = paddingLeft;
this.mPaddingRight = paddingRight;
}
public void setDrawLastItem(boolean mDrawLastItem) {
this.mDrawLastItem = mDrawLastItem;
}
public void setDrawHeaderFooter(boolean mDrawHeaderFooter) {
this.mDrawHeaderFooter = mDrawHeaderFooter;
}
/**
* 调用的是getItemOffsets会被多次调用,在layoutManager每次测量可摆放的view的时候回调用一次,
* 在当前状态下需要摆放多少个view这个方法就会回调多少次。
* @param outRect 核心参数,这个rect相当于item摆放的时候设置的margin,
* rect的left相当于item的marginLeft,
* rect的right相当于item的marginRight
* @param view 当前绘制的view,可以用来获取它在adapter中的位置
* @param parent recyclerView
* @param state 状态,用的很少
*/
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
int orientation = 0;
int headerCount = 0,footerCount = 0;
if (parent.getAdapter()==null){
return;
}
//获取header和footer的数量
if (parent.getAdapter() instanceof RecyclerArrayAdapter){
headerCount = ((RecyclerArrayAdapter) parent.getAdapter()).getHeaderCount();
footerCount = ((RecyclerArrayAdapter) parent.getAdapter()).getFooterCount();
}
RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
if (layoutManager instanceof StaggeredGridLayoutManager){
orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
}else if (layoutManager instanceof GridLayoutManager){
orientation = ((GridLayoutManager) layoutManager).getOrientation();
}else if (layoutManager instanceof LinearLayoutManager){
orientation = ((LinearLayoutManager) layoutManager).getOrientation();
}
int itemCount = parent.getAdapter().getItemCount();
int count = itemCount-footerCount;
//下面代码才是重点,更多内容可以看我的GitHub博客汇总:https://github.com/yangchong211/YCBlogs
if (mDrawHeaderFooter){
if (position >= headerCount && position<count){
if (orientation == OrientationHelper.VERTICAL){
//当是竖直方向的时候,距离底部marginBottom是分割线的高度
outRect.bottom = mHeight;
}else {
//noinspection SuspiciousNameCombination
outRect.right = mHeight;
}
}
}
}
@SuppressWarnings("ConstantConditions")
@Override
public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state) {
if (parent.getAdapter() == null){
return;
}
int orientation = 0;
int headerCount = 0, footerCount = 0 , dataCount;
if (parent.getAdapter() instanceof RecyclerArrayAdapter){
headerCount = ((RecyclerArrayAdapter) parent.getAdapter()).getHeaderCount();
footerCount = ((RecyclerArrayAdapter) parent.getAdapter()).getFooterCount();
dataCount = ((RecyclerArrayAdapter) parent.getAdapter()).getCount();
}else {
dataCount = parent.getAdapter().getItemCount();
}
int dataStartPosition = headerCount;
int dataEndPosition = headerCount+dataCount;
RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
if (layoutManager instanceof StaggeredGridLayoutManager){
orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
}else if (layoutManager instanceof GridLayoutManager){
orientation = ((GridLayoutManager) layoutManager).getOrientation();
}else if (layoutManager instanceof LinearLayoutManager){
orientation = ((LinearLayoutManager) layoutManager).getOrientation();
}
int start,end;
if (orientation == OrientationHelper.VERTICAL){
start = parent.getPaddingLeft() + mPaddingLeft;
end = parent.getWidth() - parent.getPaddingRight() - mPaddingRight;
}else {
start = parent.getPaddingTop() + mPaddingLeft;
end = parent.getHeight() - parent.getPaddingBottom() - mPaddingRight;
}
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
int position = parent.getChildAdapterPosition(child);
//数据项除了最后一项 数据项最后一项
//header&footer且可绘制
boolean a = position >= dataStartPosition;
boolean b = position<dataEndPosition-1;
boolean d = position == dataEndPosition-1 && mDrawLastItem;
boolean f = !(position>=dataStartPosition&&position<dataEndPosition)&&mDrawHeaderFooter;
if (a){
if (b ||d ||f){
if (orientation == OrientationHelper.VERTICAL){
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mHeight;
mColorDrawable.setBounds(start,top,end,bottom);
mColorDrawable.draw(c);
}else {
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
child.getLayoutParams();
int left = child.getRight() + params.rightMargin;
int right = left + mHeight;
mColorDrawable.setBounds(left,start,right,end);
mColorDrawable.draw(c);
}
}
}
}
}
} | yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/item/RecycleViewItemLine.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.item;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import org.yczbj.ycrefreshviewlib.utils.RefreshLogUtils;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2017/5/2
* desc : list条目的分割线
* revise: 可以设置线条颜色和宽度
* </pre>
*/
public class RecycleViewItemLine extends RecyclerView.ItemDecoration {
private Paint mPaint;
private Drawable mDivider;
/**
* 分割线高度,默认为1px
*/
private int mDividerHeight = 1;
/**
* 列表的方向:LinearLayoutManager.VERTICAL或LinearLayoutManager.HORIZONTAL
*/
private int mOrientation;
private static int[] ATTRS = new int[]{android.R.attr.listDivider};
/**
* 默认分割线:高度为2px,颜色为灰色
* @param context 上下文
* @param orientation 列表方向
*/
public RecycleViewItemLine(Context context, int orientation) {
if (orientation != LinearLayoutManager.VERTICAL &&
orientation != LinearLayoutManager.HORIZONTAL) {
throw new IllegalArgumentException("请输入正确的参数!");
}
mOrientation = orientation;
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
}
/**
* 自定义分割线
* @param context 上下文
* @param orientation 列表方向
* @param drawableId 分割线图片,或者shape图形
*/
public RecycleViewItemLine(Context context, int orientation, int drawableId) {
this(context, orientation);
mDivider = ContextCompat.getDrawable(context, drawableId);
if (mDivider != null) {
mDividerHeight = mDivider.getIntrinsicHeight();
}
}
/**
* 自定义分割线
* @param context 上下文
* @param orientation 列表方向
* @param dividerHeight 分割线高度
* @param dividerColor 分割线颜色
*/
public RecycleViewItemLine(Context context, int orientation,
int dividerHeight, int dividerColor) {
this(context, orientation);
mDividerHeight = dividerHeight;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//设置画笔paint的颜色
mPaint.setColor(dividerColor);
//设置样式
mPaint.setStyle(Paint.Style.FILL);
}
/**
* 调用的是getItemOffsets会被多次调用,在layoutManager每次测量可摆放的view的时候回调用一次,
* 在当前状态下需要摆放多少个view这个方法就会回调多少次。
* @param outRect 核心参数,这个rect相当于item摆放的时候设置的margin,
* rect的left相当于item的marginLeft,
* rect的right相当于item的marginRight
* @param view 当前绘制的view,可以用来获取它在adapter中的位置
* @param parent recyclerView
* @param state 状态,用的很少
*/
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
//给bottom留出一个高度为mDividerHeight的空白
//这样做的目的是什么呢?就是为下面onDraw方法绘制高度为mDividerHeight的分割线做准备用的
//set方法作用:将矩形的坐标设置为指定的值
outRect.set(0, 0, 0, mDividerHeight);
RefreshLogUtils.d("RecycleViewItemLine-------"+"getItemOffsets");
}
/**
* 绘制分割线
* ItemDecoration的onDraw方法是在RecyclerView的onDraw方法中调用的
* 注意这时候传入的canvas是RecyclerView的canvas,要时刻注意这点,它是和RecyclerView的边界是一致的。
* 这个时候绘制的内容相当于背景,会被item覆盖。
* @param c canvas用来绘制的画板
* @param parent recyclerView
* @param state 状态,用的很少
*/
@Override
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state) {
super.onDraw(c, parent, state);
if (mOrientation == LinearLayoutManager.VERTICAL) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
RefreshLogUtils.d("RecycleViewItemLine-------"+"onDraw");
}
/**
* 绘制分割线
* ItemDecoration的onDrawOver方法是在RecyclerView的draw方法中调用的
* 同样传入的是RecyclerView的canvas,这时候onLayout已经调用,所以此时绘制的内容会覆盖item。
* @param c canvas用来绘制的画板
* @param parent recyclerView
* @param state 状态,用的很少
*/
@Override
public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state) {
super.onDrawOver(c, parent, state);
RefreshLogUtils.d("RecycleViewItemLine-------"+"onDrawOver");
}
/**
* 绘制横向 item 分割线
*/
private void drawHorizontal(Canvas canvas, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
RefreshLogUtils.d("小杨逗比左右的间距分别是" + left + "----"+right);
//获取的当前显示的view的数量,并不会获取不显示的view的数量。
//假如recyclerView里共有30条数据,而当前屏幕内显示的只有5条,这paren.getChildCount的值是5,不是30。
final int childSize = parent.getChildCount();
for (int i = 0; i < childSize; i++) {
//获取索引i处的控件view
final View child = parent.getChildAt(i);
//拿到layoutParams属性
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams)
child.getLayoutParams();
final int top = child.getBottom() + layoutParams.bottomMargin;
final int bottom = top + mDividerHeight;
if (mDivider != null) {
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(canvas);
}
//使用画笔paint进行绘制
if (mPaint != null) {
canvas.drawRect(left, top, right, bottom, mPaint);
}
}
}
/**
* 绘制纵向 item 分割线
*/
private void drawVertical(Canvas canvas, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
final int childSize = parent.getChildCount();
for (int i = 0; i < childSize; i++) {
final View child = parent.getChildAt(i);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams)
child.getLayoutParams();
final int left = child.getRight() + layoutParams.rightMargin;
final int right = left + mDividerHeight;
if (mDivider != null) {
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(canvas);
}
if (mPaint != null) {
canvas.drawRect(left, top, right, bottom, mPaint);
}
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/item/SpaceViewItemLine.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.item;
import android.graphics.Rect;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.view.View;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import static android.widget.LinearLayout.VERTICAL;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2017/5/2
* desc : list条目的分割线
* revise: 使用默认的分割线颜色,且分割线宽度也是默认值,适用于瀑布流中的间距设置
* </pre>
*/
public class SpaceViewItemLine extends RecyclerView.ItemDecoration {
private int space;
private boolean mPaddingEdgeSide = true;
private boolean mPaddingStart = true;
private boolean mPaddingHeaderFooter = false;
public SpaceViewItemLine(int space) {
this.space = space ;
}
public void setPaddingEdgeSide(boolean mPaddingEdgeSide) {
this.mPaddingEdgeSide = mPaddingEdgeSide;
}
public void setPaddingStart(boolean mPaddingStart) {
this.mPaddingStart = mPaddingStart;
}
public void setPaddingHeaderFooter(boolean mPaddingHeaderFooter) {
this.mPaddingHeaderFooter = mPaddingHeaderFooter;
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
int spanCount = 0;
int orientation = 0;
int spanIndex = 0;
int headerCount = 0,footerCount = 0;
RecyclerView.Adapter adapter = parent.getAdapter();
if (adapter==null){
return;
}
if (adapter instanceof RecyclerArrayAdapter){
headerCount = ((RecyclerArrayAdapter) adapter).getHeaderCount();
footerCount = ((RecyclerArrayAdapter) adapter).getFooterCount();
}
RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
if (layoutManager instanceof StaggeredGridLayoutManager){
orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
spanCount = ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
spanIndex = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
}else if (layoutManager instanceof GridLayoutManager){
orientation = ((GridLayoutManager) layoutManager).getOrientation();
spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
spanIndex = ((GridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
}else if (layoutManager instanceof LinearLayoutManager){
orientation = ((LinearLayoutManager) layoutManager).getOrientation();
spanCount = 1;
spanIndex = 0;
}
//普通Item的尺寸
if ((position>=headerCount&&position<adapter.getItemCount()-footerCount)) {
if (orientation == VERTICAL) {
float expectedWidth = (float) (parent.getWidth() - space * (spanCount + (mPaddingEdgeSide ? 1 : -1))) / spanCount;
float originWidth = (float) parent.getWidth() / spanCount;
float expectedX = (mPaddingEdgeSide ? space : 0) + (expectedWidth + space) * spanIndex;
float originX = originWidth * spanIndex;
outRect.left = (int) (expectedX - originX);
outRect.right = (int) (originWidth - outRect.left - expectedWidth);
if (position - headerCount < spanCount && mPaddingStart) {
outRect.top = space;
}
outRect.bottom = space;
} else {
float expectedHeight = (float) (parent.getHeight() - space * (spanCount + (mPaddingEdgeSide ? 1 : -1))) / spanCount;
float originHeight = (float) parent.getHeight() / spanCount;
float expectedY = (mPaddingEdgeSide ? space : 0) + (expectedHeight + space) * spanIndex;
float originY = originHeight * spanIndex;
outRect.bottom = (int) (expectedY - originY);
outRect.top = (int) (originHeight - outRect.bottom - expectedHeight);
if (position - headerCount < spanCount && mPaddingStart) {
outRect.left = space;
}
outRect.right = space;
}
}else if (mPaddingHeaderFooter){
if (orientation == VERTICAL){outRect.right = outRect.left = mPaddingEdgeSide ? space : 0;
outRect.top = mPaddingStart?space : 0;
}else { outRect.top = outRect.bottom = mPaddingEdgeSide ? space : 0;
outRect.left = mPaddingStart?space : 0;
}
}
}
} | yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/item/StickyHeaderItemLine.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.item;
import android.annotation.SuppressLint;
import android.graphics.Canvas;
import android.graphics.Rect;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.utils.RefreshLogUtils;
import java.util.HashMap;
import java.util.Map;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2017/5/2
* desc : list条目的分割线【粘贴头部】
* revise:
* </pre>
*/
public class StickyHeaderItemLine extends RecyclerView.ItemDecoration {
private static final long NO_HEADER_ID = -1L;
private Map<Long, RecyclerView.ViewHolder> mHeaderCache;
private IStickyHeaderAdapter mAdapter;
private boolean mRenderInline;
private boolean mIncludeHeader = false;
public interface IStickyHeaderAdapter<T extends RecyclerView.ViewHolder> {
long getHeaderId(int position);
T onCreateHeaderViewHolder(ViewGroup parent);
void onBindHeaderViewHolder(T viewholder, int position);
}
public StickyHeaderItemLine(IStickyHeaderAdapter adapter) {
this(adapter, false);
}
@SuppressLint("UseSparseArrays")
public StickyHeaderItemLine(IStickyHeaderAdapter adapter, boolean renderInline) {
mAdapter = adapter;
mHeaderCache = new HashMap<>();
//mHeaderCache = new LongSparseArray<>();
mRenderInline = renderInline;
}
public void setIncludeHeader(boolean mIncludeHeader) {
this.mIncludeHeader = mIncludeHeader;
}
/**
* 调用的是getItemOffsets会被多次调用,在layoutManager每次测量可摆放的view的时候回调用一次,
* 在当前状态下需要摆放多少个view这个方法就会回调多少次。
* @param outRect 核心参数,这个rect相当于item摆放的时候设置的margin,
* rect的left相当于item的marginLeft,
* rect的right相当于item的marginRight
* @param view 当前绘制的view,可以用来获取它在adapter中的位置
* @param parent recyclerView
* @param state 状态,用的很少
*/
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
int headerHeight = 0;
if (!mIncludeHeader){
if (parent.getAdapter() instanceof RecyclerArrayAdapter){
int headerCount = ((RecyclerArrayAdapter) parent.getAdapter()).getHeaderCount();
int footerCount = ((RecyclerArrayAdapter) parent.getAdapter()).getFooterCount();
int dataCount = ((RecyclerArrayAdapter) parent.getAdapter()).getCount();
if (position<headerCount){
return;
}
if (position>=headerCount+dataCount){
return ;
}
if (position>=headerCount){
position-=headerCount;
}
}
}
boolean hasHeader = hasHeader(position);
boolean showHeaderAboveItem = showHeaderAboveItem(position);
if (position != RecyclerView.NO_POSITION && hasHeader && showHeaderAboveItem) {
View header = getHeader(parent, position).itemView;
headerHeight = getHeaderHeightForLayout(header);
}
RefreshLogUtils.d("StickyItemLine------headerHeight---"+headerHeight);
outRect.set(0, headerHeight, 0, 0);
}
private boolean showHeaderAboveItem(int itemAdapterPosition) {
if (itemAdapterPosition == 0) {
return true;
}
return mAdapter.getHeaderId(itemAdapterPosition - 1)
!= mAdapter.getHeaderId(itemAdapterPosition);
}
public void clearHeaderCache() {
mHeaderCache.clear();
}
public View findHeaderViewUnder(float x, float y) {
for (RecyclerView.ViewHolder holder : mHeaderCache.values()) {
final View child = holder.itemView;
final float translationX = ViewCompat.getTranslationX(child);
final float translationY = ViewCompat.getTranslationY(child);
if (x >= child.getLeft() + translationX && x <= child.getRight() + translationX &&
y >= child.getTop() + translationY && y <= child.getBottom() + translationY) {
return child;
}
}
return null;
}
/**
* 判断是否有header
* @param position 索引
* @return
*/
private boolean hasHeader(int position) {
return mAdapter.getHeaderId(position) != NO_HEADER_ID;
}
private RecyclerView.ViewHolder getHeader(RecyclerView parent, int position) {
final long key = mAdapter.getHeaderId(position);
if (mHeaderCache.containsKey(key)) {
return mHeaderCache.get(key);
} else {
final RecyclerView.ViewHolder holder = mAdapter.onCreateHeaderViewHolder(parent);
final View header = holder.itemView;
//noinspection unchecked
mAdapter.onBindHeaderViewHolder(holder, position);
int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(),
View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(),
View.MeasureSpec.UNSPECIFIED);
int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
parent.getPaddingLeft() + parent.getPaddingRight(),
header.getLayoutParams().width);
int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
parent.getPaddingTop() + parent.getPaddingBottom(),
header.getLayoutParams().height);
header.measure(childWidth, childHeight);
header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight());
mHeaderCache.put(key, holder);
return holder;
}
}
/**
* 绘制分割线
* ItemDecoration的onDrawOver方法是在RecyclerView的draw方法中调用的
* 同样传入的是RecyclerView的canvas,这时候onLayout已经调用,所以此时绘制的内容会覆盖item。
* @param canvas canvas用来绘制的画板
* @param parent recyclerView
* @param state 状态,用的很少
*/
@Override
public void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state) {
if (parent.getAdapter() == null){
return;
}
final int count = parent.getChildCount();
long previousHeaderId = -1;
for (int layoutPos = 0; layoutPos < count; layoutPos++) {
final View child = parent.getChildAt(layoutPos);
int adapterPos = parent.getChildAdapterPosition(child);
if (!mIncludeHeader){
if (parent.getAdapter() instanceof RecyclerArrayAdapter){
int headerCount = ((RecyclerArrayAdapter) parent.getAdapter()).getHeaderCount();
int footerCount = ((RecyclerArrayAdapter) parent.getAdapter()).getFooterCount();
int dataCount = ((RecyclerArrayAdapter) parent.getAdapter()).getCount();
if (adapterPos<headerCount){
continue;
}
if (adapterPos>=headerCount+dataCount){
continue ;
}
if (adapterPos>=headerCount){
adapterPos-=headerCount;
}
}
}
if (adapterPos != RecyclerView.NO_POSITION && hasHeader(adapterPos)) {
long headerId = mAdapter.getHeaderId(adapterPos);
if (headerId != previousHeaderId) {
previousHeaderId = headerId;
View header = getHeader(parent, adapterPos).itemView;
canvas.save();
final int left = child.getLeft();
final int top = getHeaderTop(parent, child, header, adapterPos, layoutPos);
canvas.translate(left, top);
header.setTranslationX(left);
header.setTranslationY(top);
header.draw(canvas);
canvas.restore();
}
}
}
}
private int getHeaderTop(RecyclerView parent, View child, View header,
int adapterPos, int layoutPos) {
int headerHeight = getHeaderHeightForLayout(header);
int top = ((int) child.getY()) - headerHeight;
if (layoutPos == 0) {
final int count = parent.getChildCount();
final long currentId = mAdapter.getHeaderId(adapterPos);
// find next view with header and compute the offscreen push if needed
for (int i = 1; i < count; i++) {
int adapterPosHere = parent.getChildAdapterPosition(parent.getChildAt(i));
if (adapterPosHere != RecyclerView.NO_POSITION) {
long nextId = mAdapter.getHeaderId(adapterPosHere);
if (nextId != currentId) {
final View next = parent.getChildAt(i);
final int offset = ((int) next.getY()) - (headerHeight +
getHeader(parent, adapterPosHere).itemView.getHeight());
if (offset < 0) {
return offset;
} else {
break;
}
}
}
}
top = Math.max(0, top);
}
return top;
}
private int getHeaderHeightForLayout(View header) {
return mRenderInline ? 0 : header.getHeight();
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/observer/FixDataObserver.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.observer;
import androidx.recyclerview.widget.RecyclerView;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2017/4/28
* desc : 自定义FixDataObserver
* revise: 当插入数据的时候,需要
* </pre>
*/
public class FixDataObserver extends RecyclerView.AdapterDataObserver {
private RecyclerView recyclerView;
public FixDataObserver(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
if (recyclerView.getAdapter() instanceof RecyclerArrayAdapter) {
RecyclerArrayAdapter adapter = (RecyclerArrayAdapter) recyclerView.getAdapter();
//获取footer的数量
int footerCount = adapter.getFooterCount();
//获取所有item的数量,包含header和footer
int count = adapter.getCount();
//如果footer大于0,并且
if (footerCount > 0 && count == itemCount) {
recyclerView.scrollToPosition(0);
}
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/observer/ViewDataObserver.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.observer;
import androidx.recyclerview.widget.RecyclerView;
import org.yczbj.ycrefreshviewlib.view.YCRefreshView;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2017/4/28
* desc : 自定义AdapterDataObserver
* revise:
* </pre>
*/
public class ViewDataObserver extends RecyclerView.AdapterDataObserver {
private YCRefreshView recyclerView;
private RecyclerArrayAdapter adapter;
/**
* 构造方法
* @param recyclerView recyclerView
*/
public ViewDataObserver(YCRefreshView recyclerView) {
this.recyclerView = recyclerView;
if (recyclerView.getAdapter() instanceof RecyclerArrayAdapter) {
adapter = (RecyclerArrayAdapter) recyclerView.getAdapter();
}
}
/**
* 判断是否是header或者footer
* @param position 索引
* @return true表示是header或者footer
*/
private boolean isHeaderFooter(int position) {
return adapter != null && (position < adapter.getHeaderCount()
|| position >= adapter.getHeaderCount() + adapter.getCount());
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
super.onItemRangeChanged(positionStart, itemCount);
if (!isHeaderFooter(positionStart)) {
update();
}
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
if (!isHeaderFooter(positionStart)) {
update();
}
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
super.onItemRangeRemoved(positionStart, itemCount);
if (!isHeaderFooter(positionStart)) {
update();
}
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
super.onItemRangeMoved(fromPosition, toPosition, itemCount);
//header&footer不会有移动操作
update();
}
@Override
public void onChanged() {
super.onChanged();
//header&footer不会引起changed
update();
}
/**
* 自动更改Container的样式
*/
private void update() {
int count;
if (recyclerView.getAdapter() instanceof RecyclerArrayAdapter) {
count = ((RecyclerArrayAdapter) recyclerView.getAdapter()).getCount();
} else {
count = recyclerView.getAdapter().getItemCount();
}
if (count == 0) {
recyclerView.showEmpty();
} else {
recyclerView.showRecycler();
}
}
} | yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/refresh/RefreshLayout.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.refresh;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
public class RefreshLayout extends ViewGroup {
public RefreshLayout(Context context) {
super(context);
}
public RefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/span/GridSpanSizeLookup.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.span;
import androidx.recyclerview.widget.GridLayoutManager;
import org.yczbj.ycrefreshviewlib.inter.InterItemView;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2017/5/2
* desc : 自定义SpanSizeLookup
* revise:
* </pre>
*/
public class GridSpanSizeLookup extends GridLayoutManager.SpanSizeLookup{
private int mMaxCount;
private ArrayList<InterItemView> headers;
private ArrayList<InterItemView> footers;
private List<Object> mObjects;
public GridSpanSizeLookup(int maxCount, ArrayList<InterItemView> headers,
ArrayList<InterItemView> footers, List<Object> objects){
this.mMaxCount = maxCount;
this.headers = headers;
this.footers = footers;
this.mObjects = objects;
}
/**
* 该方法的返回值就是指定position所占的列数
* @param position 指定索引
* @return 列数
*/
@Override
public int getSpanSize(int position) {
//如果有headerView,则
if (headers.size()!=0){
if (position<headers.size()) {
return mMaxCount;
}
}
//如果有footerView,则
if (footers.size()!=0) {
int i = position - headers.size() - mObjects.size();
if (i >= 0) {
return mMaxCount;
}
}
return 1;
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/swipe/OnSwipeMenuListener.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.swipe;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/9/21
* desc : 侧滑删除和置顶监听事件
* revise:
* </pre>
*/
public interface OnSwipeMenuListener {
/**
* 点击侧滑删除
* @param position 索引位置
*/
void toDelete(int position);
/**
* 点击置顶
* @param position 索引位置
*/
void toTop(int position);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/swipe/YCSwipeMenu.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.swipe;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import org.yczbj.ycrefreshviewlib.R;
public class YCSwipeMenu extends ViewGroup {
//为了处理单击事件的冲突
private int mScaleTouchSlop;
//计算滑动速度用
private int mMaxVelocity;
//多点触摸只算第一根手指的速度
private int mPointerId;
//右侧菜单宽度总和(最大滑动距离)
private int mRightMenuWidths;
//滑动判定临界值(右侧菜单宽度的40%) 手指抬起时,超过了展开,没超过收起menu
private int mLimit;
//存储contentView(第一个View)
private View mContentView;
//private Scroller mScroller;//以前item的滑动动画靠它做,现在用属性动画做
//上一次的xy
private PointF mLastP = new PointF();
//仿QQ,侧滑菜单展开时,点击除侧滑菜单之外的区域,关闭侧滑菜单。
//增加一个布尔值变量,dispatch函数里,每次down时,为true,move时判断,如果是滑动动作,设为false。
//在Intercept函数的up时,判断这个变量,如果仍为true 说明是点击事件,则关闭菜单。
private boolean isUnMoved = true;
//判断手指起始落点,如果距离属于滑动了,就屏蔽一切点击事件。
//up-down的坐标,判断是否是滑动,如果是,则屏蔽一切点击事件
private PointF mFirstP = new PointF();
private boolean isUserSwiped;
//存储的是当前正在展开的View
public YCSwipeMenu mViewCache;
//防止多只手指一起滑我的flag 在每次down里判断, touch事件结束清空
private static boolean isTouching;
//滑动速度变量
private VelocityTracker mVelocityTracker;
//右滑删除功能的开关,默认开
private boolean isSwipeEnable;
//IOS、QQ式交互,默认开
private boolean isIos;
//IOS类型下,是否拦截事件的flag
private boolean iosInterceptFlag;
//左滑右滑的开关,默认左滑打开菜单
private boolean isLeftSwipe;
//平滑展开和关闭的动画效果
private ValueAnimator mExpandAnim, mCloseAnim;
private boolean isExpand;//代表当前是否是展开状态 2016 11 03 add
public YCSwipeMenu(Context context) {
this(context, null);
}
public YCSwipeMenu(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public YCSwipeMenu(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
public boolean isSwipeEnable() {
return isSwipeEnable;
}
/**
* 设置侧滑功能开关
* @param swipeEnable 是否打开
*/
public void setSwipeEnable(boolean swipeEnable) {
isSwipeEnable = swipeEnable;
}
public boolean isIos() {
return isIos;
}
/**
* 设置是否开启IOS阻塞式交互
*/
public YCSwipeMenu setIos(boolean ios) {
isIos = ios;
return this;
}
public boolean isLeftSwipe() {
return isLeftSwipe;
}
/**
* 设置是否开启左滑出菜单,设置false 为右滑出菜单
* @param leftSwipe 是否画出左边菜单
*/
public YCSwipeMenu setLeftSwipe(boolean leftSwipe) {
isLeftSwipe = leftSwipe;
return this;
}
public boolean isExpand() {
return isExpand;
}
/**
* 返回ViewCache
*/
/*public static YCSwipeMenu getViewCache() {
return mViewCache;
}*/
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
mScaleTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mMaxVelocity = ViewConfiguration.get(context).getScaledMaximumFlingVelocity();
//初始化滑动帮助类对象
//mScroller = new Scroller(context);
//右滑删除功能的开关,默认开
isSwipeEnable = true;
//IOS、QQ式交互,默认开
isIos = true;
//左滑右滑的开关,默认左滑打开菜单
isLeftSwipe = true;
TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.YCSwipeMenu, defStyleAttr, 0);
int count = ta.getIndexCount();
for (int i = 0; i < count; i++) {
int attr = ta.getIndex(i);
//如果引用成AndroidLib 资源都不是常量,无法使用switch case
if (attr == R.styleable.YCSwipeMenu_swipeEnable) {
isSwipeEnable = ta.getBoolean(attr, true);
} else if (attr == R.styleable.YCSwipeMenu_ios) {
isIos = ta.getBoolean(attr, true);
} else if (attr == R.styleable.YCSwipeMenu_leftSwipe) {
isLeftSwipe = ta.getBoolean(attr, true);
}
}
ta.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setClickable(true);//令自己可点击,从而获取触摸事件
mRightMenuWidths = 0;//由于ViewHolder的复用机制,每次这里要手动恢复初始值
int mHeight = 0;
int contentWidth = 0;//2016 11 09 add,适配GridLayoutManager,将以第一个子Item(即ContentItem)的宽度为控件宽度
int childCount = getChildCount();
//add by 2016 08 11 为了子View的高,可以matchParent(参考的FrameLayout 和LinearLayout的Horizontal)
final boolean measureMatchParentChildren = MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
boolean isNeedMeasureChildHeight = false;
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
//令每一个子View可点击,从而获取触摸事件
childView.setClickable(true);
if (childView.getVisibility() != GONE) {
//后续计划加入上滑、下滑,则将不再支持Item的margin
measureChild(childView, widthMeasureSpec, heightMeasureSpec);
//measureChildWithMargins(childView, widthMeasureSpec, 0, heightMeasureSpec, 0);
final MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
mHeight = Math.max(mHeight, childView.getMeasuredHeight()/* + lp.topMargin + lp.bottomMargin*/);
if (measureMatchParentChildren && lp.height == LayoutParams.MATCH_PARENT) {
isNeedMeasureChildHeight = true;
}
if (i > 0) {//第一个布局是Left item,从第二个开始才是RightMenu
mRightMenuWidths += childView.getMeasuredWidth();
} else {
mContentView = childView;
contentWidth = childView.getMeasuredWidth();
}
}
}
setMeasuredDimension(getPaddingLeft() + getPaddingRight() + contentWidth,
mHeight + getPaddingTop() + getPaddingBottom());//宽度取第一个Item(Content)的宽度
mLimit = mRightMenuWidths * 4 / 10;//滑动判断的临界值
//Log.d(TAG, "onMeasure() called with: " + "mRightMenuWidths = [" + mRightMenuWidths);
if (isNeedMeasureChildHeight) {//如果子View的height有MatchParent属性的,设置子View高度
forceUniformHeight(childCount, widthMeasureSpec);
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
/**
* 给MatchParent的子View设置高度
*/
private void forceUniformHeight(int count, int widthMeasureSpec) {
// Pretend that the linear layout has an exact size. This is the measured height of
// ourselves. The measured height should be the max height of the children, changed
// to accommodate the heightMeasureSpec from the parent
int uniformMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(),
MeasureSpec.EXACTLY);//以父布局高度构建一个Exactly的测量参数
for (int i = 0; i < count; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
if (lp.height == LayoutParams.MATCH_PARENT) {
// Temporarily force children to reuse their old measured width
int oldWidth = lp.width;//measureChildWithMargins 这个函数会用到宽,所以要保存一下
lp.width = child.getMeasuredWidth();
// Remeasure with new dimensions
measureChildWithMargins(child, widthMeasureSpec, 0, uniformMeasureSpec, 0);
lp.width = oldWidth;
}
}
}
}
@SuppressWarnings("PointlessArithmeticExpression")
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
//LogUtils.e(TAG, "onLayout() called with: " + "changed = [" + changed + "], l = [" + l + "], t = [" + t + "], r = [" + r + "], b = [" + b + "]");
int childCount = getChildCount();
int left = 0 + getPaddingLeft();
int right = 0 + getPaddingLeft();
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
if (childView.getVisibility() != GONE) {
if (i == 0) {//第一个子View是内容 宽度设置为全屏
childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
left = left + childView.getMeasuredWidth();
} else {
if (isLeftSwipe) {
childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
left = left + childView.getMeasuredWidth();
} else {
childView.layout(right - childView.getMeasuredWidth(), getPaddingTop(), right, getPaddingTop() + childView.getMeasuredHeight());
right = right - childView.getMeasuredWidth();
}
}
}
}
//Log.d(TAG, "onLayout() called with: " + "maxScrollGap = [" + maxScrollGap + "], l = [" + l + "], t = [" + t + "], r = [" + r + "], b = [" + b + "]");
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//LogUtils.d(TAG, "dispatchTouchEvent() called with: " + "ev = [" + ev + "]");
if (isSwipeEnable) {
acquireVelocityTracker(ev);
final VelocityTracker verTracker = mVelocityTracker;
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
isUserSwiped = false;//2016 11 03 add,判断手指起始落点,如果距离属于滑动了,就屏蔽一切点击事件。
isUnMoved = true;//2016 10 22 add , 仿QQ,侧滑菜单展开时,点击内容区域,关闭侧滑菜单。
iosInterceptFlag = false;//add by 2016 09 11 ,每次DOWN时,默认是不拦截的
if (isTouching) {//如果有别的指头摸过了,那么就return false。这样后续的move..等事件也不会再来找这个View了。
return false;
} else {
isTouching = true;//第一个摸的指头,赶紧改变标志,宣誓主权。
}
mLastP.set(ev.getRawX(), ev.getRawY());
mFirstP.set(ev.getRawX(), ev.getRawY());//2016 11 03 add,判断手指起始落点,如果距离属于滑动了,就屏蔽一切点击事件。
//如果down,view和cacheview不一样,则立马让它还原。且把它置为null
if (mViewCache != null) {
if (mViewCache != this) {
mViewCache.smoothClose();
iosInterceptFlag = isIos;//add by 2016 09 11 ,IOS模式开启的话,且当前有侧滑菜单的View,且不是自己的,就该拦截事件咯。
}
//只要有一个侧滑菜单处于打开状态, 就不给外层布局上下滑动了
getParent().requestDisallowInterceptTouchEvent(true);
}
//求第一个触点的id, 此时可能有多个触点,但至少一个,计算滑动速率用
mPointerId = ev.getPointerId(0);
break;
case MotionEvent.ACTION_MOVE:
//add by 2016 09 11 ,IOS模式开启的话,且当前有侧滑菜单的View,且不是自己的,就该拦截事件咯。滑动也不该出现
if (iosInterceptFlag) {
break;
}
float gap = mLastP.x - ev.getRawX();
//为了在水平滑动中禁止父类ListView等再竖直滑动
if (Math.abs(gap) > 10 || Math.abs(getScrollX()) > 10) {//2016 09 29 修改此处,使屏蔽父布局滑动更加灵敏,
getParent().requestDisallowInterceptTouchEvent(true);
}
//2016 10 22 add , 仿QQ,侧滑菜单展开时,点击内容区域,关闭侧滑菜单。begin
if (Math.abs(gap) > mScaleTouchSlop) {
isUnMoved = false;
}
//2016 10 22 add , 仿QQ,侧滑菜单展开时,点击内容区域,关闭侧滑菜单。end
//如果scroller还没有滑动结束 停止滑动动画
/* if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}*/
scrollBy((int) (gap), 0);//滑动使用scrollBy
//越界修正
if (isLeftSwipe) {//左滑
if (getScrollX() < 0) {
scrollTo(0, 0);
}
if (getScrollX() > mRightMenuWidths) {
scrollTo(mRightMenuWidths, 0);
}
} else {//右滑
if (getScrollX() < -mRightMenuWidths) {
scrollTo(-mRightMenuWidths, 0);
}
if (getScrollX() > 0) {
scrollTo(0, 0);
}
}
mLastP.set(ev.getRawX(), ev.getRawY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
//2016 11 03 add,判断手指起始落点,如果距离属于滑动了,就屏蔽一切点击事件。
if (Math.abs(ev.getRawX() - mFirstP.x) > mScaleTouchSlop) {
isUserSwiped = true;
}
//add by 2016 09 11 ,IOS模式开启的话,且当前有侧滑菜单的View,且不是自己的,就该拦截事件咯。滑动也不该出现
if (!iosInterceptFlag) {//且滑动了 才判断是否要收起、展开menu
//求伪瞬时速度
verTracker.computeCurrentVelocity(1000, mMaxVelocity);
final float velocityX = verTracker.getXVelocity(mPointerId);
if (Math.abs(velocityX) > 1000) {//滑动速度超过阈值
if (velocityX < -1000) {
if (isLeftSwipe) {//左滑
//平滑展开Menu
smoothExpand();
} else {
//平滑关闭Menu
smoothClose();
}
} else {
if (isLeftSwipe) {//左滑
// 平滑关闭Menu
smoothClose();
} else {
//平滑展开Menu
smoothExpand();
}
}
} else {
if (Math.abs(getScrollX()) > mLimit) {//否则就判断滑动距离
//平滑展开Menu
smoothExpand();
} else {
// 平滑关闭Menu
smoothClose();
}
}
}
//释放
releaseVelocityTracker();
//LogUtils.i(TAG, "onTouch A ACTION_UP ACTION_CANCEL:velocityY:" + velocityX);
isTouching = false;//没有手指在摸我了
break;
default:
break;
}
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//Log.d(TAG, "onInterceptTouchEvent() called with: ev = [" + ev + "]");
//add by zhangxutong 2016 12 07 begin:
//禁止侧滑时,点击事件不受干扰。
if (isSwipeEnable) {
switch (ev.getAction()) {
//add by zhangxutong 2016 11 04 begin :
// fix 长按事件和侧滑的冲突。
case MotionEvent.ACTION_MOVE:
//屏蔽滑动时的事件
if (Math.abs(ev.getRawX() - mFirstP.x) > mScaleTouchSlop) {
return true;
}
break;
//add by zhangxutong 2016 11 04 end
case MotionEvent.ACTION_UP:
//为了在侧滑时,屏蔽子View的点击事件
if (isLeftSwipe) {
if (getScrollX() > mScaleTouchSlop) {
//add by 2016 09 10 解决一个智障问题~ 居然不给点击侧滑菜单 我跪着谢罪
//这里判断落点在内容区域屏蔽点击,内容区域外,允许传递事件继续向下的的。。。
if (ev.getX() < getWidth() - getScrollX()) {
//2016 10 22 add , 仿QQ,侧滑菜单展开时,点击内容区域,关闭侧滑菜单。
if (isUnMoved) {
smoothClose();
}
return true;//true表示拦截
}
}
} else {
if (-getScrollX() > mScaleTouchSlop) {
if (ev.getX() > -getScrollX()) {//点击范围在菜单外 屏蔽
//2016 10 22 add , 仿QQ,侧滑菜单展开时,点击内容区域,关闭侧滑菜单。
if (isUnMoved) {
smoothClose();
}
return true;
}
}
}
//add by zhangxutong 2016 11 03 begin:
// 判断手指起始落点,如果距离属于滑动了,就屏蔽一切点击事件。
if (isUserSwiped) {
return true;
}
//add by zhangxutong 2016 11 03 end
break;
}
//模仿IOS 点击其他区域关闭:
if (iosInterceptFlag) {
//IOS模式开启,且当前有菜单的View,且不是自己的 拦截点击事件给子View
return true;
}
}
return super.onInterceptTouchEvent(ev);
}
public void smoothExpand() {
//Log.d(TAG, "smoothExpand() called" + this);
/*mScroller.startScroll(getScrollX(), 0, mRightMenuWidths - getScrollX(), 0);
invalidate();*/
//展开就加入ViewCache:
mViewCache = YCSwipeMenu.this;
//2016 11 13 add 侧滑菜单展开,屏蔽content长按
if (null != mContentView) {
mContentView.setLongClickable(false);
}
cancelAnim();
mExpandAnim = ValueAnimator.ofInt(getScrollX(), isLeftSwipe ? mRightMenuWidths : -mRightMenuWidths);
mExpandAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
scrollTo((Integer) animation.getAnimatedValue(), 0);
}
});
mExpandAnim.setInterpolator(new OvershootInterpolator());
mExpandAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
isExpand = true;
}
});
mExpandAnim.setDuration(300).start();
}
/**
* 每次执行动画之前都应该先取消之前的动画
*/
private void cancelAnim() {
if (mCloseAnim != null && mCloseAnim.isRunning()) {
mCloseAnim.cancel();
}
if (mExpandAnim != null && mExpandAnim.isRunning()) {
mExpandAnim.cancel();
}
}
/**
* 平滑关闭
*/
public void smoothClose() {
//Log.d(TAG, "smoothClose() called" + this);
/* mScroller.startScroll(getScrollX(), 0, -getScrollX(), 0);
invalidate();*/
mViewCache = null;
//2016 11 13 add 侧滑菜单展开,屏蔽content长按
if (null != mContentView) {
mContentView.setLongClickable(true);
}
cancelAnim();
mCloseAnim = ValueAnimator.ofInt(getScrollX(), 0);
mCloseAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
scrollTo((Integer) animation.getAnimatedValue(), 0);
}
});
mCloseAnim.setInterpolator(new AccelerateInterpolator());
mCloseAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
isExpand = false;
}
});
mCloseAnim.setDuration(300).start();
}
/**
* @param event 向VelocityTracker添加MotionEvent
* @see VelocityTracker#obtain()
* @see VelocityTracker#addMovement(MotionEvent)
*/
private void acquireVelocityTracker(final MotionEvent event) {
if (null == mVelocityTracker) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
}
/**
* * 释放VelocityTracker
*
* @see VelocityTracker#clear()
* @see VelocityTracker#recycle()
*/
private void releaseVelocityTracker() {
if (null != mVelocityTracker) {
mVelocityTracker.clear();
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
//每次ViewDetach的时候,判断一下 ViewCache是不是自己,如果是自己,关闭侧滑菜单,且ViewCache设置为null,
// 理由:1 防止内存泄漏(ViewCache是一个静态变量)
// 2 侧滑删除后自己后,这个View被Recycler回收,复用,下一个进入屏幕的View的状态应该是普通状态,而不是展开状态。
@Override
protected void onDetachedFromWindow() {
if (this == mViewCache) {
mViewCache.smoothClose();
mViewCache = null;
}
super.onDetachedFromWindow();
}
//展开时,禁止长按
@Override
public boolean performLongClick() {
return Math.abs(getScrollX()) <= mScaleTouchSlop && super.performLongClick();
}
/**
* 快速关闭。
* 用于 点击侧滑菜单上的选项,同时想让它快速关闭(删除 置顶)。
* 这个方法在ListView里是必须调用的,
* 在RecyclerView里,视情况而定,如果是mAdapter.notifyItemRemoved(pos)方法不用调用。
*/
public void setClose() {
if (this == mViewCache) {
//先取消展开动画
cancelAnim();
mViewCache.scrollTo(0, 0);//关闭
mViewCache = null;
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/touch/ItemTouchHelpCallback.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.touch;
import android.graphics.Canvas;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
/**
* <pre>
* @author 杨充
* blog : https://github.com/yangchong211
* time : 2017/5/2
* desc : 自定义ItemTouchHelper
* revise: 参考严正杰大神博客:https://blog.csdn.net/yanzhenjie1003/article/details/51935982
* </pre>
*/
public class ItemTouchHelpCallback extends ItemTouchHelper.Callback {
/**
* Item操作的回调,去更新UI和数据源
*/
private OnItemTouchCallbackListener onItemTouchCallbackListener;
/**
* 是否可以拖拽
*/
private boolean isCanDrag = false;
/**
* 是否可以被滑动
*/
private boolean isCanSwipe = false;
/**
* 按住拖动item的颜色
*/
private int color = 0;
public ItemTouchHelpCallback(OnItemTouchCallbackListener onItemTouchCallbackListener) {
this.onItemTouchCallbackListener = onItemTouchCallbackListener;
}
/**
* 设置是否可以被拖拽
*
* @param canDrag 是true,否false
*/
public void setDragEnable(boolean canDrag) {
isCanDrag = canDrag;
}
/**
* 设置是否可以被滑动
*
* @param canSwipe 是true,否false
*/
public void setSwipeEnable(boolean canSwipe) {
isCanSwipe = canSwipe;
}
/**
* 设置按住拖动item的颜色
* @param color 颜色
*/
public void setColor(@ColorInt int color){
this.color = color;
}
/**
* 当Item被长按的时候是否可以被拖拽
*
* @return true
*/
@Override
public boolean isLongPressDragEnabled() {
return isCanDrag;
}
/**
* Item是否可以被滑动(H:左右滑动,V:上下滑动)
* isItemViewSwipeEnabled()返回值是否可以拖拽排序,true可以,false不可以
* @return true
*/
@Override
public boolean isItemViewSwipeEnabled() {
return isCanSwipe;
}
/**
* 当用户拖拽或者滑动Item的时候需要我们告诉系统滑动或者拖拽的方向
* 动作标识分:dragFlags和swipeFlags
* dragFlags:列表滚动方向的动作标识(如竖直列表就是上和下,水平列表就是左和右)
* wipeFlags:与列表滚动方向垂直的动作标识(如竖直列表就是左和右,水平列表就是上和下)
*
* 思路:如果你不想上下拖动,可以将 dragFlags = 0
* 如果你不想左右滑动,可以将 swipeFlags = 0
* 最终的动作标识(flags)必须要用makeMovementFlags()方法生成
*/
@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder viewHolder) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof GridLayoutManager) {
// flag如果值是0,相当于这个功能被关闭
int dragFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT
| ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlag = 0;
return makeMovementFlags(dragFlag, swipeFlag);
} else if (layoutManager instanceof LinearLayoutManager) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
int orientation = linearLayoutManager.getOrientation();
int dragFlag = 0;
int swipeFlag = 0;
// 为了方便理解,相当于分为横着的ListView和竖着的ListView
// 如果是横向的布局
if (orientation == LinearLayoutManager.HORIZONTAL) {
swipeFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
dragFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
} else if (orientation == LinearLayoutManager.VERTICAL) {
// 如果是竖向的布局,相当于ListView
dragFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
swipeFlag = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
}
//第一个参数是拖拽flag,第二个是滑动的flag
return makeMovementFlags(dragFlag, swipeFlag);
}
return 0;
}
/**
* 当Item被拖拽的时候被回调
*
* @param recyclerView recyclerView
* @param srcViewHolder 当前被拖拽的item的viewHolder
* @param targetViewHolder 当前被拖拽的item下方的另一个item的viewHolder
* @return 是否被移动
*/
@Override
public boolean onMove(@NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder srcViewHolder,
@NonNull RecyclerView.ViewHolder targetViewHolder) {
if (onItemTouchCallbackListener != null) {
int srcPosition = srcViewHolder.getAdapterPosition();
int targetPosition = targetViewHolder.getAdapterPosition();
return onItemTouchCallbackListener.onMove(srcPosition, targetPosition);
}
return false;
}
/**
* 当item侧滑出去时触发(竖直列表是侧滑,水平列表是竖滑)
*
* @param viewHolder viewHolder
* @param direction 滑动的方向
*/
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
if (onItemTouchCallbackListener != null) {
onItemTouchCallbackListener.onSwiped(viewHolder.getAdapterPosition());
}
}
/**
* 当item被拖拽或侧滑时触发
*
* @param viewHolder viewHolder
* @param actionState 当前item的状态
*/
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
super.onSelectedChanged(viewHolder, actionState);
//不管是拖拽或是侧滑,背景色都要变化
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
if (color==0){
viewHolder.itemView.setBackgroundColor(viewHolder.itemView.getContext()
.getResources().getColor(android.R.color.darker_gray));
}else {
viewHolder.itemView.setBackgroundColor(color);
}
}
}
/**
* 当item的交互动画结束时触发
*
* @param recyclerView recyclerView
* @param viewHolder viewHolder
*/
@Override
public void clearView(@NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
viewHolder.itemView.setBackgroundColor(viewHolder.itemView.getContext().getResources()
.getColor(android.R.color.white));
viewHolder.itemView.setAlpha(1);
viewHolder.itemView.setScaleY(1);
}
@Override
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder viewHolder,
float dX, float dY, int actionState, boolean isCurrentlyActive) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
float value = 1 - Math.abs(dX) / viewHolder.itemView.getWidth();
viewHolder.itemView.setAlpha(value);
viewHolder.itemView.setScaleY(value);
}
}
public interface OnItemTouchCallbackListener {
/**
* 当某个Item被滑动删除的时候
*
* @param adapterPosition item的position
*/
void onSwiped(int adapterPosition);
/**
* 当两个Item位置互换的时候被回调
*
* @param srcPosition 拖拽的item的position
* @param targetPosition 目的地的Item的position
* @return 开发者处理了操作应该返回true,开发者没有处理就返回false
*/
boolean onMove(int srcPosition, int targetPosition);
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/utils/RecyclerUtils.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.utils;
import android.app.Application;
import android.content.Context;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/4/22
* desc : 工具类
* revise:
* </pre>
*/
public final class RecyclerUtils {
public static void checkContent(Context context){
if (context==null){
throw new NullPointerException("context is not null");
}
if (context instanceof Application){
throw new UnsupportedOperationException("context is not application");
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/utils/RefreshLogUtils.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.utils;
import android.util.Log;
/**
* <pre>
* @author yangchong
* blog : https://blog.csdn.net/m0_37700275/article/details/80863685
* time : 2017/4/22
* desc : 日志工具类
* revise: 支持多种状态切换;支持上拉加载更多,下拉刷新;支持添加头部或底部view
* </pre>
*/
public final class RefreshLogUtils {
private static final String TAG = "RefreshLogUtils";
private static boolean mIsLog = true;
public static void setLog(boolean isLog){
mIsLog = isLog;
}
public static void d(String message) {
if(mIsLog){
Log.d(TAG, message);
}
}
public static void i(String message) {
if(mIsLog){
Log.i(TAG, message);
}
}
public static void e(String message) {
if(mIsLog){
Log.e(TAG, message);
}
}
public static void e(String message, Throwable throwable) {
if(mIsLog){
Log.e(TAG, message, throwable);
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/view/DiffCallBack.java | Java | package org.yczbj.ycrefreshviewlib.view;
import androidx.recyclerview.widget.DiffUtil;
import java.util.List;
public class DiffCallBack<T> extends DiffUtil.Callback {
/**
* 分别是旧数据和新数据集合,这里使用泛型
*/
private List<T> oldList , newList;
public DiffCallBack(List<T> oldList , List<T> newList){
this.oldList = oldList;
this.newList = newList;
}
/**
* 获取旧数据的长度
* @return 长度
*/
@Override
public int getOldListSize() {
return oldList!=null ? oldList.size() : 0;
}
/**
* 获取新数据的长度
* @return 长度
*/
@Override
public int getNewListSize() {
return newList!=null ? newList.size() : 0;
}
/**
*
* @param i i
* @param i1 i
* @return
*/
@Override
public boolean areItemsTheSame(int i, int i1) {
return false;
}
/**
*
* @param i
* @param i1
* @return
*/
@Override
public boolean areContentsTheSame(int i, int i1) {
return false;
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/view/DiffItemCallBack.java | Java | package org.yczbj.ycrefreshviewlib.view;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
public class DiffItemCallBack<T> extends DiffUtil.ItemCallback<T> {
@Override
public boolean areItemsTheSame(@NonNull T t, @NonNull T t1) {
return false;
}
@Override
public boolean areContentsTheSame(@NonNull T t, @NonNull T t1) {
return false;
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/view/InnerRecycledViewPool.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.view;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.View;
import java.io.Closeable;
public final class InnerRecycledViewPool extends RecyclerView.RecycledViewPool {
private static final String TAG = "InnerRecycledViewPool";
private static final int DEFAULT_MAX_SIZE = 5;
/*
* Wrapped InnerPool
*/
private RecyclerView.RecycledViewPool mInnerPool;
private SparseIntArray mScrapLength = new SparseIntArray();
private SparseIntArray mMaxScrap = new SparseIntArray();
/**
* Wrap an existing pool
*
* @param pool
*/
public InnerRecycledViewPool(RecyclerView.RecycledViewPool pool) {
this.mInnerPool = pool;
}
public InnerRecycledViewPool() {
this(new RecyclerView.RecycledViewPool());
}
/**
* destroyViewHolder
*/
@Override
public void clear() {
for (int i = 0, size = mScrapLength.size(); i < size; i++) {
int viewType = mScrapLength.keyAt(i);
RecyclerView.ViewHolder holder = mInnerPool.getRecycledView(viewType);
while (holder != null) {
destroyViewHolder(holder);
holder = mInnerPool.getRecycledView(viewType);
}
}
mScrapLength.clear();
super.clear();
}
/**
* 设置丢弃前要在池中持有的视图持有人的最大数量
* @param viewType type
* @param max max数量
*/
@Override
public void setMaxRecycledViews(int viewType, int max) {
// When viewType is changed, because can not get items in wrapped pool,
// destroy all the items for the viewType
RecyclerView.ViewHolder holder = mInnerPool.getRecycledView(viewType);
while (holder != null) {
destroyViewHolder(holder);
holder = mInnerPool.getRecycledView(viewType);
}
// change maxRecycledViews
this.mMaxScrap.put(viewType, max);
this.mScrapLength.put(viewType, 0);
mInnerPool.setMaxRecycledViews(viewType, max);
}
/**
* 返回给定视图类型的RecycledViewPool所持有的当前视图数
* @param viewType type
* @return
*/
@Override
public int getRecycledViewCount(int viewType) {
return super.getRecycledViewCount(viewType);
}
/**
* 从池中获取指定类型的ViewHolder,如果没有指定类型的ViewHolder,则获取{@Codenull}
* @param viewType type
* @return
*/
@Override
public RecyclerView.ViewHolder getRecycledView(int viewType) {
RecyclerView.ViewHolder holder = mInnerPool.getRecycledView(viewType);
if (holder != null) {
int scrapHeapSize = mScrapLength.indexOfKey(viewType) >= 0 ? this.mScrapLength.get(viewType) : 0;
if (scrapHeapSize > 0)
mScrapLength.put(viewType, scrapHeapSize - 1);
}
return holder;
}
/**
* 获取当前池中的所有项大小
* @return size
*/
public int size() {
int count = 0;
for (int i = 0, size = mScrapLength.size(); i < size; i++) {
int val = mScrapLength.valueAt(i);
count += val;
}
return count;
}
/**
* 向池中添加一个废视图保存器。如果那个ViewHolder类型的池已经满了,它将立即被丢弃。
* @param scrap scrap
*/
@Override
@SuppressWarnings("unchecked")
public void putRecycledView(RecyclerView.ViewHolder scrap) {
int viewType = scrap.getItemViewType();
if (mMaxScrap.indexOfKey(viewType) < 0) {
// does't contains this viewType, initial scrap list
mMaxScrap.put(viewType, DEFAULT_MAX_SIZE);
setMaxRecycledViews(viewType, DEFAULT_MAX_SIZE);
}
// get current heap size
int scrapHeapSize = mScrapLength.indexOfKey(viewType) >= 0 ?
this.mScrapLength.get(viewType) : 0;
if (this.mMaxScrap.get(viewType) > scrapHeapSize) {
// if exceed current heap size
mInnerPool.putRecycledView(scrap);
mScrapLength.put(viewType, scrapHeapSize + 1);
} else {
// destroy viewHolder
destroyViewHolder(scrap);
}
}
private void destroyViewHolder(RecyclerView.ViewHolder holder) {
View view = holder.itemView;
// if view inherits {@link Closeable}, cal close method
if (view instanceof Closeable) {
try {
((Closeable) view).close();
} catch (Exception e) {
Log.w(TAG, Log.getStackTraceString(e), e);
}
}
if (holder instanceof Closeable) {
try {
((Closeable) holder).close();
} catch (Exception e) {
Log.w(TAG, Log.getStackTraceString(e), e);
}
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
RefreshViewLib/src/main/java/org/yczbj/ycrefreshviewlib/view/YCRefreshView.java | Java | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.yczbj.ycrefreshviewlib.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import androidx.annotation.ColorRes;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.yczbj.ycrefreshviewlib.R;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.observer.ViewDataObserver;
import org.yczbj.ycrefreshviewlib.utils.RefreshLogUtils;
import java.util.ArrayList;
/**
* <pre>
* @author yangchong
* blog : https://blog.csdn.net/m0_37700275/article/details/80863685
* time : 2017/4/22
* desc : 自定义控件
* revise: 支持多种状态切换;支持上拉加载更多,下拉刷新;支持添加头部或底部view
* </pre>
*/
public class YCRefreshView extends FrameLayout {
protected RecyclerView mRecyclerView;
protected ViewGroup mProgressView;
protected ViewGroup mEmptyView;
protected ViewGroup mErrorView;
private int mProgressId;
private int mEmptyId;
private int mErrorId;
protected boolean mClipToPadding;
protected int mPadding;
protected int mPaddingTop;
protected int mPaddingBottom;
protected int mPaddingLeft;
protected int mPaddingRight;
protected int mScrollbarStyle;
protected int mScrollbar;
protected RecyclerView.OnScrollListener mInternalOnScrollListener;
protected RecyclerView.OnScrollListener mExternalOnScrollListener;
protected ArrayList<RecyclerView.OnScrollListener> mExternalOnScrollListenerList = new ArrayList<>();
protected SwipeRefreshLayout mPtrLayout;
protected SwipeRefreshLayout.OnRefreshListener mRefreshListener;
public YCRefreshView(Context context) {
super(context);
initView();
}
public YCRefreshView(Context context, AttributeSet attrs) {
super(context, attrs);
initAttrs(attrs);
initView();
}
public YCRefreshView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initAttrs(attrs);
initView();
}
/**
* 事件的分发
* @param ev 事件
* @return 是否分发事件
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//交给父类去处理
return mPtrLayout.dispatchTouchEvent(ev);
}
/**
* 事件的触摸
* @param event event
* @return 是否自己处理触摸事件
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
//暂不处理
return super.onTouchEvent(event);
}
/**
* 拦截事件
* @param ev event
* @return 是否拦截事件
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//事件拦截,暂不处理
return super.onInterceptTouchEvent(ev);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
/**
* 当view销毁时会调用该方法
*/
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mRecyclerView!=null){
mRecyclerView.removeOnScrollListener(mInternalOnScrollListener);
}
}
/**
* 完成绘制会调用该方法
*/
@Override
protected void onFinishInflate() {
super.onFinishInflate();
//int childCount = getChildCount();
RecyclerView recyclerView = getRecyclerView();
if (recyclerView!=null){
initScrollListener();
//添加滚动监听事件
recyclerView.addOnScrollListener(mInternalOnScrollListener);
}
}
/**
* 初始化资源
* @param attrs attrs
*/
protected void initAttrs(AttributeSet attrs) {
//加载attr属性
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.YCRefreshView);
try {
mClipToPadding = a.getBoolean(R.styleable.YCRefreshView_recyclerClipToPadding, false);
mPadding = (int) a.getDimension(R.styleable.YCRefreshView_recyclerPadding, -1.0f);
mPaddingTop = (int) a.getDimension(R.styleable.YCRefreshView_recyclerPaddingTop, 0.0f);
mPaddingBottom = (int) a.getDimension(R.styleable.YCRefreshView_recyclerPaddingBottom, 0.0f);
mPaddingLeft = (int) a.getDimension(R.styleable.YCRefreshView_recyclerPaddingLeft, 0.0f);
mPaddingRight = (int) a.getDimension(R.styleable.YCRefreshView_recyclerPaddingRight, 0.0f);
mScrollbarStyle = a.getInteger(R.styleable.YCRefreshView_scrollbarStyle, -1);
mScrollbar = a.getInteger(R.styleable.YCRefreshView_scrollbars, -1);
mEmptyId = a.getResourceId(R.styleable.YCRefreshView_layout_empty, 0);
mProgressId = a.getResourceId(R.styleable.YCRefreshView_layout_progress, 0);
mErrorId = a.getResourceId(R.styleable.YCRefreshView_layout_error, 0);
} finally {
a.recycle();
}
}
/**
* 2017年3月29日
* 欢迎访问GitHub:https://github.com/yangchong211
* 初始化
*/
private void initView() {
//使用isInEditMode解决可视化编辑器无法识别自定义控件的问题
if (isInEditMode()) {
return;
}
//生成主View
View v = LayoutInflater.from(getContext()).inflate(R.layout.refresh_recyclerview, this);
mPtrLayout = v.findViewById(R.id.ptr_layout);
mPtrLayout.setEnabled(false);
//加载进度view
mProgressView = v.findViewById(R.id.progress);
if (mProgressId!=0){
LayoutInflater.from(getContext()).inflate(mProgressId,mProgressView);
}
//数据为空时view
mEmptyView = v.findViewById(R.id.empty);
if (mEmptyId!=0){
LayoutInflater.from(getContext()).inflate(mEmptyId,mEmptyView);
}
//数据加载错误view
mErrorView = v.findViewById(R.id.error);
if (mErrorId!=0){
LayoutInflater.from(getContext()).inflate(mErrorId,mErrorView);
}
//初始化
initRecyclerView(v);
}
protected void initRecyclerView(View view) {
mRecyclerView = view.findViewById(android.R.id.list);
setItemAnimator(null);
if (mRecyclerView != null) {
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setClipToPadding(mClipToPadding);
//设置recyclerView的padding值
if (mPadding != -1) {
mRecyclerView.setPadding(mPadding, mPadding, mPadding, mPadding);
} else {
mRecyclerView.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
if (mScrollbarStyle != -1) {
mRecyclerView.setScrollBarStyle(mScrollbarStyle);
}
//这个是滑动区分滑动方向
switch (mScrollbar){
case 0:
setVerticalScrollBarEnabled(false);
break;
case 1:
setHorizontalScrollBarEnabled(false);
break;
case 2:
setVerticalScrollBarEnabled(false);
setHorizontalScrollBarEnabled(false);
break;
default:
break;
}
}
}
/**
* 初始化滚动监听事件
*/
private void initScrollListener() {
mInternalOnScrollListener = new RecyclerView.OnScrollListener() {
/**
*
* @param recyclerView recyclerView
* @param dx x
* @param dy y
*/
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (mExternalOnScrollListener != null){
mExternalOnScrollListener.onScrolled(recyclerView, dx, dy);
}
for (RecyclerView.OnScrollListener listener : mExternalOnScrollListenerList) {
listener.onScrolled(recyclerView, dx, dy);
}
}
/**
*
* @param recyclerView recyclerView
* @param newState newState
*/
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (mExternalOnScrollListener != null){
mExternalOnScrollListener.onScrollStateChanged(recyclerView, newState);
}
for (RecyclerView.OnScrollListener listener : mExternalOnScrollListenerList) {
listener.onScrollStateChanged(recyclerView, newState);
}
}
};
}
/*--------------------------------------相关方法--------------------------------------------**/
/**
* 设置RecyclerView的LayoutManager
* @param manager LayoutManager
*/
public void setLayoutManager(RecyclerView.LayoutManager manager) {
if (manager!=null){
mRecyclerView.setLayoutManager(manager);
} else {
throw new NullPointerException("un find no manager , please set manager must be null");
}
}
/**
* 获取SwipeRefreshLayout对象
* @return SwipeRefreshLayout对象
*/
public SwipeRefreshLayout getSwipeToRefresh() {
return mPtrLayout;
}
/**
* 获取RecyclerView对象
* @return RecyclerView对象
*/
public RecyclerView getRecyclerView() {
//获取对象
return mRecyclerView;
}
/**
* 设置预加载itemView数目
* @param size size
*/
public void setCacheSize(@IntRange int size){
if (getRecyclerView()!=null){
getRecyclerView().setItemViewCacheSize(size);
}
}
/**
* 设置上下左右的边距
*/
public void setRecyclerPadding(int left,int top,int right,int bottom){
this.mPaddingLeft = left;
this.mPaddingTop = top;
this.mPaddingRight = right;
this.mPaddingBottom = bottom;
mRecyclerView.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
/**
* 是否将剪辑设置为填充
* @param isClip isClip
*/
@Override
public void setClipToPadding(boolean isClip){
if (getRecyclerView()!=null){
getRecyclerView().setClipToPadding(isClip);
}
}
/**
* 设置滚动到索引为position的位置
* @param position 位置
*/
public void scrollToPosition(int position){
if(getRecyclerView()!=null){
getRecyclerView().scrollToPosition(position);
}
}
@Override
public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
mRecyclerView.setVerticalScrollBarEnabled(verticalScrollBarEnabled);
}
@Override
public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
mRecyclerView.setHorizontalScrollBarEnabled(horizontalScrollBarEnabled);
}
/**
* 设置加载数据为空的状态
* @param emptyView 自定义布局
*/
public void setEmptyView(View emptyView){
mEmptyView.removeAllViews();
mEmptyView.addView(emptyView);
}
/**
* 设置加载数据为空的状态
* @param emptyView 自定义布局
*/
public void setEmptyView(int emptyView){
mEmptyView.removeAllViews();
LayoutInflater.from(getContext()).inflate(emptyView, mEmptyView);
}
/**
* 设置加载数据中
* @param progressView 自定义布局
*/
public void setProgressView(View progressView){
mProgressView.removeAllViews();
mProgressView.addView(progressView);
}
/**
* 设置加载数据中
* @param progressView 自定义布局
*/
public void setProgressView(int progressView){
mProgressView.removeAllViews();
LayoutInflater.from(getContext()).inflate(progressView, mProgressView);
}
/**
* 设置加载错误的状态
* @param errorView 自定义布局
*/
public void setErrorView(View errorView){
mErrorView.removeAllViews();
mErrorView.addView(errorView);
}
/**
* 设置加载错误的状态
* @param errorView 自定义布局
*/
public void setErrorView(int errorView){
mErrorView.removeAllViews();
LayoutInflater.from(getContext()).inflate(errorView, mErrorView);
}
/**
* 设置适配器,关闭所有副view。展示recyclerView
* 适配器有更新,自动关闭所有副view。根据条数判断是否展示EmptyView
* @param adapter Adapter适配器
*/
public void setAdapter(RecyclerView.Adapter adapter) {
mRecyclerView.setAdapter(adapter);
adapter.registerAdapterDataObserver(new ViewDataObserver(this));
showRecycler();
}
/**
* 设置适配器,关闭所有副view。展示进度条View
* 适配器有更新,自动关闭所有副view。根据条数判断是否展示EmptyView
* @param adapter Adapter适配器
*/
public void setAdapterWithProgress(RecyclerView.Adapter adapter) {
mRecyclerView.setAdapter(adapter);
adapter.registerAdapterDataObserver(new ViewDataObserver(this));
//只有Adapter为空时才显示ProgressView
if (adapter instanceof RecyclerArrayAdapter){
if (((RecyclerArrayAdapter) adapter).getCount() == 0){
showProgress();
}else {
showRecycler();
}
}else {
if (adapter.getItemCount() == 0){
showProgress();
}else {
showRecycler();
}
}
}
/**
* 从recycler清除adapter
*/
public void clear() {
mRecyclerView.setAdapter(null);
}
/**
* 展示有数据时的布局,隐藏其他布局
*/
private void hideAll(){
mEmptyView.setVisibility(View.GONE);
mProgressView.setVisibility(View.GONE);
mErrorView.setVisibility(GONE);
mPtrLayout.setRefreshing(false);
mRecyclerView.setVisibility(View.INVISIBLE);
}
/**
* 设置加载错误状态
*/
public void showError() {
RefreshLogUtils.e("showError");
if (mErrorView.getChildCount()>0){
hideAll();
mErrorView.setVisibility(View.VISIBLE);
}else {
showRecycler();
}
}
/**
* 设置加载数据为空状态
*/
public void showEmpty() {
RefreshLogUtils.e("showEmpty");
if (mEmptyView.getChildCount()>0){
hideAll();
mEmptyView.setVisibility(View.VISIBLE);
}else {
showRecycler();
}
}
/**
* 设置加载数据中状态
*/
public void showProgress() {
RefreshLogUtils.e("showProgress");
if (mProgressView.getChildCount()>0){
hideAll();
mProgressView.setVisibility(View.VISIBLE);
}else {
showRecycler();
}
}
/**
* 设置加载数据完毕状态
*/
public void showRecycler() {
RefreshLogUtils.e("showRecycler");
hideAll();
mRecyclerView.setVisibility(View.VISIBLE);
}
/**
* 设置下拉刷新监听
* @param listener OnRefreshListener监听
*/
public void setRefreshListener(SwipeRefreshLayout.OnRefreshListener listener) {
mPtrLayout.setEnabled(true);
mPtrLayout.setOnRefreshListener(listener);
this.mRefreshListener = listener;
}
/**
* 设置是否刷新
* @param isRefreshing 是否刷新
*/
public void setRefreshing(final boolean isRefreshing){
mPtrLayout.post(new Runnable() {
@Override
public void run() {
mPtrLayout.setRefreshing(isRefreshing);
}
});
}
/**
* 设置是否刷新
* @param isRefreshing 是否刷新
* @param isCallbackListener 是否回调监听
*/
public void setRefreshing(final boolean isRefreshing, final boolean isCallbackListener){
mPtrLayout.post(new Runnable() {
@Override
public void run() {
mPtrLayout.setRefreshing(isRefreshing);
if (isRefreshing && isCallbackListener && mRefreshListener!=null){
mRefreshListener.onRefresh();
}
}
});
}
/**
* 设置刷新颜色
* @param colRes int类型颜色值
*/
public void setRefreshingColorResources(@ColorRes int... colRes) {
mPtrLayout.setColorSchemeResources(colRes);
}
/**
* 设置刷新颜色
* @param col int类型颜色值
*/
public void setRefreshingColor(int... col) {
mPtrLayout.setColorSchemeColors(col);
}
/**
* 设置滚动监听
* @param listener OnScrollListener监听器
*/
@Deprecated
public void setOnScrollListener(RecyclerView.OnScrollListener listener) {
mExternalOnScrollListener = listener;
}
/**
* 添加滚动监听器
* @param listener OnScrollListener监听器
*/
public void addOnScrollListener(RecyclerView.OnScrollListener listener) {
mExternalOnScrollListenerList.add(listener);
}
/**
* 移除滚动监听器
* @param listener OnScrollListener监听器
*/
public void removeOnScrollListener(RecyclerView.OnScrollListener listener) {
mExternalOnScrollListenerList.remove(listener);
}
/**
* 移除所有的滚动监听
*/
public void removeAllOnScrollListeners() {
mExternalOnScrollListenerList.clear();
}
/**
* 添加条目触摸监听器
* @param listener OnItemTouchListener监听器
*/
public void addOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
mRecyclerView.addOnItemTouchListener(listener);
}
/**
* 移除条目触摸监听器
*/
public void removeOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
mRecyclerView.removeOnItemTouchListener(listener);
}
/**
* 获取RecyclerView的adapter适配器
* @return RecyclerView.Adapter对象
*/
public RecyclerView.Adapter getAdapter() {
return mRecyclerView.getAdapter();
}
@Override
@SuppressLint("ClickableViewAccessibility")
public void setOnTouchListener(OnTouchListener listener) {
mRecyclerView.setOnTouchListener(listener);
}
/**
* 设置条目动画效果
* @param animator ItemAnimator
*/
public void setItemAnimator(RecyclerView.ItemAnimator animator) {
mRecyclerView.setItemAnimator(animator);
}
/**
* 添加分割线
* @param itemDecoration 分割线
*/
public void addItemDecoration(RecyclerView.ItemDecoration itemDecoration) {
mRecyclerView.addItemDecoration(itemDecoration);
}
/**
* 在索引index出添加分割线
* @param itemDecoration 分割线
* @param index 索引
*/
public void addItemDecoration(RecyclerView.ItemDecoration itemDecoration, int index) {
mRecyclerView.addItemDecoration(itemDecoration, index);
}
/**
* 移除分割线
* @param itemDecoration 分割线
*/
public void removeItemDecoration(RecyclerView.ItemDecoration itemDecoration) {
mRecyclerView.removeItemDecoration(itemDecoration);
}
/**
* 获取error视图view
* @return view
*/
public View getErrorView() {
if (mErrorView.getChildCount()>0){
return mErrorView.getChildAt(0);
}
return null;
}
/**
* 获取Progress视图view
* @return view
*/
public View getProgressView() {
if (mProgressView.getChildCount()>0){
return mProgressView.getChildAt(0);
}
return null;
}
/**
* 获取Empty视图view
* @return view
*/
public View getEmptyView() {
if (mEmptyView.getChildCount()>0) {
return mEmptyView.getChildAt(0);
}
return null;
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SelectViewLib/build.gradle | Gradle | plugins {
id 'com.android.library'
}
apply from: rootProject.projectDir.absolutePath + "/AppGradle/app.gradle"
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion project.ext.androidCompileSdkVersion
//buildToolsVersion project.ext.androidBuildToolsVersion
defaultConfig {
minSdkVersion project.ext.androidMinSdkVersion
targetSdkVersion project.ext.androidTargetSdkVersion
versionCode 32
versionName "3.0.2"
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project.ext.AppDependencies['appcompat']
implementation project.ext.AppDependencies['annotation']
implementation project.ext.AppDependencies['recyclerview']
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SelectViewLib/src/androidTest/java/com/yc/selectviewlib/ExampleInstrumentedTest.java | Java | package com.yc.selectviewlib;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.yc.selectviewlib.test", appContext.getPackageName());
}
} | yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SelectViewLib/src/main/java/com/yc/selectviewlib/FingerListener.java | Java | package com.yc.selectviewlib;
public interface FingerListener {
void onDragSelectFingerAction(boolean var1);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SelectViewLib/src/main/java/com/yc/selectviewlib/SelectRecyclerView.java | Java | package com.yc.selectviewlib;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
public class SelectRecyclerView extends RecyclerView {
private static final boolean LOGGING = false;
private static final int AUTO_SCROLL_DELAY = 25;
private int lastDraggedIndex = -1;
private SelectRecyclerViewAdapter<?> adapter;
private int initialSelection;
private boolean dragSelectActive;
private int minReached;
private int maxReached;
private int hotspotHeight;
private int hotspotOffsetTop;
private int hotspotOffsetBottom;
private int hotspotTopBoundStart;
private int hotspotTopBoundEnd;
private int hotspotBottomBoundStart;
private int hotspotBottomBoundEnd;
private int autoScrollVelocity;
private boolean inTopHotspot;
private boolean inBottomHotspot;
private RectF topBoundRect;
private RectF bottomBoundRect;
private Paint debugPaint;
private boolean debugEnabled = false;
private FingerListener fingerListener;
private Handler autoScrollHandler;
private Runnable autoScrollRunnable;
public SelectRecyclerView(Context context) {
super(context);
this.autoScrollRunnable = new NamelessClass_1();
this.init(context, (AttributeSet)null);
}
public SelectRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
this.autoScrollRunnable = new NamelessClass_1();
this.init(context, attrs);
}
public SelectRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.autoScrollRunnable = new NamelessClass_1();
this.init(context, attrs);
}
class NamelessClass_1 implements Runnable {
NamelessClass_1() {
}
public void run() {
if (SelectRecyclerView.this.autoScrollHandler != null) {
if (SelectRecyclerView.this.inTopHotspot) {
SelectRecyclerView.this.scrollBy(0, -SelectRecyclerView.this.autoScrollVelocity);
SelectRecyclerView.this.autoScrollHandler.postDelayed(this, 25L);
} else if (SelectRecyclerView.this.inBottomHotspot) {
SelectRecyclerView.this.scrollBy(0, SelectRecyclerView.this.autoScrollVelocity);
SelectRecyclerView.this.autoScrollHandler.postDelayed(this, 25L);
}
}
}
}
private void init(Context context, AttributeSet attrs) {
this.autoScrollHandler = new Handler();
int defaultHotspotHeight = context.getResources().getDimensionPixelSize(R.dimen.spotHeight);
if (attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SelectRecyclerView, 0, 0);
try {
boolean autoScrollEnabled = a.getBoolean(R.styleable.SelectRecyclerView_scrollEnabled, true);
if (!autoScrollEnabled) {
this.hotspotHeight = -1;
this.hotspotOffsetTop = -1;
this.hotspotOffsetBottom = -1;
} else {
this.hotspotHeight = a.getDimensionPixelSize(R.styleable.SelectRecyclerView_spotHeight, defaultHotspotHeight);
this.hotspotOffsetTop = a.getDimensionPixelSize(R.styleable.SelectRecyclerView_spot_offsetTop, 0);
this.hotspotOffsetBottom = a.getDimensionPixelSize(R.styleable.SelectRecyclerView_spot_offsetBottom, 0);
}
} finally {
a.recycle();
}
} else {
this.hotspotHeight = defaultHotspotHeight;
}
}
public void setFingerListener(@Nullable FingerListener listener) {
this.fingerListener = listener;
}
protected void onMeasure(int widthSpec, int heightSpec) {
super.onMeasure(widthSpec, heightSpec);
if (this.hotspotHeight > -1) {
this.hotspotTopBoundStart = this.hotspotOffsetTop;
this.hotspotTopBoundEnd = this.hotspotOffsetTop + this.hotspotHeight;
this.hotspotBottomBoundStart = this.getMeasuredHeight() - this.hotspotHeight - this.hotspotOffsetBottom;
this.hotspotBottomBoundEnd = this.getMeasuredHeight() - this.hotspotOffsetBottom;
}
}
public boolean setDragSelectActive(boolean active, int initialSelection) {
if (active && this.dragSelectActive) {
return false;
} else {
this.lastDraggedIndex = -1;
this.minReached = -1;
this.maxReached = -1;
if (!this.adapter.isIndexSelectable(initialSelection)) {
this.dragSelectActive = false;
this.initialSelection = -1;
this.lastDraggedIndex = -1;
return false;
} else {
this.adapter.setSelected(initialSelection, true);
this.dragSelectActive = active;
this.initialSelection = initialSelection;
this.lastDraggedIndex = initialSelection;
if (this.fingerListener != null) {
this.fingerListener.onDragSelectFingerAction(true);
}
return true;
}
}
}
/** @deprecated */
@Deprecated
public void setAdapter(Adapter adapter) {
if (!(adapter instanceof SelectRecyclerViewAdapter)) {
throw new IllegalArgumentException("Adapter must be a DragSelectRecyclerViewAdapter.");
} else {
this.setAdapter((SelectRecyclerViewAdapter)adapter);
}
}
public void setAdapter(SelectRecyclerViewAdapter<?> adapter) {
super.setAdapter(adapter);
this.adapter = adapter;
}
private int getItemPosition(MotionEvent e) {
View v = this.findChildViewUnder(e.getX(), e.getY());
if (v == null) {
return -1;
} else if (v.getTag() != null && v.getTag() instanceof ViewHolder) {
ViewHolder holder = (ViewHolder)v.getTag();
return holder.getAdapterPosition();
} else {
throw new IllegalStateException("Make sure your adapter makes a call to super.onBindViewHolder(), and doesn't override itemView tags.");
}
}
public final void enableDebug() {
this.debugEnabled = true;
this.invalidate();
}
public void onDraw(Canvas c) {
super.onDraw(c);
if (this.debugEnabled) {
if (this.debugPaint == null) {
this.debugPaint = new Paint();
this.debugPaint.setColor(-16777216);
this.debugPaint.setAntiAlias(true);
this.debugPaint.setStyle(Style.FILL);
this.topBoundRect = new RectF(0.0F, (float)this.hotspotTopBoundStart, (float)this.getMeasuredWidth(), (float)this.hotspotTopBoundEnd);
this.bottomBoundRect = new RectF(0.0F, (float)this.hotspotBottomBoundStart, (float)this.getMeasuredWidth(), (float)this.hotspotBottomBoundEnd);
}
c.drawRect(this.topBoundRect, this.debugPaint);
c.drawRect(this.bottomBoundRect, this.debugPaint);
}
}
public boolean dispatchTouchEvent(MotionEvent e) {
if (this.adapter.getItemCount() == 0) {
return super.dispatchTouchEvent(e);
} else {
if (this.dragSelectActive) {
int itemPosition = this.getItemPosition(e);
if (e.getAction() == 1) {
this.dragSelectActive = false;
this.inTopHotspot = false;
this.inBottomHotspot = false;
this.autoScrollHandler.removeCallbacks(this.autoScrollRunnable);
if (this.fingerListener != null) {
this.fingerListener.onDragSelectFingerAction(false);
}
return true;
}
if (e.getAction() == 2) {
if (this.hotspotHeight > -1) {
float simulatedY;
float simulatedFactor;
if (e.getY() >= (float)this.hotspotTopBoundStart && e.getY() <= (float)this.hotspotTopBoundEnd) {
this.inBottomHotspot = false;
if (!this.inTopHotspot) {
this.inTopHotspot = true;
this.autoScrollHandler.removeCallbacks(this.autoScrollRunnable);
this.autoScrollHandler.postDelayed(this.autoScrollRunnable, 25L);
}
simulatedY = (float)(this.hotspotTopBoundEnd - this.hotspotTopBoundStart);
simulatedFactor = e.getY() - (float)this.hotspotTopBoundStart;
this.autoScrollVelocity = (int)(simulatedY - simulatedFactor) / 2;
} else if (e.getY() >= (float)this.hotspotBottomBoundStart && e.getY() <= (float)this.hotspotBottomBoundEnd) {
this.inTopHotspot = false;
if (!this.inBottomHotspot) {
this.inBottomHotspot = true;
this.autoScrollHandler.removeCallbacks(this.autoScrollRunnable);
this.autoScrollHandler.postDelayed(this.autoScrollRunnable, 25L);
}
simulatedY = e.getY() + (float)this.hotspotBottomBoundEnd;
simulatedFactor = (float)(this.hotspotBottomBoundStart + this.hotspotBottomBoundEnd);
this.autoScrollVelocity = (int)(simulatedY - simulatedFactor) / 2;
} else if (this.inTopHotspot || this.inBottomHotspot) {
this.autoScrollHandler.removeCallbacks(this.autoScrollRunnable);
this.inTopHotspot = false;
this.inBottomHotspot = false;
}
}
if (itemPosition != -1 && this.lastDraggedIndex != itemPosition) {
this.lastDraggedIndex = itemPosition;
if (this.minReached == -1) {
this.minReached = this.lastDraggedIndex;
}
if (this.maxReached == -1) {
this.maxReached = this.lastDraggedIndex;
}
if (this.lastDraggedIndex > this.maxReached) {
this.maxReached = this.lastDraggedIndex;
}
if (this.lastDraggedIndex < this.minReached) {
this.minReached = this.lastDraggedIndex;
}
if (this.adapter != null) {
this.adapter.selectRange(this.initialSelection, this.lastDraggedIndex, this.minReached, this.maxReached);
}
if (this.initialSelection == this.lastDraggedIndex) {
this.minReached = this.lastDraggedIndex;
this.maxReached = this.lastDraggedIndex;
}
}
return true;
}
}
return super.dispatchTouchEvent(e);
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SelectViewLib/src/main/java/com/yc/selectviewlib/SelectRecyclerViewAdapter.java | Java | package com.yc.selectviewlib;
import android.os.Bundle;
import androidx.annotation.CallSuper;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public abstract class SelectRecyclerViewAdapter<VH extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<VH> {
private ArrayList<Integer> selectedIndices = new ArrayList<>();
private SelectionListener selectionListener;
private int lastCount = -1;
private int maxSelectionCount = -1;
private void fireSelectionListener() {
if (this.lastCount != this.selectedIndices.size()) {
this.lastCount = this.selectedIndices.size();
if (this.selectionListener != null) {
this.selectionListener.onDragSelectionChanged(this.lastCount);
}
}
}
protected SelectRecyclerViewAdapter() {
}
@CallSuper
public void onBindViewHolder(VH holder, int position) {
holder.itemView.setTag(holder);
}
public void setMaxSelectionCount(int maxSelectionCount) {
this.maxSelectionCount = maxSelectionCount;
}
public void setSelectionListener(SelectionListener selectionListener) {
this.selectionListener = selectionListener;
}
public void saveInstanceState(Bundle out) {
this.saveInstanceState("selected_indices", out);
}
public void saveInstanceState(String key, Bundle out) {
out.putSerializable(key, this.selectedIndices);
}
public void restoreInstanceState(Bundle in) {
this.restoreInstanceState("selected_indices", in);
}
public void restoreInstanceState(String key, Bundle in) {
if (in != null && in.containsKey(key)) {
this.selectedIndices = (ArrayList)in.getSerializable(key);
if (this.selectedIndices == null) {
this.selectedIndices = new ArrayList();
} else {
this.fireSelectionListener();
}
}
}
public final void setSelected(int index, boolean selected) {
if (!this.isIndexSelectable(index)) {
selected = false;
}
if (selected) {
if (!this.selectedIndices.contains(index) && (this.maxSelectionCount == -1 || this.selectedIndices.size() < this.maxSelectionCount)) {
this.selectedIndices.add(index);
this.notifyItemChanged(index);
}
} else if (this.selectedIndices.contains(index)) {
this.selectedIndices.remove(index);
this.notifyItemChanged(index);
}
this.fireSelectionListener();
}
public final boolean toggleSelected(int index) {
boolean selectedNow = false;
if (this.isIndexSelectable(index)) {
if (this.selectedIndices.contains(index)) {
this.selectedIndices.remove(index);
} else if (this.maxSelectionCount == -1 || this.selectedIndices.size() < this.maxSelectionCount) {
this.selectedIndices.add(index);
selectedNow = true;
}
this.notifyItemChanged(index);
}
this.fireSelectionListener();
return selectedNow;
}
public final void selectRange(int from, int to, int min, int max) {
int i;
if (from == to) {
for(i = min; i <= max; ++i) {
if (i != from) {
this.setSelected(i, false);
}
}
this.fireSelectionListener();
} else {
if (to < from) {
for(i = to; i <= from; ++i) {
this.setSelected(i, true);
}
if (min > -1 && min < to) {
for(i = min; i < to; ++i) {
if (i != from) {
this.setSelected(i, false);
}
}
}
if (max > -1) {
for(i = from + 1; i <= max; ++i) {
this.setSelected(i, false);
}
}
} else {
for(i = from; i <= to; ++i) {
this.setSelected(i, true);
}
if (max > -1 && max > to) {
for(i = to + 1; i <= max; ++i) {
if (i != from) {
this.setSelected(i, false);
}
}
}
if (min > -1) {
for(i = min; i < from; ++i) {
this.setSelected(i, false);
}
}
}
this.fireSelectionListener();
}
}
protected boolean isIndexSelectable(int index) {
return true;
}
public final void selectAll() {
int max = this.getItemCount();
this.selectedIndices.clear();
for(int i = 0; i < max; ++i) {
if (this.isIndexSelectable(i)) {
this.selectedIndices.add(i);
}
}
this.notifyDataSetChanged();
this.fireSelectionListener();
}
public final void clearSelected() {
this.selectedIndices.clear();
this.notifyDataSetChanged();
this.fireSelectionListener();
}
public final int getSelectedCount() {
return this.selectedIndices.size();
}
public final Integer[] getSelectedIndices() {
return (Integer[])this.selectedIndices.toArray(new Integer[this.selectedIndices.size()]);
}
public final boolean isIndexSelected(int index) {
return this.selectedIndices.contains(index);
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SelectViewLib/src/main/java/com/yc/selectviewlib/SelectionListener.java | Java | package com.yc.selectviewlib;
public interface SelectionListener {
void onDragSelectionChanged(int var1);
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SelectViewLib/src/test/java/com/yc/selectviewlib/ExampleUnitTest.java | Java | package com.yc.selectviewlib;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
ShopCatLib/build.gradle | Gradle | apply plugin: 'com.android.library'
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
minSdkVersion 17
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
ShopCatLib/src/main/java/com/ycbjie/ycshopcatlib/VerticalListView.java | Java | package com.ycbjie.ycshopcatlib;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ExpandableListView;
/**
* <pre>
* @author yangchong
* blog :
* time : 2018/6/21.
* desc : 当ListView在最顶部或者最底部的时候,不消费事件
* revise:
* </pre>
*/
public class VerticalListView extends ExpandableListView {
private float downX;
private float downY;
public VerticalListView(Context context) {
this(context, null);
}
public VerticalListView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.listViewStyle);
}
public VerticalListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = ev.getX();
downY = ev.getY();
//如果滑动到了最底部,就允许继续向上滑动加载下一页,否者不允许
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
float dx = ev.getX() - downX;
float dy = ev.getY() - downY;
boolean allowParentTouchEvent;
if (Math.abs(dy) > Math.abs(dx)) {
//垂直方向滑动
if (dy > 0) {
//位于顶部时下拉,让父View消费事件
allowParentTouchEvent = isTop();
} else {
//位于底部时上拉,让父View消费事件
allowParentTouchEvent = isBottom();
}
} else {
//水平方向滑动
allowParentTouchEvent = true;
}
getParent().requestDisallowInterceptTouchEvent(!allowParentTouchEvent);
}
return super.dispatchTouchEvent(ev);
}
public boolean isTop() {
if (getChildCount() <= 0) return false;
final int firstTop = getChildAt(0).getTop();
return getFirstVisiblePosition() == 0 && firstTop >= getListPaddingTop();
}
public boolean isBottom() {
final int childCount = getChildCount();
if (childCount <= 0) return false;
final int itemsCount = getCount();
final int firstPosition = getFirstVisiblePosition();
final int lastPosition = firstPosition + childCount;
final int lastBottom = getChildAt(childCount - 1).getBottom();
return lastPosition >= itemsCount && lastBottom <= getHeight() - getListPaddingBottom();
}
public void goTop() {
setSelection(0);
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
ShopCatLib/src/main/java/com/ycbjie/ycshopcatlib/VerticalRecyclerView.java | Java | package com.ycbjie.ycshopcatlib;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
/**
* <pre>
* @author yangchong
* blog :
* time : 2018/6/21.
* desc : 当RecyclerView在最顶部或者最底部的时候,不消费事件
* revise:
* </pre>
*/
public class VerticalRecyclerView extends RecyclerView {
private float downX;
private float downY;
/** 第一个可见的item的位置 */
private int firstVisibleItemPosition;
/** 第一个的位置 */
private int[] firstPositions;
/** 最后一个可见的item的位置 */
private int lastVisibleItemPosition;
/** 最后一个的位置 */
private int[] lastPositions;
private boolean isTop;
private boolean isBottom;
public VerticalRecyclerView(Context context) {
this(context, null);
}
public VerticalRecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public VerticalRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
RecyclerView.LayoutManager layoutManager = getLayoutManager();
if (layoutManager != null) {
if (layoutManager instanceof GridLayoutManager) {
lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
firstVisibleItemPosition = ((GridLayoutManager) layoutManager).findFirstVisibleItemPosition();
} else if (layoutManager instanceof LinearLayoutManager) {
lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
firstVisibleItemPosition = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
if (lastPositions == null) {
lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];
firstPositions = new int[staggeredGridLayoutManager.getSpanCount()];
}
staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
staggeredGridLayoutManager.findFirstVisibleItemPositions(firstPositions);
lastVisibleItemPosition = findMax(lastPositions);
firstVisibleItemPosition = findMin(firstPositions);
}
} else {
throw new RuntimeException("Unsupported LayoutManager used. Valid ones are LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager");
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = ev.getX();
downY = ev.getY();
//如果滑动到了最底部,就允许继续向上滑动加载下一页,否者不允许
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
float dx = ev.getX() - downX;
float dy = ev.getY() - downY;
boolean allowParentTouchEvent;
if (Math.abs(dy) > Math.abs(dx)) {
if (dy > 0) {
//位于顶部时下拉,让父View消费事件
allowParentTouchEvent = isTop = firstVisibleItemPosition == 0 && getChildAt(0).getTop() >= 0;
} else {
//位于底部时上拉,让父View消费事件
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
allowParentTouchEvent = isBottom = visibleItemCount > 0 && (lastVisibleItemPosition) >= totalItemCount - 1 && getChildAt(getChildCount() - 1).getBottom() <= getHeight();
}
} else {
//水平方向滑动
allowParentTouchEvent = true;
}
getParent().requestDisallowInterceptTouchEvent(!allowParentTouchEvent);
}
return super.dispatchTouchEvent(ev);
}
private int findMax(int[] lastPositions) {
int max = lastPositions[0];
for (int value : lastPositions) {
if (value >= max) {
max = value;
}
}
return max;
}
private int findMin(int[] firstPositions) {
int min = firstPositions[0];
for (int value : firstPositions) {
if (value < min) {
min = value;
}
}
return min;
}
public boolean isTop() {
return isTop;
}
public boolean isBottom() {
return isBottom;
}
public void goTop() {
scrollToPosition(0);
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SlideViewLib/build.gradle | Gradle | apply plugin: 'com.android.library'
apply from: rootProject.projectDir.absolutePath + "/AppGradle/app.gradle"
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion project.ext.androidCompileSdkVersion
//buildToolsVersion project.ext.androidBuildToolsVersion
defaultConfig {
minSdkVersion project.ext.androidMinSdkVersion
targetSdkVersion project.ext.androidTargetSdkVersion
versionCode 32
versionName "3.0.2"
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project.ext.AppDependencies['appcompat']
implementation project.ext.AppDependencies['annotation']
implementation project.ext.AppDependencies['recyclerview']
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SlideViewLib/src/main/java/com/yc/slideview/Slide.java | Java | package com.yc.slideview;
/**
* ================================================
* 作 者:杨充
* 版 本:1.0
* 创建日期:2017/7/3
* 描 述:item侧滑 接口
* 修订历史:
* 项目地址:https://github.com/yangchong211/YCSlideView
* ================================================
*/
public interface Slide {
void slideOpen();
void slideClose();
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SlideViewLib/src/main/java/com/yc/slideview/SlideAnimationHelper.java | Java | package com.yc.slideview;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
/**
* ================================================
* 作 者:杨充
* 版 本:1.0
* 创建日期:2017/7/3
* 描 述:帮助类
* 修订历史:
* 项目地址:https://github.com/yangchong211/YCSlideView
* ================================================
*/
public class SlideAnimationHelper {
//关闭时的动画时间
static final int STATE_CLOSE = 20000;
//打开时的动画时间
static final int STATE_OPEN = 30000;
//关闭还是打开的状态
private static int mCurrentState = STATE_CLOSE;
private ValueAnimator mValueAnimator;
SlideAnimationHelper() {}
public int getState() {
return mCurrentState;
}
public ValueAnimator getAnimation() {
if (mValueAnimator == null) {
mValueAnimator = new ValueAnimator();
mValueAnimator.setFloatValues(0.0f, 1.0f);
}
return mValueAnimator;
}
public void openAnimation(long duration, AnimatorUpdateListener animatorUpdateListener,
Animator.AnimatorListener listener, float... values) {
mCurrentState = STATE_OPEN;
setValueAnimator(duration, animatorUpdateListener, listener, values);
}
public void closeAnimation(long duration, AnimatorUpdateListener animatorUpdateListener,
Animator.AnimatorListener listener, float... values) {
mCurrentState = STATE_CLOSE;
setValueAnimator(duration, animatorUpdateListener, listener, values);
}
public void openAnimation(long duration, AnimatorUpdateListener animatorUpdateListener,
float... values) {
mCurrentState = STATE_OPEN;
setValueAnimator(duration, animatorUpdateListener, null, values);
}
public void closeAnimation(long duration, AnimatorUpdateListener animatorUpdateListener,
float... values) {
mCurrentState = STATE_CLOSE;
setValueAnimator(duration, animatorUpdateListener, null, values);
}
public void openAnimation(long duration, AnimatorUpdateListener animatorUpdateListener,
Animator.AnimatorListener listener) {
mCurrentState = STATE_OPEN;
setValueAnimator(duration, animatorUpdateListener, listener);
}
public void closeAnimation(long duration, AnimatorUpdateListener animatorUpdateListener,
Animator.AnimatorListener listener) {
mCurrentState = STATE_CLOSE;
setValueAnimator(duration, animatorUpdateListener, listener);
}
public void openAnimation(long duration, AnimatorUpdateListener animatorUpdateListener) {
mCurrentState = STATE_OPEN;
setValueAnimator(duration, animatorUpdateListener, null);
}
public void closeAnimation(long duration, AnimatorUpdateListener animatorUpdateListener) {
mCurrentState = STATE_CLOSE;
setValueAnimator(duration, animatorUpdateListener, null);
}
private void setValueAnimator(long duration, AnimatorUpdateListener animatorUpdateListener,
Animator.AnimatorListener listener) {
mValueAnimator = getAnimation();
mValueAnimator.setDuration(duration);
if (animatorUpdateListener != null) {
mValueAnimator.addUpdateListener(animatorUpdateListener);
}
if (listener != null) {
mValueAnimator.addListener(listener);
}
start();
}
private void setValueAnimator(long duration, AnimatorUpdateListener animatorUpdateListener,
Animator.AnimatorListener listener, float... values) {
mValueAnimator = getAnimation();
mValueAnimator.setDuration(duration);
mValueAnimator.setFloatValues(values);
if (animatorUpdateListener != null) {
mValueAnimator.addUpdateListener(animatorUpdateListener);
}
if (listener != null) {
mValueAnimator.addListener(listener);
}
start();
}
private void start() {
if (mValueAnimator != null && !mValueAnimator.isRunning()) {
mValueAnimator.start();
}
}
static int getOffset(Context context, int offset) {
return (int) (context.getResources().getDisplayMetrics().density * offset + 0.5f);
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SlideViewLib/src/main/java/com/yc/slideview/SlideHelper.java | Java | package com.yc.slideview;
import java.util.ArrayList;
import java.util.List;
/**
* ================================================
* 作 者:杨充
* 版 本:1.0
* 创建日期:2017/7/3
* 描 述:帮助类
* 修订历史:
* 项目地址:https://github.com/yangchong211/YCSlideView
* ================================================
*/
public class SlideHelper {
private List<Slide> mISlides = new ArrayList<>();
public void add(Slide iSlide) {
mISlides.add(iSlide);
}
public void remove(Slide iSlide) {
mISlides.remove(iSlide);
}
public void clear() {
mISlides.clear();
}
public List<Slide> getISlideList() {
return mISlides;
}
public void slideOpen() {
for (Slide slide : mISlides) {
slide.slideOpen();
}
}
public void slideClose() {
for (Slide slide : mISlides) {
slide.slideClose();
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
SlideViewLib/src/main/java/com/yc/slideview/SlideViewHolder.java | Java | package com.yc.slideview;
import android.animation.ValueAnimator;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
/**
* ================================================
* 作 者:杨充
* 版 本:1.0
* 创建日期:2017/7/3
* 描 述:ViewHolder抽取类
* 修订历史:
* 项目地址:https://github.com/yangchong211/YCSlideView
* ================================================
*/
public abstract class SlideViewHolder extends RecyclerView.ViewHolder implements Slide {
private static final int DURATION_OPEN = 300;
private static final int DURATION_CLOSE = 150;
//默认正常偏移的量为50
private static final int NORMAL_OFFSET = 70;
private SlideAnimationHelper mSlideAnimationHelper;
private OpenUpdateListener mOpenUpdateListener;
private CloseUpdateListener mCloseUpdateListener;
private int mOffset;
public SlideViewHolder(View itemView) {
super(itemView);
mOffset = SlideAnimationHelper.getOffset(itemView.getContext(), NORMAL_OFFSET);
mSlideAnimationHelper = new SlideAnimationHelper();
}
protected void setOffset(int offset) {
mOffset = SlideAnimationHelper.getOffset(itemView.getContext(), offset);
}
public int getOffset() {
return mOffset;
}
//keep change state
public void onBindSlide(View targetView) {
switch (mSlideAnimationHelper.getState()) {
case SlideAnimationHelper.STATE_CLOSE:
targetView.scrollTo(0, 0);
onBindSlideClose(SlideAnimationHelper.STATE_CLOSE);
break;
case SlideAnimationHelper.STATE_OPEN:
targetView.scrollTo(-mOffset, 0);
doAnimationSetOpen(SlideAnimationHelper.STATE_OPEN);
break;
}
}
/**
* 关闭时调用的方法
*/
@Override
public void slideOpen() {
if (mOpenUpdateListener == null) {
mOpenUpdateListener = new OpenUpdateListener();
}
mSlideAnimationHelper.openAnimation(DURATION_OPEN, mOpenUpdateListener);
}
/**
* 打开时调用的方法
*/
@Override
public void slideClose() {
if (mCloseUpdateListener == null) {
mCloseUpdateListener = new CloseUpdateListener();
}
mSlideAnimationHelper.closeAnimation(DURATION_CLOSE, mCloseUpdateListener);
}
//以下几个方法子类必须继承
public abstract void doAnimationSet(int offset, float fraction);
public abstract void onBindSlideClose(int state);
public abstract void doAnimationSetOpen(int state);
private class OpenUpdateListener implements ValueAnimator.AnimatorUpdateListener {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float fraction = animation.getAnimatedFraction();
int endX = (int) (-mOffset * fraction);
doAnimationSet(endX, fraction);
}
}
private class CloseUpdateListener implements ValueAnimator.AnimatorUpdateListener {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float fraction = animation.getAnimatedFraction();
fraction = 1.0f - fraction;
int endX = (int) (-mOffset * fraction);
doAnimationSet(endX, fraction);
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
app/build.gradle | Gradle | apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
applicationId "org.yczbj.ycrefreshview"
minSdkVersion 17
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'jp.wasabeef:glide-transformations:1.3.1'
implementation 'cn.yc:YCBannerLib:1.4.0'
//recyclerView封装库
implementation 'com.github.yangchong211.YCRefreshView:RefreshViewLib:3.0.2'
//整体item侧滑库
implementation 'com.github.yangchong211.YCRefreshView:SlideViewLib:3.0.2'
//仿汽车之家画廊库
implementation 'com.github.yangchong211.YCRefreshView:PhotoCoverLib:3.0.2'
//标签多选单选库
implementation 'com.github.yangchong211.YCRefreshView:SelectViewLib:3.0.2'
//之前简单型adapter
implementation 'com.github.yangchong211.YCRefreshView:EastAdapterLib:3.0.2'
// implementation project(path: ':RefreshViewLib')
// implementation project(path: ':SlideViewLib')
// implementation project(path: ':PhotoCoverLib')
// implementation project(path: ':SelectViewLib')
implementation 'com.github.yangchong211:YCGroupAdapter:1.0.6'
//glide
implementation 'cn.yc:zoomImageLib:1.0.1'
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/org/yczbj/ycrefreshview/MainActivity.java | Java | package org.yczbj.ycrefreshview;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import org.yczbj.ycrefreshview.collapsing.EightCollapsingActivity;
import org.yczbj.ycrefreshview.cover.CoverActivity;
import org.yczbj.ycrefreshview.load.LoadMoreActivity;
import org.yczbj.ycrefreshview.load.LoadMoreActivity2;
import org.yczbj.ycrefreshview.normal.NormalRecyclerViewActivity;
import org.yczbj.ycrefreshview.normal.SpanRecyclerViewActivity;
import org.yczbj.ycrefreshview.refresh.RefreshAndMoreActivity1;
import org.yczbj.ycrefreshview.refresh.RefreshAndMoreActivity2;
import org.yczbj.ycrefreshview.multistyle.FiveMultiStyleActivity;
import org.yczbj.ycrefreshview.horizontal.FourHorizontalActivity;
import org.yczbj.ycrefreshview.refresh.RefreshAndMoreActivity3;
import org.yczbj.ycrefreshview.scroll.ScrollActivity;
import org.yczbj.ycrefreshview.select.SelectFollowActivity;
import org.yczbj.ycrefreshview.slide.SlideViewActivity;
import org.yczbj.ycrefreshview.staggered.SevenStaggeredActivity;
import org.yczbj.ycrefreshview.staggered.StageredLoadMoreActivity;
import org.yczbj.ycrefreshview.sticky.SixStickyNormalActivity;
import org.yczbj.ycrefreshview.sticky.SixStickyViewActivity;
import org.yczbj.ycrefreshview.tag.TagRecyclerViewActivity;
import org.yczbj.ycrefreshview.touchmove.NightTouchMoveActivity;
import org.yczbj.ycrefreshview.header.HeaderFooterActivity;
import org.yczbj.ycrefreshview.staggered.SevenStaggeredGridActivity;
import org.yczbj.ycrefreshview.sticky.SixStickyHeaderActivity;
import org.yczbj.ycrefreshview.delete.DeleteAndTopActivity;
import org.yczbj.ycrefreshview.insert.ThirdInsertActivity;
import org.yczbj.ycrefreshview.touchmove.NightTouchMoveActivity2;
import org.yczbj.ycrefreshview.type.TypeActivity;
import org.yczbj.ycrefreshviewlib.utils.RefreshLogUtils;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RefreshLogUtils.setLog(true);
init();
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
private void init() {
findViewById(R.id.tv_1_1).setOnClickListener(this);
findViewById(R.id.tv_1_2).setOnClickListener(this);
findViewById(R.id.tv_1_3).setOnClickListener(this);
findViewById(R.id.tv_2).setOnClickListener(this);
findViewById(R.id.tv_3).setOnClickListener(this);
findViewById(R.id.tv_4).setOnClickListener(this);
findViewById(R.id.tv_5_1).setOnClickListener(this);
findViewById(R.id.tv_6_1).setOnClickListener(this);
findViewById(R.id.tv_6_2).setOnClickListener(this);
findViewById(R.id.tv_6_3).setOnClickListener(this);
findViewById(R.id.tv_7).setOnClickListener(this);
findViewById(R.id.tv_7_2).setOnClickListener(this);
findViewById(R.id.tv_7_3).setOnClickListener(this);
findViewById(R.id.tv_8).setOnClickListener(this);
findViewById(R.id.tv_9).setOnClickListener(this);
findViewById(R.id.tv_9_2).setOnClickListener(this);
findViewById(R.id.tv_10).setOnClickListener(this);
findViewById(R.id.tv_11).setOnClickListener(this);
findViewById(R.id.tv_11_2).setOnClickListener(this);
findViewById(R.id.tv_12).setOnClickListener(this);
findViewById(R.id.tv_13_1).setOnClickListener(this);
findViewById(R.id.tv_13_2).setOnClickListener(this);
findViewById(R.id.tv_14).setOnClickListener(this);
findViewById(R.id.tv_15).setOnClickListener(this);
findViewById(R.id.tv_16).setOnClickListener(this);
findViewById(R.id.tv_17).setOnClickListener(this);
findViewById(R.id.tv_18).setOnClickListener(this);
findViewById(R.id.tv_19).setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.tv_1_1:
startActivity(new Intent(this, RefreshAndMoreActivity1.class));
break;
case R.id.tv_1_2:
startActivity(new Intent(this, RefreshAndMoreActivity2.class));
break;
case R.id.tv_1_3:
startActivity(new Intent(this, RefreshAndMoreActivity3.class));
break;
case R.id.tv_2:
startActivity(new Intent(this, HeaderFooterActivity.class));
break;
case R.id.tv_3:
startActivity(new Intent(this, ThirdInsertActivity.class));
break;
case R.id.tv_4:
startActivity(new Intent(this, FourHorizontalActivity.class));
break;
case R.id.tv_5_1:
startActivity(new Intent(this, FiveMultiStyleActivity.class));
break;
case R.id.tv_6_1:
startActivity(new Intent(this, SixStickyHeaderActivity.class));
break;
case R.id.tv_6_2:
startActivity(new Intent(this, SixStickyViewActivity.class));
break;
case R.id.tv_6_3:
startActivity(new Intent(this, SixStickyNormalActivity.class));
break;
case R.id.tv_7:
startActivity(new Intent(this, SevenStaggeredGridActivity.class));
break;
case R.id.tv_7_2:
startActivity(new Intent(this, SevenStaggeredActivity.class));
break;
case R.id.tv_7_3:
startActivity(new Intent(this, StageredLoadMoreActivity.class));
break;
case R.id.tv_8:
startActivity(new Intent(this, EightCollapsingActivity.class));
break;
case R.id.tv_9:
startActivity(new Intent(this, NightTouchMoveActivity.class));
break;
case R.id.tv_9_2:
startActivity(new Intent(this, NightTouchMoveActivity2.class));
break;
case R.id.tv_10:
startActivity(new Intent(this, DeleteAndTopActivity.class));
break;
case R.id.tv_11:
startActivity(new Intent(this, NormalRecyclerViewActivity.class));
break;
case R.id.tv_11_2:
startActivity(new Intent(this, SpanRecyclerViewActivity.class));
break;
case R.id.tv_12:
startActivity(new Intent(this, TypeActivity.class));
break;
case R.id.tv_13_1:
startActivity(new Intent(this, LoadMoreActivity.class));
break;
case R.id.tv_13_2:
startActivity(new Intent(this, LoadMoreActivity2.class));
break;
case R.id.tv_14:
startActivity(new Intent(this, SlideViewActivity.class));
break;
case R.id.tv_15:
break;
case R.id.tv_16:
startActivity(new Intent(this, TagRecyclerViewActivity.class));
break;
case R.id.tv_17:
startActivity(new Intent(this, ScrollActivity.class));
break;
case R.id.tv_18:
startActivity(new Intent(this, CoverActivity.class));
break;
case R.id.tv_19:
startActivity(new Intent(this, SelectFollowActivity.class));
break;
default:
break;
}
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
app/src/main/java/org/yczbj/ycrefreshview/app/BaseApp.java | Java | package org.yczbj.ycrefreshview.app;
import android.app.Application;
import com.bumptech.glide.request.target.ViewTarget;
import org.yczbj.ycrefreshview.R;
public class BaseApp extends Application {
private static Application application;
public static Application getApp(){
if (application==null){
synchronized(BaseApp.class){
if (application==null){
application = new Application();
}
}
}
return application;
}
@Override
public void onCreate() {
super.onCreate();
application = this;
ViewTarget.setTagId(R.id.glide_tag);
}
}
| yangchong211/YCRefreshView | 455 | 自定义支持上拉加载更多,下拉刷新,可以自定义头部和底部,可以添加多个headerView,使用一个原生recyclerView就可以搞定复杂界面。支持自由切换状态【加载中,加载成功,加载失败,没网络等状态】的控件,可以自定义状态视图View。拓展功能【支持长按拖拽,侧滑删除】,轻量级,可以选择性添加 。持续更新…… | Java | yangchong211 | 杨充 | Tencent |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.