blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 131 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 32 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
046192b41965e46746c0599520a8d63cd3aae79f | 63f751519e64ac067e11189edaf6a34aeb3e5dba | /4.JavaCollections/src/com/javarush/task/task32/task3210/Solution.java | 51b67615420ac202b4832fb7ba8535e1833bd7f7 | [] | no_license | sharygin-vic/JavaRushTasks | 8507b96c2103828be4c8c3de29f6ad446b33b9df | 88e383a10a64286a2750bd67ec7f27d1a10a21dd | refs/heads/master | 2021-01-21T18:25:20.400669 | 2017-08-01T22:50:45 | 2017-08-01T22:50:45 | 92,046,759 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,122 | java | package com.javarush.task.task32.task3210;
import java.io.IOException;
import java.io.RandomAccessFile;
/*
Используем RandomAccessFile
*/
public class Solution {
public static void main(String... args) throws IOException {
String fileName = args[0];
long number = Long.parseLong(args[1]);
String text = args[2];
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
byte[] textBytes = text.getBytes();
long fileLength = raf.length();
byte[] bytesFromFile = new byte[textBytes.length];
raf.seek(number);
raf.read(bytesFromFile, 0, textBytes.length);
String fromFile = convertByteToString(bytesFromFile);
raf.seek(fileLength);
if (text.equals(fromFile)) {
raf.write("true".getBytes());
}
else {
raf.write("false".getBytes());
}
raf.close();
}
private static String convertByteToString(byte[] readBytes) {
String s = new String(readBytes);
String[] substrings = s.split("\r?\n");
return substrings[0];
}
}
| [
"lasprog@mail.ru"
] | lasprog@mail.ru |
bf610f4d879caf99489abe87962b28b32f8bd6e4 | f3beb239c1c70aaa0e458c0499161a05306cb1dc | /src/main/java/wisdom21/config/MybatisPlusConfig.java | 92fcae958e0578edb2811b5857df076534ed17bb | [] | no_license | wisdom-21/book-druid-mybatis_plus | ecc1d76b6f84bdc9a1cf02250a9b0d64a1832e63 | bf0a686188d13bd0ff084d2822a4f92c94e92983 | refs/heads/master | 2022-06-30T08:12:48.844056 | 2019-08-16T09:11:50 | 2019-08-16T09:11:50 | 202,696,715 | 1 | 0 | null | 2022-06-21T01:40:55 | 2019-08-16T09:11:37 | Java | UTF-8 | Java | false | false | 4,556 | java | package wisdom21.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* mybatis-plus配置
*/
@Configuration
@EnableTransactionManagement
@MapperScan("wisdom21.model.**.mapper.db*")
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setOverflow(true);
//paginationInterceptor.setLocalPage(true);
return paginationInterceptor;
}
@Bean(name = "db1")
@ConfigurationProperties(prefix = "spring.datasource.druid.db1")
public DataSource db1() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "db2")
@ConfigurationProperties(prefix = "spring.datasource.druid.db2")
public DataSource db2() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "db3")
@ConfigurationProperties(prefix = "spring.datasource.druid.db3")
public DataSource db3() {
return DruidDataSourceBuilder.create().build();
}
/**
* 动态数据源配置
*
* @return
*/
@Bean
@Primary
public DataSource multipleDataSource(@Qualifier("db1") DataSource db1,
@Qualifier("db2") DataSource db2,
@Qualifier("db3") DataSource db3) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DBTypeEnum.db1.getValue(), db1);
targetDataSources.put(DBTypeEnum.db2.getValue(), db2);
targetDataSources.put(DBTypeEnum.db3.getValue(), db3);
dynamicDataSource.setTargetDataSources(targetDataSources);
dynamicDataSource.setDefaultTargetDataSource(db2);
return dynamicDataSource;
}
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(multipleDataSource(db1(), db2(), db3()));
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
sqlSessionFactory.setConfiguration(configuration);
//PerformanceInterceptor(),OptimisticLockerInterceptor()
//添加分页功能
/*sqlSessionFactory.setPlugins(new Interceptor[]{
paginationInterceptor()
});*/
//sqlSessionFactory.setGlobalConfig(globalConfiguration());
return sqlSessionFactory.getObject();
}
/* @Bean
public GlobalConfiguration globalConfiguration() {
GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
conf.setLogicDeleteValue("-1");
conf.setLogicNotDeleteValue("1");
conf.setIdType(0);
conf.setMetaObjectHandler(new MyMetaObjectHandler());
conf.setDbColumnUnderline(true);
conf.setRefresh(true);
return conf;
}*/
/**
* 分页插件
*/
/*@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}*/
/**
* sql注入器 逻辑删除插件
*
* @return
*/
@Bean
public ISqlInjector iSqlInjector() {
return new LogicSqlInjector();
}
}
| [
"wisdom_lhz@163.com"
] | wisdom_lhz@163.com |
a9bcf81d178561275edbf66a874505043c538c51 | f542657e872449f88c43ede62b80a83698e240fa | /app/src/androidTest/java/com/walmart/orderstreamerapplication/ApplicationTest.java | ef16879d8ba7b99748a4ed842d6f18e1b3621d9d | [] | no_license | nirusr/OrderStreamerApplication | 3f943f1ab854343e19ffc190fb938b1ae1a63308 | 798d66520a9f12bc4f2a80dbe7d016b72d42f7bc | refs/heads/master | 2021-01-10T05:43:28.987210 | 2015-11-13T20:10:58 | 2015-11-13T20:10:58 | 46,144,692 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 367 | java | package com.walmart.orderstreamerapplication;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"sgovindaraji@walmartlabs.com"
] | sgovindaraji@walmartlabs.com |
02c674ee1ade38664f2c70bd26089f7a05e5879d | a31d2c8e1c8f5562f468d493efe851cb4a1c4e5b | /J_0828_4.java | d766d47f6632691c7b9e63aa4481d68bd41c0ed0 | [] | no_license | kk50576/JAVA_EXERCISE | de49e61b614b8d83b0fb5b71a45aa23d79d5bffa | a4b8dee06024c210dcdf9d3e3ad84402c57814a1 | refs/heads/master | 2020-05-29T09:14:54.721948 | 2016-10-06T06:06:37 | 2016-10-06T06:06:37 | 70,126,219 | 0 | 0 | null | null | null | null | BIG5 | Java | false | false | 921 | java | package tw.org.iii_2;
public class J_0828_4 {
public static void main(String[] args) {
final int d;//區域變數
d=12;//不能第二次給值
System.out.println(Brad376.a);
}
}
interface Brad371{void m1();}
interface Brad372{void m2();}//都是public的
class Brad373 implements Brad371,Brad372{
public void m1(){}
public void m2(){}
}
interface Brad374 extends Brad371{//介面可以(只能)繼成介面
void m3();//因為介面沒有做初始化 故A要先給值
}
interface Brad375 extends Brad371,Brad372{//可以繼成多個介面
int a=10;//必須給值 public final
void m3();//public
}
class Brad376 implements Brad375{//需實作以下三個
int b;
final int c;//FINAL只能給值一次 屬性!!
Brad376(){c=12;}//建構式
@Override
public void m1() {
b++;
// a=1;//final
}
@Override
public void m2() {
}
@Override
public void m3() {
}
} | [
"noreply@github.com"
] | kk50576.noreply@github.com |
58758fc9e69c62c7d8691011b71429d95e531a9f | dc0e271669780a11284b9626919846a51b00d54c | /service/com/hys/exam/service/local/impl/BannerManageImpl.java | 6e41924712466cdea3dc96c25a8d480a04abfd20 | [
"Apache-2.0"
] | permissive | 1224500506/NCME-Admin | 4a4b8e62f85b352dee0a96f096748b04fbf1b67e | e4f0969938ed6d9c076a9d647681dd56a1bf2679 | refs/heads/master | 2021-04-24T19:28:33.899711 | 2018-01-15T01:54:21 | 2018-01-15T01:54:21 | 117,482,274 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,524 | java | package com.hys.exam.service.local.impl;
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import com.hys.exam.dao.local.BannerManageDAO;
import com.hys.exam.model.Advert;
import com.hys.exam.model.SystemSite;
import com.hys.exam.model.SystemUser;
import com.hys.exam.service.local.BannerManage;
import com.hys.exam.utils.PageList;
import com.hys.framework.service.impl.BaseMangerImpl;
public class BannerManageImpl extends BaseMangerImpl implements BannerManage {
private BannerManageDAO localBannerManageDAO;
@Override
public Advert getAdvertById(Long id) {
return localBannerManageDAO.getAdvertById(id);
}
@Override
public List<Advert> getAdvertList(Advert advert) {
return localBannerManageDAO.getAdvertList(advert);
}
@Override
public boolean addAdvert(Advert advert) {
if(localBannerManageDAO.addAdvert(advert))
return true;
else
return false;
}
@Override
public boolean updateState(Long id, int state) {
return localBannerManageDAO.updateState(id, state);
}
@Override
public boolean deleteAdvertById(Long id) {
return localBannerManageDAO.deleteAdvertById(id);
}
@Override
public boolean updateAdvert(Advert advert) {
localBannerManageDAO.updateAdvert(advert);
return true;
}
@Override
public void getAdvertPageList(PageList pl, Advert advert) {
//模糊查询banner
localBannerManageDAO.getAdvertPageList(pl, advert);
//设置banner对于的站点信息
List<Advert> list=pl.getList();
for(Advert adv:list){
adv.setSiteList(getSiteListByBannerId(adv.getId()));
}
}
@Override
public int getAdvertByName(String name) {
return localBannerManageDAO.getAdvertByName(name);
}
@Override
public List<SystemSite> getSiteListByBannerId(long id) {
return localBannerManageDAO.getSiteListByBannerId(id);
}
public void setLocalBannerManageDAO(BannerManageDAO localBannerManageDAO) {
this.localBannerManageDAO = localBannerManageDAO;
}
public BannerManageDAO getLocalBannerManageDAO() {
return localBannerManageDAO;
}
//排序操作
@Override
public boolean resortOrderNum(String orderstr) {
boolean flag = false;
try{
flag = localBannerManageDAO.resortOrderNum(orderstr);
}
catch(Exception e){
flag = false;
}
return flag;
}
@Override
public void updateImageById(Long id, String url) {
localBannerManageDAO.updateImageById(id,url);
}
@Override
public int getAdvertByState(Integer state,Integer type) {
return localBannerManageDAO.getAdvertByState(state,type);
}
}
| [
"weeho@DESKTOP-71D9DPN"
] | weeho@DESKTOP-71D9DPN |
a21cb734c6bfa58685b03c58abba3f043535e68f | bc47b3ddbded90c437901ccdae391409f1c822bb | /src/main/java/top_k_elements/_973_M_K_Closest_Points_to_Origin.java | 10ea1056a0893d3a5c6ae8fc5d4e495db1a8e3e9 | [] | no_license | softtwilight/leetcode | abdd4de64ee8b76fb607eacbfd67c0d1d58a9ff3 | 6b17167f102fe5e00275bd3307750cf11b525628 | refs/heads/master | 2023-01-28T08:19:17.706492 | 2023-01-12T13:08:06 | 2023-01-12T13:08:06 | 157,892,232 | 2 | 0 | null | 2023-01-12T08:31:51 | 2018-11-16T16:18:07 | Java | UTF-8 | Java | false | false | 1,841 | java | package top_k_elements;
import javax.swing.*;
import java.util.Arrays;
import java.util.Random;
/**
* https://leetcode.com/problems/k-closest-points-to-origin/
*
* Author: softtwilight
* Date: 2020/07/07 21:53
*/
public class _973_M_K_Closest_Points_to_Origin {
private static final _973_M_K_Closest_Points_to_Origin instance = new _973_M_K_Closest_Points_to_Origin();
public static void main(String[] args) {
System.out.println(instance);
}
/**
* 6 ms 115.7 MB
* 标准的top k解法
*/
public int[][] kClosest(int[][] points, int K) {
halfSort(points, 0, points.length - 1, K);
return Arrays.copyOfRange(points, 0, K);
}
private void halfSort(int[][] points, int lo, int hi, int k) {
if (lo >= hi) return;
Random ra = new Random();
int pivotIndex = lo + ra.nextInt(hi - lo + 1);
int pi = partition(points, lo, hi, k, pivotIndex);
if (pi == k) return;
if (pi > k) {
halfSort(points, lo, pi - 1, k);
} else {
halfSort(points, pi + 1, hi, k);
}
}
private int partition(int[][] points, int lo, int hi, int k, int pivotIndex) {
int storeIndex = lo;
swap(points, hi, pivotIndex);
int square = getSquare(points[hi]);
for (int i = lo; i < hi - 1; i++) {
if (getSquare(points[i]) < square) {
swap(points, i, storeIndex);
storeIndex++;
}
}
swap(points, hi, storeIndex);
return storeIndex;
}
private int getSquare(int[] point) {
return point[0] * point[0] + point[1] * point[1];
}
private void swap(int[][] points, int i, int j) {
int[] temp = points[i];
points[i] = points[j];
points[j] = temp;
}
}
| [
"tjuyxl@gmail.com"
] | tjuyxl@gmail.com |
289ec4df0082919b7ba4f64167a70b026e09fd8a | af659086d641b64c4615a2a5de217c328b7a542d | /src/com/hzfc/soar/zfbz/byfz/websupport/SfblByyf.java | 5f2a483c75a09fcada981d726c6089d43619fed8 | [] | no_license | kate2014/HousingService | 1c74da19e965a81c95783d224e7b66e00c00100d | 158094e249bdbcd67e719581befe252ee75e7150 | refs/heads/master | 2021-01-23T23:12:39.554876 | 2017-03-13T16:07:47 | 2017-03-14T01:03:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,977 | java |
package com.hzfc.soar.zfbz.byfz.websupport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for sfblByyf complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="sfblByyf">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fczh" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="fwzl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sfblByyf", propOrder = {
"fczh",
"fwzl"
})
public class SfblByyf {
protected String fczh;
protected String fwzl;
/**
* Gets the value of the fczh property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFczh() {
return fczh;
}
/**
* Sets the value of the fczh property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFczh(String value) {
this.fczh = value;
}
/**
* Gets the value of the fwzl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFwzl() {
return fwzl;
}
/**
* Sets the value of the fwzl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFwzl(String value) {
this.fwzl = value;
}
}
| [
"471066902@qq.com"
] | 471066902@qq.com |
444cb5af8d1dc5d60f2657697e6545f9eb8a9c26 | 9283600b76de836d8b22d7b0abb9fbe03b19bdc7 | /ass2/Guitar37.java | 5f862ed908fde40f2e1cef2e40154850e0e1f0c9 | [] | no_license | yjia757-2/guitar-string | e34516fb5f988f2d7f6934ae75fa42dac8956605 | 3c8df12be6068139a72f7ee6a795113fb9fd8dab | refs/heads/master | 2020-07-10T21:38:04.795978 | 2019-08-26T02:11:19 | 2019-08-26T02:11:19 | 204,377,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 189 | java | // skeleton version of the class
public class Guitar37 implements Guitar {
public static final String KEYBOARD =
"q2we4r5ty7u8i9op-[=zxdcfvgbnjmk,.;/' "; // keyboard layout
} | [
"yjia757@uw.edu"
] | yjia757@uw.edu |
a6a6c9a62923ee4b6a73794fcb2859ed41997200 | 822ab6b9ba3959a5647518070099ea37edcb9521 | /src/cn/zjyy/appsys/service/developer/DataDictionaryServiceImpl.java | 05da27e17d27eb24743af4dec9ec0422622f4a1b | [] | no_license | kaixin789/AppInfoSystem | 87503c58337fe308a7b055b193e07ce3f7ad96c1 | 2e4ffa5cac976ddb9e404691fea99a29412e0cc0 | refs/heads/master | 2020-03-27T00:12:02.051648 | 2018-08-22T09:54:52 | 2018-08-22T09:54:52 | 145,603,158 | 0 | 0 | null | 2018-08-22T09:54:53 | 2018-08-21T18:24:18 | Java | UTF-8 | Java | false | false | 611 | java | package cn.zjyy.appsys.service.developer;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.zjyy.appsys.dao.datadictionary.DataDictionaryMapper;
import cn.zjyy.appsys.pojo.DataDictionary;
@Service
public class DataDictionaryServiceImpl implements DataDictionaryService {
@Resource
private DataDictionaryMapper mapper;
@Override
public List<DataDictionary> getDataDictionaryList(String typeCode)
throws Exception {
// TODO Auto-generated method stub
return mapper.getDataDictionaryList(typeCode);
}
}
| [
"kaixin.lu@UN3AZDXA87DWDSM"
] | kaixin.lu@UN3AZDXA87DWDSM |
0ab74e09ebeef61493cb453e1c56ac507670c8f5 | 611043591ef5ccfedcf7e235358d6e8eb7198e29 | /DesafioStone/app/src/main/java/kelly/com/desafiostone/data/TransactionDataBaseHelper.java | 63eb46a9538d8ad63f6817770b4488523d3f4b50 | [
"MIT"
] | permissive | KellyMBentes/desafio-mobile | 91e8338230a8196fe959e4910d84b184bf79c004 | c5d11c0590465ebd61f69990c7f46d361d6926e4 | refs/heads/master | 2021-08-22T13:47:33.187416 | 2017-11-30T10:30:41 | 2017-11-30T10:30:41 | 112,504,404 | 0 | 0 | null | 2017-11-29T17:10:49 | 2017-11-29T17:10:48 | null | UTF-8 | Java | false | false | 1,675 | java | package kelly.com.desafiostone.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by kelly on 30/11/17.
*/
public class TransactionDataBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "itemTransaction.db";
private static final int DATABASE_VERSION = 1;
public TransactionDataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_TRANSACTION_TABLE = "CREATE TABLE " + TransactionContract.TransactionEntry.TABLE_NAME + "("
+ TransactionContract.TransactionEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TransactionContract.TransactionEntry.COLUMN_TRANSACTION_HOLDER_NAME + " TEXT NOT NULL, "
+ TransactionContract.TransactionEntry.COLUMN_TRANSACTION_LAST_CARD_NUMBERS + " TEXT NOT NULL, "
+ TransactionContract.TransactionEntry.COLUMN_TRANSACTION_VALUE + " REAL NOT NULL, "
+ TransactionContract.TransactionEntry.COLUMN_TRANSACTION_DATE + " INTEGER NOT NULL);";
db.execSQL(SQL_CREATE_TRANSACTION_TABLE);
}
private static final String SQL_DELETE_TRANSACTION_TABLE =
"DROP TABLE IF EXISTS " + TransactionContract.TransactionEntry.TABLE_NAME;
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
db.execSQL(SQL_DELETE_TRANSACTION_TABLE);
onCreate(db);
}
}
}
| [
"kellymaria.bentes@gmail.com"
] | kellymaria.bentes@gmail.com |
2944667089c63f7ad1bc5838a04734d61f2506b8 | dcddb83fc4ae07250dd30bbc1e59ba13237f335b | /src/mipt/infosec/bitcoin/network/Protocol.java | cdf69f869d707a6da5147ff7aa87f7315af1cf7d | [] | no_license | yuranich/BitcoinAnalogProject | 0b10a642b874cfc05771025208ff64661b0e7c7f | 76bb4c52d37e7ff1bb93e1352cf0d34b7740610d | refs/heads/master | 2021-01-10T22:06:32.496561 | 2014-12-13T11:11:39 | 2014-12-13T11:11:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 269 | java | package mipt.infosec.bitcoin.network;
public class Protocol {
public static final int CONNECTION_PORT = 60000;
public static final int NEW_PUBLIC_KEY = 1;
public static final int NEW_TRANSACTION = 2;
public static final int SUCCESSFUL_TRANSACTION = 3;
}
| [
"yuri.a.samarin@gmail.com"
] | yuri.a.samarin@gmail.com |
1002033fa05a1f3590562da3c3dab30d8f100344 | aa226c3d8d63758ae339005fab70733971b92205 | /dziedziczenie/src/algorytmy/Zliczanie.java | e19274fab89cdc753293f345b37ab4dd8ae86e25 | [] | no_license | kata-chan/dziedziczenie | 5895b645e6effac37f23b895ce22dcf54fdbfab6 | fb451b96aa2425f4b28081b6f7068e8b51070a9e | refs/heads/master | 2021-01-10T09:39:56.575394 | 2016-03-17T06:42:07 | 2016-03-17T06:42:07 | 45,971,255 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 323 | java | package algorytmy;
public class Zliczanie {
public static int zliczanie(int x) {
int liczbaZliczona = 0;
while (x > 0) {
liczbaZliczona = liczbaZliczona + x % 10;
x = x / 10;
}
if (liczbaZliczona > 9) {
liczbaZliczona = zliczanie(liczbaZliczona);
}
return liczbaZliczona;
}
}
| [
"kasha.lenart@gmail.com"
] | kasha.lenart@gmail.com |
1301912fd3a8f48b8ebce2530dacb0f6cfcaf17d | 1df9b7163784930af3a43a0a940afbe14ee8a132 | /app/src/main/java/com/example/yls/test1/NotesDB.java | 276a4f294f59301b5f92a972c71aed6566c9718e | [] | no_license | ruanjianyanyifan/jishiben | 2a11f336242e80acf001dfbb7e330fdd9ffe9acb | 4590ffb4aae1fe9e7539e4ed1aa3b71a4026ba4e | refs/heads/master | 2020-05-31T18:15:15.657319 | 2017-06-12T01:33:06 | 2017-06-12T01:33:06 | 94,043,768 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,576 | java | package com.example.yls.test1;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by yls on 2017/5/15.
*/
public class NotesDB extends SQLiteOpenHelper {
public static final String TABLE_NAME_NOTES = "note";
public static final String COLUMN_NAME_ID = "_id";
public static final String COLUMN_NAME_NOTE_CONTENT = "content";
public static final String COLUMN_NAME_NOTE_DATE = "date";
public NotesDB(Context context) {
super(context, "note", null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME_NOTES + "(" + COLUMN_NAME_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME_NOTE_CONTENT + " TEXT NOT NULL DEFAULT\"\","
+ COLUMN_NAME_NOTE_DATE + " TEXT NOT NULL DEFAULT\"\"" + ")";
Log.d("SQL", sql);
db.execSQL(sql);
// String sql1="insert into "+TABLE_NAME_NOTES+"values("+"1,"+"'写作业',"+"'晚上要写作业的干活'"+")";
// Log.d("SQL1", sql1);
// db.execSQL(sql1);
// ContentValues values=new ContentValues();
// values.put("id",1);
// values.put("content","写作业");
// values.put("date", "2013-1-2");
// db.insert("note", null, values);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
| [
"956266717@qq.com"
] | 956266717@qq.com |
69cd62d15ebaa93ca23a2c4be2c944c04b84bbf9 | 8fb7c282c0f086fabd01952fa9e2b9caadb13c42 | /src/main/java/cn/yuchen/bigdate/rs/service/model/dao/ModelModuleDao.java | abc38635403e5d1a25c63a48c9f858f122a53711 | [] | no_license | wangzhixian/regionalstability | b24c1048db2fc13c45a4a6f5bc80a9959b3b0fd6 | e835d979c8d58dc541226237c63b4fef08200a30 | refs/heads/master | 2020-03-22T19:45:43.223073 | 2018-09-18T06:28:26 | 2018-09-18T06:28:26 | 140,549,020 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 576 | java | package cn.yuchen.bigdate.rs.service.model.dao;
import cn.yuchen.bigdate.rs.service.model.pojo.webvo.ModelPageVo;
import cn.yuchen.bigdate.rs.service.model.pojo.po.ModelModulePo;
import cn.yuchen.bigdate.rs.service.model.pojo.vo.ModelModuleVo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ModelModuleDao {
int insert(ModelModulePo record);
int deleteByPrimaryKey(Long id);
int update(ModelModulePo record);
List<ModelModuleVo> selectByPage(ModelPageVo modelPageVo);
List<ModelModulePo> selectAll();
} | [
"wangzhixian.king@foxmail.com"
] | wangzhixian.king@foxmail.com |
f039283c6a0f862e4a5e01379411f21d1a78ebfe | 2294b9cfc35a5061df72cba9db79039aaa4455b3 | /CoreFeatures/Checkpoint/FailureAction/src/main/java/info/smart_tools/smartactors/checkpoint/failure_action/CheckpointFailureActionSectionStrategy.java | 2ad2006f30c533c86d630a666db0682782772b15 | [
"Apache-2.0"
] | permissive | qwertyo1/smartactors-core | f89f5f4ea7997eb833a6516cb25095a1fff487b0 | 35d6cae61144305e80b22db04264c14be8405c3f | refs/heads/master | 2020-12-22T20:43:38.307590 | 2019-10-07T06:12:37 | 2019-10-07T06:12:37 | 236,926,857 | 0 | 0 | null | 2020-01-29T07:30:15 | 2020-01-29T07:30:14 | null | UTF-8 | Java | false | false | 3,486 | java | package info.smart_tools.smartactors.checkpoint.failure_action;
import info.smart_tools.smartactors.base.exception.invalid_argument_exception.InvalidArgumentException;
import info.smart_tools.smartactors.base.interfaces.iaction.IAction;
import info.smart_tools.smartactors.base.strategy.singleton_strategy.SingletonStrategy;
import info.smart_tools.smartactors.configuration_manager.interfaces.iconfiguration_manager.ISectionStrategy;
import info.smart_tools.smartactors.configuration_manager.interfaces.iconfiguration_manager.exceptions.ConfigurationProcessingException;
import info.smart_tools.smartactors.iobject.ifield_name.IFieldName;
import info.smart_tools.smartactors.iobject.iobject.IObject;
import info.smart_tools.smartactors.iobject.iobject.exception.ReadValueException;
import info.smart_tools.smartactors.ioc.iioccontainer.exception.RegistrationException;
import info.smart_tools.smartactors.ioc.iioccontainer.exception.ResolutionException;
import info.smart_tools.smartactors.ioc.ioc.IOC;
import info.smart_tools.smartactors.ioc.named_keys_storage.Keys;
/**
* Strategy for "checkpoint_failure_action" configuration section. That section defines the action that should be executed on the message
* lost by a checkpoint.
*
* <pre>
* {
* ...
* "checkpoint_failure_action": {
* "action": "send to chain checkpoint failure action", // Name of the action dependency
*
* // Action-specific parameters (example for "send to chain" action):
* "targetChain": "myLastResortChain", // Chain to send envelope to
* "messageField": "message" // Field of the envelope where to store the message
* }
* }
* </pre>
*/
public class CheckpointFailureActionSectionStrategy implements ISectionStrategy {
private final IFieldName sectionName;
private final IFieldName actionNameFieldName;
/**
* The constructor.
*
* @throws ResolutionException if error occurs resolving any dependencies
*/
public CheckpointFailureActionSectionStrategy()
throws ResolutionException {
sectionName = IOC.resolve(Keys.getOrAdd("info.smart_tools.smartactors.iobject.ifield_name.IFieldName"), "checkpoint_failure_action");
actionNameFieldName = IOC.resolve(Keys.getOrAdd("info.smart_tools.smartactors.iobject.ifield_name.IFieldName"), "action");
}
@Override
public void onLoadConfig(final IObject config) throws ConfigurationProcessingException {
try {
IObject section = (IObject) config.getValue(sectionName);
Object actionKeyName = section.getValue(actionNameFieldName);
if (null == actionKeyName) {
actionKeyName = "default configurable checkpoint failure action";
}
IAction<IObject> action = IOC.resolve(IOC.resolve(IOC.getKeyForKeyStorage(), actionKeyName), section);
IOC.register(Keys.getOrAdd("checkpoint failure action"),
new SingletonStrategy(action));
} catch (ReadValueException | InvalidArgumentException | ResolutionException | RegistrationException e) {
throw new ConfigurationProcessingException("Error occurred processing checkpoint_failure_action section.", e);
}
}
@Override
public IFieldName getSectionName() {
return sectionName;
}
}
| [
"alexey.bond.94.55@gmail.com"
] | alexey.bond.94.55@gmail.com |
0cfc6d2d7b56f717073f2b2aaa1be4557b993f36 | 5440a66eecbbfbf01b29ab1f9728ee0daa8fb52d | /pau-admin/src/main/java/com/soft/ware/modular/system/factory/UserFactory.java | 025f8e40d34fbb9a6ba23023a223fde4fd7e2a57 | [
"Apache-2.0"
] | permissive | guoop/pau | 6bbc990b56a0a0a7edd6e8da2fe65bb80eac6f99 | 8635bef6f4dff0782fb9e2afb892fb422a8a1760 | refs/heads/master | 2022-12-22T14:37:04.961449 | 2019-12-17T03:09:20 | 2019-12-17T03:09:20 | 167,721,383 | 0 | 0 | NOASSERTION | 2022-12-16T21:57:36 | 2019-01-26T18:06:05 | Java | UTF-8 | Java | false | false | 504 | java | package com.soft.ware.modular.system.factory;
import com.soft.ware.modular.system.transfer.UserDto;
import com.soft.ware.modular.system.model.User;
import org.springframework.beans.BeanUtils;
/**
* 用户创建工厂
*/
public class UserFactory {
public static User createUser(UserDto userDto){
if(userDto == null){
return null;
}else{
User user = new User();
BeanUtils.copyProperties(userDto,user);
return user;
}
}
}
| [
"744964089@qq.com"
] | 744964089@qq.com |
eecbc9303b7b68d32233b073a25ff1335745f3cf | a7f4c4bbb5a02df256cc32b4cfc4f70d5e6d5f50 | /app/src/main/java/by/antukh/noteswithme/synk/ExchangePacket.java | 9efa90b3d9b73459280878d9d5d2a0f69db51f9a | [] | no_license | AntukhKatsya/PMSProject | 8f6e4c3e889ec35f7f9098fecc09d96b4593aef0 | 4baea780e8ad70e160fe541c91056ee844561410 | refs/heads/master | 2021-09-03T11:57:22.632155 | 2018-01-08T22:11:54 | 2018-01-08T22:11:54 | 116,734,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 112 | java | package by.antukh.noteswithme.system;
/**
* Created by acdc on 07.01.18.
*/
public class ExchangePacket {
}
| [
"2Ðkaterok2@mail.ru"
] | 2Ðkaterok2@mail.ru |
5745191a94cbc003200f6ea521a60e8579dadd47 | d6dddeaa9a161d428eb735215cab2ea9ce471661 | /src/com/example/studentparticipationandattendancetracker/AttendanceRecord.java | 62dad75fd93e735b91cd0406fc27eabc7afccbed | [] | no_license | murhaf-khaled/studentParticipationAndAttendanceTracker | ec5cc49f8111aca2b55424754ef61623e0ede666 | 5cdca0e7cbb811bccce5a8578ce339258de8036a | refs/heads/master | 2020-05-18T03:12:17.307434 | 2014-12-03T09:17:28 | 2014-12-03T09:17:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,758 | java | package com.example.studentparticipationandattendancetracker;
import java.util.Date;
public class AttendanceRecord {
private Date attendanceDate;
private int studentID;
private String studentName;
private int courseID;
private String attendanceStatus;
private int count;
/**
* @param attendanceDate
* @param studentID
* @param studentName
* @param courseID
* @param attendanceStatus
*/
public AttendanceRecord(Date attendanceDate, int studentID,
String studentName, int courseID, String attendanceStatus) {
super();
this.attendanceDate = attendanceDate;
this.studentID = studentID;
this.studentName = studentName;
this.courseID = courseID;
this.attendanceStatus = attendanceStatus;
}
/**
* @param attendanceDate
* @param studentID
* @param studentName
* @param courseID
* @param count
*/
public AttendanceRecord(Date attendanceDate, int studentID,
String studentName, int courseID, int count) {
super();
this.attendanceDate = attendanceDate;
this.studentID = studentID;
this.studentName = studentName;
this.courseID = courseID;
this.count = count;
}
/**
* @param studentID
* @param studentName
* @param count
*/
public AttendanceRecord(int studentID, String studentName, int count) {
super();
this.studentID = studentID;
this.studentName = studentName;
this.count = count;
}
/**
* @return the attendanceDate
*/
public Date getAttendanceDate() {
return attendanceDate;
}
/**
* @param attendanceDate the attendanceDate to set
*/
public void setAttendanceDate(Date attendanceDate) {
this.attendanceDate = attendanceDate;
}
/**
* @return the studentID
*/
public int getStudentID() {
return studentID;
}
/**
* @param studentID the studentID to set
*/
public void setStudentID(int studentID) {
this.studentID = studentID;
}
/**
* @return the studentName
*/
public String getStudentName() {
return studentName;
}
/**
* @param studentName the studentName to set
*/
public void setStudentName(String studentName) {
this.studentName = studentName;
}
/**
* @return the courseID
*/
public int getCourseID() {
return courseID;
}
/**
* @param courseID the courseID to set
*/
public void setCourseID(int courseID) {
this.courseID = courseID;
}
/**
* @return the attendanceStatus
*/
public String getAttendanceStatus() {
return attendanceStatus;
}
/**
* @param attendanceStatus the attendanceStatus to set
*/
public void setAttendanceStatus(String attendanceStatus) {
this.attendanceStatus = attendanceStatus;
}
/**
* @return the count
*/
public int getCount() {
return count;
}
/**
* @param count the count to set
*/
public void setCount(int count) {
this.count = count;
}
}
| [
"newmorhaf@gmail.com"
] | newmorhaf@gmail.com |
98355f53f0e97a18c070dc086c91986eb9979208 | 7332a820e4c01af12b76afd9233c1c93ae0a8ef2 | /src/com/ms/silverking/cloud/dht/client/impl/AsyncOperationImpl.java | b31637701cfe27ee1025cd71009f9c79689f2fad | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bepahol/SilverKing | d58255caf3201504b1941004f99112bc92cba1ab | 4651d62ae12e35f33998e02b7d6ed5ecd9bae37b | refs/heads/master | 2021-01-11T18:05:57.193915 | 2019-05-20T22:56:19 | 2019-05-20T22:56:19 | 79,489,059 | 0 | 0 | null | 2018-03-16T21:51:45 | 2017-01-19T19:49:55 | Java | UTF-8 | Java | false | false | 14,627 | java | package com.ms.silverking.cloud.dht.client.impl;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.google.common.collect.ImmutableSet;
import com.ms.silverking.cloud.dht.NonExistenceResponse;
import com.ms.silverking.cloud.dht.client.AsyncOperation;
import com.ms.silverking.cloud.dht.client.AsyncOperationListener;
import com.ms.silverking.cloud.dht.client.FailureCause;
import com.ms.silverking.cloud.dht.client.OpTimeoutController;
import com.ms.silverking.cloud.dht.client.OperationException;
import com.ms.silverking.cloud.dht.client.OperationState;
import com.ms.silverking.cloud.dht.common.OpResult;
import com.ms.silverking.cloud.dht.common.SystemTimeUtil;
import com.ms.silverking.cloud.dht.net.MessageGroup;
import com.ms.silverking.cloud.dht.net.ProtoMessageGroup;
import com.ms.silverking.collection.CollectionUtil;
import com.ms.silverking.collection.Pair;
import com.ms.silverking.log.Log;
import com.ms.silverking.thread.lwt.BaseWorker;
/**
* AsyncOperationImpl provides a concrete implementation of AsyncOperation
* and wraps an Operation with current state.
*/
abstract class AsyncOperationImpl implements AsyncOperation {
protected final Operation operation;
protected byte[] originator;
private final Lock lock;
private final Condition cv;
private volatile OpResult result;
protected final EnumSet<OpResult> allResults;
private volatile Set<Pair<AsyncOperationListener,EnumSet<OperationState>>> listeners;
private static final boolean spin = true;
private static final int spinDurationNanos = 5 * 1000;
// Attempt state
private volatile boolean sent; // a hint as to whether or not this operation has been sent before
// used to optimize the first message creation
protected OpTimeoutState timeoutState;
public AsyncOperationImpl(Operation operation, long curTimeMillis, byte[] originator) {
OpTimeoutController timeoutController;
assert operation != null;
assert originator != null;
this.operation = operation;
this.originator = originator;
lock = new ReentrantLock();
cv = lock.newCondition();
result = OpResult.INCOMPLETE;
allResults = EnumSet.noneOf(OpResult.class);
// FUTURE - could lazily create the timeout state since most ops never need it
//System.out.printf("%s %d\n", timeoutParameters.hasRelTimeout(), timeoutParameters.getRelTimeout());
timeoutController = operation.getTimeoutController();
timeoutState = new OpTimeoutState(this, timeoutController, curTimeMillis);
}
protected abstract NonExistenceResponse getNonExistenceResponse();
protected final boolean isActive() {
return !result.isComplete();
}
boolean opHasTimedOut(long curTimeMillis) {
return timeoutState.opHasTimedOut(curTimeMillis);
}
boolean attemptHasTimedOut(long curTimeMillis) {
return timeoutState.attemptHasTimedOut(curTimeMillis);
}
void newAttempt(long curTimeMillis) {
timeoutState.newAttempt(curTimeMillis);
}
public ClientOpType getType() {
return operation.getOpType();
}
public final OperationUUID getUUID() {
return operation.getUUID();
}
@Override
public OperationState getState() {
return result.toOperationState(getNonExistenceResponse());
}
protected OpResult getResult() {
return result;
}
@Override
public FailureCause getFailureCause() {
return result.toFailureCause(getNonExistenceResponse());
}
@Override
public void close() {
cleanup();
}
protected abstract int opWorkItems();
protected boolean isFailure(OpResult result) {
return result.hasFailed(getNonExistenceResponse());
}
protected void failureCleanup(FailureCause failureCause) {
cleanup();
}
protected void cleanup() {
}
// must hold completionCheckLock
protected void setResult(EnumSet<OpResult> results) {
assert results.size() > 0;
allResults.addAll(results);
if (results.size() > 1) {
setResult(OpResult.MULTIPLE);
} else {
setResult(results.iterator().next());
}
}
protected void setResult(OpResult result) {
assert result.isComplete();
if (this.result.isComplete()) {
if (result != this.result) {
Log.warning("AsyncOperationImpl.setResult() ignoring new completion", this);
} else {
Log.fine("AsyncOperationImpl.setResult() received duplicate completion", this);
}
} else {
Set<Pair<AsyncOperationListener,EnumSet<OperationState>>> _listeners;
_listeners = null;
lock.lock();
try {
if (!this.result.isComplete()) {
//System.out.println("Setting result to: "+ result);
if (isFailure(result)) {
failureCleanup(result.toFailureCause(getNonExistenceResponse()));
}
this.result = result;
cv.signalAll();
if (listeners != null) {
_listeners = ImmutableSet.copyOf(listeners);
}
} else {
if (result != this.result) {
Log.warning("AsyncOperationImpl.setResult() ignoring new completion", this);
} else {
Log.fine("AsyncOperationImpl.setResult() received duplicate completion", this);
}
}
} finally {
lock.unlock();
}
if (_listeners != null) {
notificationWorker.fiterForUpdates(this, _listeners, getState());
}
cleanup();
}
}
/**
* Called by subclasses to update incomplete state. Complete updates are handled inside of
* setResult to ensure that completion results fire exactly once.
*/
protected void checkForUpdates() {
if (listeners != null) {
Set<Pair<AsyncOperationListener,EnumSet<OperationState>>> _listeners;
OperationState opState;
opState = getState();
if (opState == OperationState.INCOMPLETE) {
_listeners = null;
lock.lock();
try {
if (listeners != null) {
_listeners = ImmutableSet.copyOf(listeners);
}
} finally {
lock.unlock();
}
if (_listeners != null) {
notificationWorker.fiterForUpdates(this, _listeners, opState);
}
}
}
}
private void notifyListeners(Set<AsyncOperationListener> listeners) {
for (AsyncOperationListener listener : listeners) {
listener.asyncOperationUpdated(this);
}
}
private static final NotificationWorker notificationWorker = new NotificationWorker();
private static class NotificationWorker extends BaseWorker<Pair<AsyncOperationImpl, Set<AsyncOperationListener>>> {
NotificationWorker() {
}
void fiterForUpdates(AsyncOperationImpl opImpl, Set<Pair<AsyncOperationListener,EnumSet<OperationState>>> _listeners, OperationState opState) {
Set<AsyncOperationListener> listeners;
listeners = new HashSet<>();
for (Pair<AsyncOperationListener, EnumSet<OperationState>> candidate : _listeners) {
if (candidate.getV2().contains(opState)) {
listeners.add(candidate.getV1());
}
}
notificationWorker.addWork(new Pair<>(opImpl, listeners), 0);
}
@Override
public void doWork(Pair<AsyncOperationImpl, Set<AsyncOperationListener>> p) {
p.getV1().notifyListeners(p.getV2());
}
}
public boolean waitForCompletion(long timeout, TimeUnit unit) throws OperationException {
long relativeDeadlineMillis;
long absoluteDeadlineMillis;
relativeDeadlineMillis = TimeUnit.MILLISECONDS.convert(timeout, unit);
absoluteDeadlineMillis = SystemTimeUtil.systemTimeSource.absTimeMillis() + relativeDeadlineMillis;
lock.lock();
try {
while (!result.isComplete()) {
try {
long millisToDeadline;
millisToDeadline = absoluteDeadlineMillis - SystemTimeUtil.systemTimeSource.absTimeMillis();
if (millisToDeadline > 0) {
Log.fine("activeOp awaiting ", this);
if (!spin) {
cv.await(millisToDeadline, TimeUnit.MILLISECONDS);
} else {
cv.awaitNanos(spinDurationNanos);
}
} else {
debugTimeout();
return false;
}
} catch (InterruptedException ie) {
}
}
if (isFailure(result)) {
throwFailedException();
}
return true;
} finally {
lock.unlock();
}
}
protected void debugTimeout() {
}
protected abstract void throwFailedException() throws OperationException;
/**
* Adds a completion listener. If the operation is already complete, the callback will be
* immediately executed, possibly in the calling thread.
* Equivalent to addListener(listener, OperationState.SUCCEEDED, OperationState.FAILED)
* @param listener completion listener
*/
public void addListener(AsyncOperationListener listener) {
addListener(listener, OperationState.SUCCEEDED, OperationState.FAILED);
}
/**
* Adds multiple completion listeners. For any listener that is already complete, the callback will be
* immediately executed, possibly in the calling thread.
* Equivalent to addListeners(listeners, OperationState.SUCCEEDED, OperationState.FAILED)
* @param listeners update listeners
*/
public void addListeners(Iterable<AsyncOperationListener> listeners) {
addListeners(listeners, OperationState.SUCCEEDED, OperationState.FAILED);
}
/**
* Adds an operation listener. If the operation is already complete, the callback will be
* immediately executed, possibly in the calling thread.
* @param listener update listener
* @param listenStates states to generate updates for
*/
public void addListener(AsyncOperationListener listener, OperationState... listenStates) {
EnumSet<OperationState> _listenStates;
OperationState opState;
_listenStates = CollectionUtil.arrayToEnumSet(listenStates);
opState = getState();
lock.lock();
try {
// Trigger immediate updates for completion, but only for completion
if (opState != OperationState.INCOMPLETE && _listenStates.contains(opState)) {
listener.asyncOperationUpdated(this);
} else {
if (listeners == null) {
listeners = new HashSet<>();
}
listeners.add(new Pair<>(listener, _listenStates));
}
} finally {
lock.unlock();
}
}
/**
* Adds multiple completion listeners. For any listener that is already complete, the callback will be
* immediately executed, possibly in the calling thread.
* @param listeners update listeners
* @param listenStates states to generate updates for
*/
public void addListeners(Iterable<AsyncOperationListener> _listeners, OperationState... listenStates) {
EnumSet<OperationState> _listenStates;
OperationState opState;
_listenStates = CollectionUtil.arrayToEnumSet(listenStates);
opState = getState();
lock.lock();
try {
// Trigger immediate updates for completion, but only for completion
if (opState != OperationState.INCOMPLETE && _listenStates.contains(opState)) {
for (AsyncOperationListener listener : _listeners) {
listener.asyncOperationUpdated(this);
}
} else {
if (listeners == null) {
listeners = new HashSet<>();
}
for (AsyncOperationListener listener : _listeners) {
listeners.add(new Pair<>(listener, _listenStates));
}
}
} finally {
lock.unlock();
}
}
void _waitForCompletion() throws OperationException {
lock.lock();
try {
while (!result.isComplete()) {
try {
Log.fine("activeOp awaiting ", this);
if (!spin) {
cv.await();
} else {
cv.awaitNanos(spinDurationNanos);
}
} catch (InterruptedException ie) {
}
}
if (isFailure(result)) {
throwFailedException();
}
} finally {
lock.unlock();
}
}
public boolean poll() {
boolean complete;
lock.lock();
try {
complete = result.isComplete();
} finally {
lock.unlock();
}
return complete;
}
public boolean poll(long duration, TimeUnit timeUnit) {
boolean complete;
lock.lock();
try {
while (!result.isComplete()) {
try {
if (!spin) {
cv.await(duration, timeUnit);
} else {
cv.awaitNanos(spinDurationNanos);
}
} catch (InterruptedException ie) {
}
}
complete = result.isComplete();
} finally {
lock.unlock();
}
return complete;
}
protected void setSent() {
sent = true;
}
protected boolean getSent() {
return sent;
}
abstract void addToEstimate(MessageEstimate estimate);
abstract MessageEstimate createMessageEstimate();
abstract ProtoMessageGroup createProtoMG(MessageEstimate estimate);
abstract ProtoMessageGroup createMessagesForIncomplete(ProtoMessageGroup protoMG, List<MessageGroup> messageGroups, MessageEstimate estimate);
@Override
public String toString() {
StringBuilder sb;
sb = new StringBuilder();
sb.append(super.toString());
sb.append(operation.getOpType());
sb.append(':');
sb.append(getUUID());
sb.append(':');
sb.append(result);
return sb.toString();
}
// for debugging
protected final String objectToString() {
return super.toString();
}
/**
* Determine if this operation can be grouped with another operation in a single
* message.
* @param asyncOperationImpl
* @return True iff this operation can be another operation
*/
public boolean canBeGroupedWith(AsyncOperationImpl asyncOperationImpl) {
return asyncOperationImpl.getType() == getType();
}
}
| [
"bepahol2@gmail.com"
] | bepahol2@gmail.com |
4a656b9c77deac858f7952a4ea7429ece015bcff | 2e81698f6e1336c595f30be2b416deda3cddd414 | /src/Services/serviceEntraineur.java | a1634d4a6756ab6b86ce8c739610a7ebde10fa03 | [] | no_license | Legacy2018/PIDEV | fc60c5e5bd9c2689a5cb370e79c966a6d0b66d14 | e440d7ee3590ef7d2a6035c741aad803009b3de5 | refs/heads/master | 2021-04-28T06:38:40.626412 | 2018-05-22T02:21:20 | 2018-05-22T02:21:20 | 122,205,046 | 0 | 0 | null | 2018-02-20T15:47:30 | 2018-02-20T13:56:37 | Java | UTF-8 | Java | false | false | 4,318 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Services;
import DataSource.DataSource;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import Entities.Entraineur;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Emel
*/
public class serviceEntraineur {
DataSource db;
Connection cnx;
Statement st;
public serviceEntraineur() {
cnx = (Connection) db.getInstance().getConnection();
try {
st = (Statement) cnx.createStatement();
} catch (SQLException ex) {
Logger.getLogger(serviceEntraineur.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void ajouterEntraineur(Entraineur e) {
try {
String req = " INSERT INTO `entraineur` (`id_entraineur`, `nom_entraineur`, `nationalité`, `id_equipe`)"
+ " VALUES (NULL, '" + e.getNom_entraineur() + "', '" + e.getNationalite() + "', '" + e.getId_equipe() + "');";
st.executeUpdate(req);
} catch (SQLException ex) {
Logger.getLogger(serviceEntraineur.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void modifierEntraineur(Entraineur e)
{ try {
String req = "UPDATE `entraineur` SET "
+ "`nom_entraineur` = '" + e.getNom_entraineur() + "', `nationalité` = '" + e.getNationalite() + "', `id_equipe` = '" + e.getId_equipe() + "' "
+ "WHERE `entraineur`.`id_entraineur` = " + e.getId_entraineur() + ";";
st.executeUpdate(req);
} catch (SQLException ex) {
Logger.getLogger(serviceEntraineur.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void supprimerEntraineur(int id_entraineur) {
try {
String req = "DELETE FROM `entraineur` "
+ "WHERE `entraineur`.`id_entraineur` = " + id_entraineur + ";";
st.executeUpdate(req);
} catch (SQLException ex) {
Logger.getLogger(serviceEntraineur.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void chercherParNom(String nom) {
List<Entraineur> entraineurs = new ArrayList<>();
try {
ResultSet rest= st.executeQuery("select * from Entraineur where nom_entraineur like '%+" + nom + "+%'");
if (!rest.next()) {
System.err.println("Resultat introuvable");
} else {
rest.beforeFirst();
while (rest.next()) {
Entraineur e = new Entraineur();
e.setId_entraineur(rest.getInt(1));
e.setNom_entraineur(rest.getString(2));
e.setNationalite(rest.getString(3));
e.setId_equipe(rest.getInt(4));
entraineurs.add(e);
}
for (Entraineur e : entraineurs) {
System.out.println(e);
}
}
} catch (SQLException ex) {
Logger.getLogger(serviceEntraineur.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void selectEntraineurs() {
List<Entraineur> entraineurs = new ArrayList<>();
try {
ResultSet rest= st.executeQuery("select * from Entraineur");
if (!rest.next()) {
System.err.println("Resultat introuvable");
} else {
rest.beforeFirst();
while (rest.next()) {
Entraineur e = new Entraineur();
e.setId_entraineur(rest.getInt(1));
e.setNom_entraineur(rest.getString(2));
e.setNationalite(rest.getString(3));
e.setId_equipe(rest.getInt(4));
entraineurs.add(e);
}
for (Entraineur e : entraineurs) {
System.out.println(e);
}
}
} catch (SQLException ex) {
Logger.getLogger(serviceEntraineur.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| [
"ali.garouachi@hotmail.com"
] | ali.garouachi@hotmail.com |
29601ea3d9372e997f0f7be57524c311e602b903 | f1347f1b93fcabe4a8126a58d2afef3e6796cc15 | /AppMovil/GasStationFarmacy/app/src/main/java/com/example/bryan/gasstationfarmacy/ProductosAdapter.java | 5ed6c77b323cbd8c0b9a0e64f1ce969c24349937 | [] | no_license | Ronypa/GasStationPharmacy3RB | e0a9bfe29f4c0f82dd17c41d8247bd8ee1704f30 | eefe285de5200734365b265bef6e4717279231c5 | refs/heads/master | 2021-07-12T22:48:06.203366 | 2017-10-17T23:26:23 | 2017-10-17T23:26:23 | 104,280,391 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,741 | java | package com.example.bryan.gasstationfarmacy;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Adapter de la lista de productos/medicamentos
*/
public class ProductosAdapter extends ArrayAdapter<Medicamentos> implements CompoundButton.OnCheckedChangeListener{
private ArrayList<Medicamentos> medicamentosList;//Lista completa de medicamentos
private static ArrayList<Medicamentos> submedicamentosList;//Lista de medicamentos seleccionados
private Context context;//contexto
/**
* Constructor de la clase
* @param medicamentosList: lista de medicamentos a mostrar en la lista
* @param context: contxto de activity que lo invoca
*/
public ProductosAdapter(ArrayList<Medicamentos> medicamentosList, Context context) {
super(context, R.layout.item_medicamento,medicamentosList);
this.medicamentosList=medicamentosList;
this.context=context;
submedicamentosList = new ArrayList<>();
}
/**
* Metodo que se ejecuta cuanto se activa o desactiva un checkbox
* @param buttonView: el check que se activo/desactivo
* @param isChecked:si se marcó o se desmarcó
*/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = Productos.getListViewProductos().getPositionForView(buttonView);
if(pos!= ListView.INVALID_POSITION){
Medicamentos m = Productos.getListaProductos().get(pos);
if(isChecked){
submedicamentosList.add(m); //Si se marcó se agrega a la lista
}else{
submedicamentosList.remove(m);//Si se desmarcó se quita de la lista
}
}
}
/**
* El holder es para que no se desmarquen los checkboxes al ocultarse por la presencia de un scrollbar
*/
public static class MedicamentoHolder{
public TextView nombreMedicamento;
public TextView precio;
public CheckBox check;
public MedicamentoHolder(){}
}
/**
* Obtiene un view
* @param position: posicion del view
* @param convertView: objeto view
* @param parent: padre del view
* @return: el view
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v =convertView;
MedicamentoHolder holder =new MedicamentoHolder();
if(convertView==null){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.item_medicamento,null);
holder.nombreMedicamento=(TextView) v.findViewById(R.id.medicamento);
holder.precio=(TextView) v.findViewById(R.id.precio);
holder.check = (CheckBox) v.findViewById(R.id.check);
holder.check.setOnCheckedChangeListener(ProductosAdapter.this);
}else{
holder = (MedicamentoHolder) v.getTag();
}
Medicamentos m = medicamentosList.get(position);
if(holder!=null){
holder.nombreMedicamento.setText(m.getNombre());
holder.precio.setText(m.getPrecio());
//holder.check.setChecked(parent.isSelected());
holder.check.setChecked(parent.isSelected());
holder.check.setTag(m);}
return v;
}
/**
* @return: lista de objetos seleccionados
*/
public static ArrayList<Medicamentos> getSubmedicamentosList(){return submedicamentosList;}
}
| [
"rarias1820@live.com"
] | rarias1820@live.com |
8983f439290803b56c8238c314a6d08605aa0a76 | aeca27a5c08453ad840a777534397fd909ea969a | /src/main/java/GenericCalculator.java | d566c900f204a321e22e289f049ea0763638d182 | [] | no_license | beckfordp/Shopping | da48ae503cdf85dc4fab2b78473ec3b6fb5d4106 | 3435901f85d7a6340775fcace758e543e32d04e9 | refs/heads/master | 2021-01-23T22:52:54.939188 | 2015-04-13T07:18:12 | 2015-04-13T07:18:12 | 33,640,866 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,476 | java | import rx.Observable;
import java.util.List;
public class GenericCalculator {
private Observable<BasketItem> basketObservable;
private Observable<Integer> totalPriceObservable;
public GenericCalculator(List<BasketItem> items) {
basketObservable = Observable.from(items);
totalPriceObservable = Observable.merge(each(), offer_b1g1f(), offer_b3fp2()).scan(0, this::sum);
}
private Observable<Integer> offer_b3fp2() {
return basketObservable.filter((item) -> item.onOffer(OfferEnum.BUY_THREE_FOR_THE_PRICE_OF_TWO)).buffer(3)
.map((eachOffer) -> {
Integer each = eachOffer.get(0).getUnitPrice();
int count = eachOffer.size();
return count == 3 ? each * 2 : count * each;
});
}
private Observable<Integer> offer_b1g1f() {
return basketObservable.filter((item) -> item.onOffer(OfferEnum.BUY_ONE_GET_ONE_FREE)).buffer(2)
.map((eachOffer) -> eachOffer.get(0).getUnitPrice());
}
private Observable<Integer> each() {
return basketObservable.filter((item) -> item.onOffer(OfferEnum.NONE)).map(BasketItem::getUnitPrice);
}
public Observable<Integer> totalPrice() {
return totalPriceObservable;
}
private Integer sum(Integer acc, Integer next) {
return acc + next;
}
}
| [
"beckfordp@btinternet.com"
] | beckfordp@btinternet.com |
9c93147c1048fa34359c36787481374261757808 | e347c84aaa18bf86345e2da0e5630aca5067ea3c | /app/src/main/java/com/example/rigbys/Seller/SellerAddFragment.java | e1f8696d4a62dd650543f09cc3c3678f731dd6d6 | [] | no_license | Shahrin04/Rigbys | b8cc7b22efcb1efa8b1b2bbfcf7e2c347ae0a5ba | b739bd21abd8fee1d4dd8838e528637c286ba08c | refs/heads/master | 2023-05-27T16:48:10.869076 | 2021-06-11T15:19:54 | 2021-06-11T15:19:54 | 376,063,965 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,353 | java | package com.example.rigbys.Seller;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.rigbys.Buyer.CategoryDetailsActivity;
import com.example.rigbys.R;
import com.example.rigbys.Seller.SellerAddNewProductActivity;
public class SellerAddFragment extends Fragment {
private ImageView tshirts, sports_tshirts, female_dress, sweaters, glasses, ladies_bags, hats_caps, shoes, headphone, laptop, watches, mobiles;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_seller_add, container, false);
// Inflate the layout for this fragment
tshirts = view.findViewById(R.id.category_male_dress);
sports_tshirts = view.findViewById(R.id.category_sports_dress);
female_dress = view.findViewById(R.id.category_female_dress);
sweaters = view.findViewById(R.id.category_winter_dress);
glasses = view.findViewById(R.id.category_glasses);
ladies_bags = view.findViewById(R.id.category_female_bags);
hats_caps = view.findViewById(R.id.category_hats);
shoes = view.findViewById(R.id.category_shoes);
headphone = view.findViewById(R.id.category_headphones);
laptop = view.findViewById(R.id.category_computer);
watches = view.findViewById(R.id.category_watches);
mobiles = view.findViewById(R.id.category_mobiles);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tshirts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "tshirts");
startActivity(intent);
}
});
sports_tshirts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "sportsTshirts");
startActivity(intent);
}
});
female_dress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "femaleDress");
startActivity(intent);
}
});
sweaters.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "sweaters");
startActivity(intent);
}
});
glasses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "glasses");
startActivity(intent);
}
});
ladies_bags.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "ladiesBags");
startActivity(intent);
}
});
hats_caps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "hatsCaps");
startActivity(intent);
}
});
shoes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "shoes");
startActivity(intent);
}
});
headphone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "headphone");
startActivity(intent);
}
});
laptop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "laptop");
startActivity(intent);
}
});
watches.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "watches");
startActivity(intent);
}
});
mobiles.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(), SellerAddNewProductActivity.class);
intent.putExtra("category", "mobile");
startActivity(intent);
}
});
}
} | [
"shahrin029@gmail.com"
] | shahrin029@gmail.com |
5443bafca713b97012eec208b7e7bbad62a5712d | 16cf261f53aa46593e21b58cce48f909f011a35d | /src/main/java/com/iwanvi/bookstore/admin/common/aspectj/lang/annotation/DataSource.java | db30bd8c39b25b3a23ceeadb44196db318747547 | [] | no_license | elevenhome/iwanvi-bookstore-manage-admin | 52601d181ae87234bd02ca3d4ab7df306d2d22d5 | fe556e9e917adf3f105229008ca60adba00b6bae | refs/heads/master | 2022-10-28T15:38:29.849637 | 2019-07-04T01:37:20 | 2019-07-04T01:37:20 | 195,149,587 | 0 | 0 | null | 2022-10-12T20:28:45 | 2019-07-04T01:37:09 | JavaScript | UTF-8 | Java | false | false | 622 | java | package com.iwanvi.bookstore.admin.common.aspectj.lang.annotation;
import com.iwanvi.bookstore.admin.common.aspectj.lang.enums.DataSourceType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author YDF
* @Description 自定义多数据源切换注解
* @Date 2019/3/12 0012 10:25
* @Version 1.0
**/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {
/**
* 切换数据源名称
*/
public DataSourceType value() default DataSourceType.MASTER;
}
| [
"去掉import处无用的;号"
] | 去掉import处无用的;号 |
ba31cf7303957a49b9d8f3d1ed1879bfc9d6911a | 6dd79c77afd586ada9927e86651a68071b665a11 | /src/main/java/com/lin/community/dao/DiscussPostMapper.java | f34f5b3ace0d978f2eb2a4668ffda30e7711b7c4 | [] | no_license | lanlingwang9099/llw-practice | deee7224effdca3987686ad0db8384e8aa932487 | 57c3243bbedf848d6ea3ee9e3b301ead1cd3922d | refs/heads/master | 2023-09-04T07:43:25.571184 | 2021-10-17T17:36:40 | 2021-10-17T17:36:40 | 418,185,434 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 526 | java | package com.lin.community.dao;
import com.lin.community.entity.DiscussPost;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface DiscussPostMapper {
List<DiscussPost> selectDiscussPosts(int userId,int offset,int limit); //offset 跳过的条数 limit 取多少条
//注解用于给参数起别名,动态sql里 如果<id>里只有一个参数,就必须起别名
int selectDiscussPostRows(@Param("userId") int userId);
}
| [
"1322417421@qq.com"
] | 1322417421@qq.com |
6b7c2fc8561ef743c5ca3bc32b2739608c78b420 | 94da9df747bef2db246f0cdeb20963f5a7fa09ba | /src/main/java/com/fox/skasafs_sys/entity/AGV_State.java | 01936e7d682ceba22df2f5641e41dd2f216d32c8 | [] | no_license | YTY11/KeyParameter | ae51ee4251751c22371b0d4efc9731e92a7209d9 | 5bb8055bb6c1a5b72b06e31d987ef52fcd3afa74 | refs/heads/master | 2023-03-24T10:58:15.875621 | 2021-03-15T14:34:01 | 2021-03-15T14:34:01 | 341,171,481 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,720 | java | package com.fox.skasafs_sys.entity;
import java.math.BigDecimal;
import java.util.Date;
public class AGV_State {
private BigDecimal id;
private String agv;
private String rfid;
private String task;
private String runstate;
private String speed;
private String abnormal;
private String batterystate;
private String state;
private String network;
private String workstation;
private Date updateTime;
private String floor;
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public String getAgv() {
return agv;
}
public void setAgv(String agv) {
this.agv = agv == null ? null : agv.trim();
}
public String getRfid() {
return rfid;
}
public void setRfid(String rfid) {
this.rfid = rfid == null ? null : rfid.trim();
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task == null ? null : task.trim();
}
public String getRunstate() {
return runstate;
}
public void setRunstate(String runstate) {
this.runstate = runstate == null ? null : runstate.trim();
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed == null ? null : speed.trim();
}
public String getAbnormal() {
return abnormal;
}
public void setAbnormal(String abnormal) {
this.abnormal = abnormal == null ? null : abnormal.trim();
}
public String getBatterystate() {
return batterystate;
}
public void setBatterystate(String batterystate) {
this.batterystate = batterystate == null ? null : batterystate.trim();
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state == null ? null : state.trim();
}
public String getNetwork() {
return network;
}
public void setNetwork(String network) {
this.network = network == null ? null : network.trim();
}
public String getWorkstation() {
return workstation;
}
public void setWorkstation(String workstation) {
this.workstation = workstation == null ? null : workstation.trim();
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getFloor() {
return floor;
}
public void setFloor(String floor) {
this.floor = floor == null ? null : floor.trim();
}
} | [
"862454711@qq.com"
] | 862454711@qq.com |
fa45276a96cec124819063f9d60576a5e866992a | 141da01a78056bff77a8a0bc449f0f8085dbb0bb | /Spring/src/main/java/com/web/spring4/bean/impl/JayChouAlbum.java | 6a2438c3bdb6b7a9ebbbe857f60c84ed7c375777 | [] | no_license | Garden12138/Spring4 | 61c237acc7c4d79f5a2ab36f57f4b092d8996984 | a27a6ac88c7d91ada4a3d130c4be1283a3f0f5e9 | refs/heads/master | 2021-09-14T21:47:11.239001 | 2018-05-20T10:38:17 | 2018-05-20T10:38:17 | 119,340,727 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,445 | java | package com.web.spring4.bean.impl;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import com.web.spring4.annotation.JCA;
import com.web.spring4.annotation._1;
import com.web.spring4.bean.CompactDisc;
import com.web.spring4.bean.condition.ChooseJayChouAlbum;
/**
* CD实现类-周杰伦专辑
* @author Garden
* 2018年3月5日
*/
@Component
//@Primary
//@Qualifier("JCA")
//@Qualifier("_1")
//@JCA
//@_1
public class JayChouAlbum implements CompactDisc{
private String songs[] = {"夜曲"};
private String artist = "周杰伦";
@Override
public void play() {
// TODO Auto-generated method stub
System.out.println("正在播放:"+ songs[0] + "-" +artist);
}
@Override
public void audiencePlay(String audienceName,int age){
System.out.println(age + "岁的" + audienceName + " 正在播放:"+ songs[0] + "-" +artist);
}
@Override
public List<String> getSongsList() {
// TODO Auto-generated method stub
return Arrays.asList(this.songs);
}
@Override
public void setSongsList(List<String> songsList) {
// TODO Auto-generated method stub
List<String> songs = Arrays.asList(this.songs);
songs.clear();
songs.addAll(songsList);
this.songs = (String[]) songs.toArray();
}
}
| [
"847686279@qq.com"
] | 847686279@qq.com |
ba0b30fd22356c3419307b086756d7c683ccab18 | 2cf1b02afc8280c669f2afb5a55908e671cdd147 | /src/main/java/com.malaganguo.athmsssm/model/TempAndHumModel.java | 79a5c73fa27708f876317e3a48ff05c42979d9cb | [] | no_license | malaganguo/athmsssm | 25c8aa7d27a8441d9d765ce0a5a89be26699ebc3 | d109c1a8776f755a182bafbaf00a48bdbb1a645d | refs/heads/master | 2022-02-10T13:05:57.292650 | 2019-05-09T03:24:54 | 2019-05-09T03:24:54 | 173,528,432 | 3 | 0 | null | 2022-02-07T06:50:16 | 2019-03-03T03:57:36 | JavaScript | UTF-8 | Java | false | false | 617 | java | package com.malaganguo.athmsssm.model;
public class TempAndHumModel {
private String date ;
private String temperature;
private String humidity;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
}
| [
"admin@admin.com"
] | admin@admin.com |
bc2cdc31751c7cc593906f9da1ae27687d1324ef | df68d757ffaa3ff375dc66da26b64b2e293364ff | /examples/camel-example-rest-swagger/src/main/java/org/apache/camel/example/RestSwaggerApplication.java | b4f63413d89c8595abbe843d0195bcc2e87970d0 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] | permissive | mondain/camel | e9f64e058996413377fe14f25dc824787eb4d671 | b5228be41c44caa2fc3e2f10d14961c4e95cf35e | refs/heads/master | 2023-08-23T07:49:16.779384 | 2019-10-18T13:58:46 | 2019-10-18T14:59:55 | 216,057,984 | 2 | 0 | Apache-2.0 | 2019-10-18T15:47:11 | 2019-10-18T15:47:11 | null | UTF-8 | Java | false | false | 2,504 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.camel.example;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.function.Function.identity;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class RestSwaggerApplication implements ApplicationRunner {
@Autowired
ApplicationContext context;
@Value("${operation:getInventory}")
String operation;
@Value("${swagger:http://petstore.swagger.io/v2/swagger.json}")
String specificationUri;
@Autowired
ProducerTemplate template;
@Override
public void run(final ApplicationArguments args) throws Exception {
final Predicate<String> operations = "operation"::equals;
final Map<String, Object> headers = args.getOptionNames().stream().filter(operations.negate())
.collect(Collectors.toMap(identity(), arg -> args.getOptionValues(arg).get(0)));
final String body = template.requestBodyAndHeaders("rest-swagger:" + specificationUri + "#" + operation, null,
headers, String.class);
System.out.println(body);
SpringApplication.exit(context, () -> 0);
}
public static void main(final String[] args) {
SpringApplication.run(RestSwaggerApplication.class, args);
}
}
| [
"zregvart@apache.org"
] | zregvart@apache.org |
22fc72f71745efc1296bf5406c390c9f5e4318af | 8abeb6c28cffeabc2abb34e09e4db8a1b468d2ff | /src/main/java/com/hq/myblog/Exception/CustomExceptionType.java | 73a2df65aa73c3ad1bdcef6fb29fbabc5124f3eb | [] | no_license | GOGOHQ/myblog | 35a4e437172f09c0495c17471e17b1096e646f13 | 4fc1b41a0bf73c67d43f3b207da95884a03dc5dd | refs/heads/master | 2022-10-21T15:49:20.602706 | 2020-06-14T13:54:17 | 2020-06-14T13:54:17 | 272,211,813 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 531 | java | package com.hq.myblog.Exception;
public enum CustomExceptionType{
USER_INPUT_ERROR(400,"用户输入异常"),
SYSTEM_ERROR (500,"系统服务异常"),
OTHER_ERROR(999,"其他未知异常");
CustomExceptionType(int code, String typeDesc) {
this.code = code;
this.typeDesc = typeDesc;
}
private String typeDesc;//异常类型中文描述
private int code; //code
public String getTypeDesc() {
return typeDesc;
}
public int getCode() {
return code;
}
} | [
"www.657473650@qq.com"
] | www.657473650@qq.com |
1c06ce270fecce078e000d11e473d26a9155372f | 6c2e8ea8d03a07d12303c8b2a54f826a2c92bdf9 | /assignment-battleship-game/ClassicEditionGUI.java | 75ded117c217c85d276d873bf3105bda428ac404 | [] | no_license | gentisaliu/lab-system-architecture | d5971c3c71ad28f59afb0c1f4234d18367d41ac6 | 03d3724c3311e4e893c0540a44e0f6a76ffe55c8 | refs/heads/master | 2021-01-22T08:38:05.087157 | 2017-05-28T01:15:48 | 2017-05-28T01:15:48 | 92,624,490 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,879 | java | import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ClassicEditionGUI extends JFrame implements ActionListener
{
private JPanel userInformation;
private JPanel networkConfiguration;
private JPanel buttonPanel;
private JLabel playerName;
private JTextField playerNameField;
private JLabel portNr;
private JTextField portNrField;
private JButton connectButton;
private JButton cancelButton;
private String hostname;
private String playername;
private int portNumber;
private Game gameData;
private Controller cont;
public ClassicEditionGUI()
{
setLayout(new FlowLayout());
userInformation = new JPanel();
userInformation.setLayout(new GridLayout(1, 1));
playerName = new JLabel("Player name:");
playerNameField = new JTextField("Player1");
playerNameField.setPreferredSize(new Dimension(100, 20));
userInformation.add(playerName);
userInformation.add(playerNameField);
networkConfiguration = new JPanel();
networkConfiguration.setLayout(new GridLayout(1, 1));
portNr = new JLabel("Port Nr.:");
portNrField = new JTextField("1111");
portNrField.setPreferredSize(new Dimension(100, 20));
networkConfiguration.add(portNr);
networkConfiguration.add(portNrField);
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
connectButton = new JButton("Wait for connection");
connectButton.addActionListener(this);
buttonPanel.add(connectButton);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
buttonPanel.add(cancelButton);
add(userInformation);
add(networkConfiguration);
add(buttonPanel);
setTitle("Battleship Options - Classic Edition");
setSize(250, 130);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void elaborateInput()
{
playername = playerNameField.getText();
portNumber = Integer.parseInt(portNrField.getText());
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == connectButton)
{
elaborateInput();
gameData = new Game(playername, 10, 10);
gameData.setDestroyers(1, -1);
gameData.setSubmarines(1, -1);
gameData.setBattleships(1, -1);
gameData.setAircraftCarriers(1, -1);
gameData.setShipRelocations(0);
gameData.setPlayerSide("host");
gameData.setMaximalShots(5);
cont = new Controller(1, 1, playerNameField.getText(), 0, 10, 10);
cont.setDestroyers(1, 1);
cont.setSubmarines(1, 1);
cont.setBattleships(1, 1);
cont.setAircraftCarriers(1, 1);
cont.useInfiniteAmmo(true);
cont.useBlitzkriegStrategy(true);
cont.setGameTimed(false);
cont.setGameEdition("classical");
cont.setMaximalShots(5);
ConnectionInProgress c = new ConnectionInProgress((JFrame) this, " ", portNumber, null, true, gameData, cont);
new Thread(c).run();
}
if(e.getSource() == cancelButton) System.exit(0);
}
} | [
"gentisaliu@gmail.com"
] | gentisaliu@gmail.com |
54d422f7052179f997b42c822cbeddc9f5f56f8f | 4358b6e584d99b43586349d0dbf15b24483bf0fe | /src/main/java/com/example/demo/controllers/PostController.java | 7143613aa636811cc12f6baad7b0a60e918caeb0 | [] | no_license | DushaBorisov/RestApiServiceForStudentMap | be5d390bb0f9e7facdc1ad4ad8826d2f48d665ad | 5867c31c20dfc8a2dc6bba9c14a4a371f02f42fb | refs/heads/master | 2023-02-03T17:01:20.558458 | 2020-11-23T20:02:01 | 2020-11-23T20:02:01 | 308,090,473 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,829 | java | package com.example.demo.controllers;
import com.example.demo.model.Post;
import com.example.demo.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class PostController {
private final PostService postService;
@Autowired
public PostController(PostService postService){
this.postService = postService;
}
// Создание нового поста
@PostMapping(value = "/posts")
public ResponseEntity<?> create(@RequestBody Post post){
postService.create(post);
return new ResponseEntity<>(HttpStatus.CREATED);
}
// Получить все имеющиеся в БД посты
@GetMapping(value = "/posts")
public ResponseEntity<List<Post>> read(){
final List<Post> posts = postService.readAll();
return posts != null && !posts.isEmpty()
? new ResponseEntity<>(posts, HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
// Получить все посты с указанным местом
@GetMapping(value = "/posts/name/{name}")
public ResponseEntity<List<Post>> findAllPostByPlace(@PathVariable(name = "name") String name){
final List<Post> posts= postService.getAllPostByPlace(name);
return (posts != null && !posts.isEmpty())
? new ResponseEntity<>(posts, HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
// Получить все посты с указанным логином
@GetMapping(value = "/posts/login/{login}")
public ResponseEntity<List<Post>> findAllPostByLogin(@PathVariable(name = "login") String login){
final List<Post> posts= postService.getAllPostByLogin(login);
return (posts != null && !posts.isEmpty())
? new ResponseEntity<>(posts, HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@PutMapping(value ="/posts/{id}")
public ResponseEntity<?> update(@PathVariable(name = "id") int id,
@RequestBody Post post){
final boolean update = postService.update(post,id);
return update
? new ResponseEntity<>(HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@DeleteMapping(value = "/posts/{id}")
public ResponseEntity<?> delete(@PathVariable(name = "id") int id){
final boolean delete = postService.delete(id);
return delete
? new ResponseEntity<>(HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
| [
"borisovandrey.work@gmail.com"
] | borisovandrey.work@gmail.com |
0850d52f36c524223e15d95a694da45f02f89dba | 824fc0c6edeaaa997e97e183317f6ca8dbc6147d | /src/main/java/strcrossover/FooCrossOverStrategy.java | bf7bc4b109943e3c997e700ed66f63c1bfbc39aa | [] | no_license | davgutavi/trlab-trigen | 2ab6bb49ac7fa40c106ce4a96db5203babc19e74 | 6788a17b49f79640b4270920e29d39a57c803d1a | refs/heads/master | 2022-12-21T13:22:34.642866 | 2022-12-16T08:47:34 | 2022-12-16T08:47:34 | 99,221,674 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 814 | java | package strcrossover;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import algcore.AlgorithmIndividual;
import algutils.TriclusterUtilities;
import crossovers.CrossoverStrategy;
public class FooCrossOverStrategy implements CrossoverStrategy {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(FooCrossOverStrategy.class);
public AlgorithmIndividual[] cross(AlgorithmIndividual father, AlgorithmIndividual mother, String individualClassName) {
AlgorithmIndividual[] r = new AlgorithmIndividual[2];
AlgorithmIndividual son1 = TriclusterUtilities.getInstance().
buildIndividual(father.getGenes(),father.getSamples(),father.getTimes(),
individualClassName,"from crossover: foo");
r[0] = son1;
return r;
}
} | [
"davgutavi@gmail.com"
] | davgutavi@gmail.com |
9c867961c7d6f5e980c8c0dee4939db92bdfb409 | 1de2721fda45d5ac71547eda0ab912ddb5855b5e | /android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorOperatorsFragment.java | d8672c65daa9a0558b6a28feb46e11780bdb1fad | [] | no_license | GeekyTrash/android-calculatorpp | d0039cb3fd33cb8df3cf916deec34bfdb656ae0f | 73bcbde57bbe21121b7baac29ee06667560bd383 | refs/heads/master | 2020-12-25T03:10:30.856463 | 2013-04-01T09:08:05 | 2013-04-01T09:08:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,473 | java | package org.solovyev.android.calculator.math.edit;
import android.app.Activity;
import android.content.Context;
import android.text.ClipboardManager;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.CalculatorEventType;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.menu.AMenuItem;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* User: serso
* Date: 11/17/11
* Time: 1:53 PM
*/
public class CalculatorOperatorsFragment extends AbstractMathEntityListFragment<Operator> {
public CalculatorOperatorsFragment() {
super(CalculatorFragmentType.operators);
}
@Override
protected AMenuItem<Operator> getOnClickAction() {
return LongClickMenuItem.use;
}
@NotNull
@Override
protected List<LabeledMenuItem<Operator>> getMenuItemsOnLongClick(@NotNull Operator item) {
final List<LabeledMenuItem<Operator>> result = new ArrayList<LabeledMenuItem<Operator>>(Arrays.asList(LongClickMenuItem.values()));
if ( StringUtils.isEmpty(OperatorDescriptionGetter.instance.getDescription(this.getActivity(), item.getName())) ) {
result.remove(LongClickMenuItem.copy_description);
}
return result;
}
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return OperatorDescriptionGetter.instance;
}
@NotNull
@Override
protected List<Operator> getMathEntities() {
final List<Operator> result = new ArrayList<Operator>();
result.addAll(Locator.getInstance().getEngine().getOperatorsRegistry().getEntities());
result.addAll(Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getEntities());
return result;
}
@Override
protected String getMathEntityCategory(@NotNull Operator operator) {
String result = Locator.getInstance().getEngine().getOperatorsRegistry().getCategory(operator);
if (result == null) {
result = Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getCategory(operator);
}
return result;
}
private static enum OperatorDescriptionGetter implements MathEntityDescriptionGetter {
instance;
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
String result = Locator.getInstance().getEngine().getOperatorsRegistry().getDescription(mathEntityName);
if (StringUtils.isEmpty(result)) {
result = Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getDescription(mathEntityName);
}
return result;
}
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static enum LongClickMenuItem implements LabeledMenuItem<Operator> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_operator, data);
}
},
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
final String text = OperatorDescriptionGetter.instance.getDescription(context, data.getName());
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}
};
private final int captionId;
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}
}
| [
"se.solovyev@gmail.com"
] | se.solovyev@gmail.com |
9590bdbd351b096ae3d0b2b6cd11168f2bee5ccc | 34c10d100a0819ab9b3975ff526252f16f1c2ffa | /app/src/main/java/com/krisoflies/lilbudgeteer/model/CategoryListContent.java | 5fa2bb9cb16a0173d4489ad0e1d42b13f5a467c1 | [] | no_license | willypf/LilBudgeteer-master | 8c7d1fcea05bf0931016fc084f4432aafc6914aa | 72c9066205c1c72baef1429fede5a70c6401455c | refs/heads/master | 2020-05-17T10:53:17.910098 | 2015-07-11T07:57:18 | 2015-07-11T07:57:18 | 38,909,232 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,497 | java | package com.krisoflies.lilbudgeteer.model;
import com.krisoflies.lilbudgeteer.controller.TransactionManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/* Created by Paolo on 3/13/2015. */
public class CategoryListContent {
public static List<CategoryItem> ITEMS = new ArrayList<>();
public static Map<Integer, CategoryItem> ITEM_MAP = new HashMap<>();
public CategoryListContent(String path) {// Aqui se adhieren los usos unicos y basicos de la aplicacion.
List<String> categories = TransactionManager.obtainCategories(path);
for (int i = 0; i < categories.size(); i++)
addItem(new CategoryItem(i + 1, categories.get(i)));
}
private static void addItem(CategoryItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.getId(), item);
}
public static class CategoryItem {
private int id;
private String content;
public CategoryItem(int id, String content) {
this.setId(id);
this.setContent(content);
}
@Override
public String toString() {
return getContent();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
}
| [
"willypf21@hotmail.com"
] | willypf21@hotmail.com |
08f439a1f6c6e2248b15bdbdacb773610a5e97d6 | d9f9740c81bbfbbdcffcd3e51cb0623f38c284c1 | /src/com/ken/bookingview/BookingProvider.java | b12e145c80d30efb9ebe3ccf04e30e1bf90485e2 | [] | no_license | cKcK18/bookingRecord | 9bf56feba9159c74fc151d1f41659ea8dc847a88 | 0c7bdd18ceef3a03f86448761329395d05ec7618 | refs/heads/master | 2021-01-23T02:48:47.157403 | 2014-09-23T07:32:33 | 2014-09-23T07:32:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,396 | java | /*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.ken.bookingview;
import java.io.File;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
public class BookingProvider extends ContentProvider {
private static final String TAG = BookingProvider.class.getSimpleName();
private static final boolean LOGD = true;
private static final String DATABASE_NAME = "booking.db";
private static final int DATABASE_VERSION = 1;
static final String AUTHORITY = "com.ken.bookingview";
static final String TABLE_NAME = "booking";
static final String PARAMETER_NOTIFY = "notify";
static final String COLUMN_ID = "_id";
static final String COLUMN_NAME = "name";
static final String COLUMN_YEAR = "year";
static final String COLUMN_MONTH = "month";
static final String COLUMN_DATE = "date";
static final String COLUMN_HOUR = "hour";
static final String COLUMN_MINUTE = "minute";
static final String COLUMN_PHONE_NUMBER = "phoneNumber";
static final String COLUMN_SERVICE_ITEMS = "serviceItems";
static final String COLUMN_REQUIRED_TIME = "requiredTime";
private long mLastID = -1;
/**
* The content:// style URL for this table
*/
static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME + "?" + PARAMETER_NOTIFY
+ "=true");
/**
* The content:// style URL for this table. When this Uri is used, no notification is sent if the content changes.
*/
static final Uri CONTENT_URI_NO_NOTIFICATION = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME + "?"
+ PARAMETER_NOTIFY + "=false");
private DatabaseHelper mOpenHelper;
@Override
public boolean onCreate() {
mOpenHelper = new DatabaseHelper(getContext());
// open to read and write
mOpenHelper.getWritableDatabase();
// set a reference to outer
((BookingApplication) getContext()).setBookingProvider(this);
return true;
}
@Override
public String getType(Uri uri) {
SqlArguments args = new SqlArguments(uri, null, null);
if (TextUtils.isEmpty(args.where)) {
return "vnd.android.cursor.dir/" + args.table;
} else {
return "vnd.android.cursor.item/" + args.table;
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(args.table);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
result.setNotificationUri(getContext().getContentResolver(), uri);
if (mLastID == -1) {
mLastID = getLastID(result);
}
return result;
}
private long getLastID(Cursor cursor) {
int lastID = -1;
if (cursor == null || cursor.getCount() == 0) {
return lastID;
}
final boolean succeeded = cursor.moveToLast();
if (succeeded) {
final int idIndex = cursor.getColumnIndexOrThrow(BookingProvider.COLUMN_ID);
lastID = cursor.getInt(idIndex);
}
return lastID;
}
public long generateNewId() {
if (mLastID < 0) {
throw new RuntimeException("Error: last id was not initialized");
}
mLastID += 1;
return mLastID;
}
private static long dbInsertAndCheck(DatabaseHelper helper, SQLiteDatabase db, String table, String nullColumnHack,
ContentValues values) {
if (!values.containsKey(BaseColumns._ID)) {
throw new RuntimeException("Error: attempting to add item without specifying an id");
}
return db.insert(table, nullColumnHack, values);
}
@Override
public Uri insert(Uri uri, ContentValues initialValues) {
if (LOGD) Log.d(TAG, String.format("[insert] uri: %s. cv: %s", uri.toString(), initialValues));
SqlArguments args = new SqlArguments(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
if (rowId <= 0) return null;
uri = ContentUris.withAppendedId(uri, rowId);
sendNotify(uri);
return uri;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
if (LOGD) Log.d(TAG, String.format("[bulkInsert] uri: %s", uri.toString()));
SqlArguments args = new SqlArguments(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
int numValues = values.length;
for (int i = 0; i < numValues; i++) {
if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
return 0;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
sendNotify(uri);
return values.length;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if (LOGD) Log.d(TAG, String.format("[delete] uri: %s", uri.toString()));
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count = db.delete(args.table, args.where, args.args);
if (count > 0) sendNotify(uri);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
if (LOGD) Log.d(TAG, String.format("[update] uri: %s", uri.toString()));
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count = db.update(args.table, values, args.where, args.args);
if (count > 0) sendNotify(uri);
return count;
}
private void sendNotify(Uri uri) {
String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
if (notify == null || "true".equals(notify)) {
getContext().getContentResolver().notifyChange(uri, null);
}
}
public void deleteDatabase() {
// Are you sure? (y/n)
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final File dbFile = new File(db.getPath());
mOpenHelper.close();
if (dbFile.exists()) {
SQLiteDatabase.deleteDatabase(dbFile);
}
mOpenHelper = new DatabaseHelper(getContext());
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
if (LOGD) Log.d(TAG, "creating new booking database");
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME + " TEXT NOT NULL," +
COLUMN_YEAR + " INTEGER NOT NULL," +
COLUMN_MONTH + " INTEGER NOT NULL," +
COLUMN_DATE + " INTEGER NOT NULL," +
COLUMN_HOUR + " INTEGER NOT NULL," +
COLUMN_MINUTE + " INTEGER NOT NULL," +
COLUMN_PHONE_NUMBER + " TEXT NOT NULL," +
COLUMN_SERVICE_ITEMS + " TEXT NOT NULL," +
COLUMN_REQUIRED_TIME + " TEXT NOT NULL" +
");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (LOGD) Log.d(TAG, "onUpgrade triggered");
}
}
/**
* Build a query string that will match any row where the column matches anything in the values list.
*/
static String buildOrWhereString(String column, int[] values) {
StringBuilder selectWhere = new StringBuilder();
for (int i = values.length - 1; i >= 0; i--) {
selectWhere.append(column).append("=").append(values[i]);
if (i > 0) {
selectWhere.append(" OR ");
}
}
return selectWhere.toString();
}
static class SqlArguments {
public final String table;
public final String where;
public final String[] args;
SqlArguments(Uri url, String where, String[] args) {
if (url.getPathSegments().size() == 1) {
this.table = url.getPathSegments().get(0);
this.where = where;
this.args = args;
} else if (url.getPathSegments().size() != 2) {
throw new IllegalArgumentException("Invalid URI: " + url);
} else if (!TextUtils.isEmpty(where)) {
throw new UnsupportedOperationException("WHERE clause not supported: " + url);
} else {
this.table = url.getPathSegments().get(0);
this.where = "_id=" + ContentUris.parseId(url);
this.args = null;
}
}
SqlArguments(Uri url) {
if (url.getPathSegments().size() == 1) {
table = url.getPathSegments().get(0);
where = null;
args = null;
} else {
throw new IllegalArgumentException("Invalid URI: " + url);
}
}
}
}
| [
"ken.chen@movial.com"
] | ken.chen@movial.com |
4191e50f0c3eb49c531a74790ab1e0ab9f6708c4 | b52806c5f3439ac8cce3545a4f0a14edfde28ec3 | /link-shorter/src/main/java/com/linkshorter/demo/controller/ShortUrlController.java | e00e0c724ef1752126041414ec1d25f90c7c8829 | [] | no_license | numenshane/link_shorter | 54f145920a064f1544677d0a969efb0ff68057f5 | 3a9474670dc676cc8a1cd3f10e16f4fdcb6dc0dd | refs/heads/master | 2022-12-03T14:39:18.311505 | 2020-08-28T03:52:03 | 2020-08-28T03:52:03 | 289,261,811 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,718 | java | package com.linkshorter.demo.controller;
import com.linkshorter.demo.URLUtils;
import com.linkshorter.demo.repository.DynamoDBRepository;
import com.linkshorter.demo.service.ShortUrlService;
import com.linkshorter.demo.utils.ShortUrlGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.List;
@RestController
@RequestMapping("/")
public class
ShortUrlController {
@Autowired
private ShortUrlService shortUrlService;
@RequestMapping(value = "/{resource_Id}/**", method = RequestMethod.GET)
public ResponseEntity getShortUrl(@PathVariable("resource_Id") String resourceId, HttpServletResponse response) throws IOException {
String sourceUrl = shortUrlService.getSourceUrlByResourceId(resourceId);
if (sourceUrl == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
response.sendRedirect(sourceUrl);
return ResponseEntity.ok().build();
}
@RequestMapping(value = "/api/v1/source_url/{source_url}/**", method = RequestMethod.POST)
public ResponseEntity createShortUrlIfNeeded(@PathVariable("source_url") String sourceUrl, HttpServletRequest request) throws UnknownHostException {
final String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
final String bestMatchingPattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
String arguments = new AntPathMatcher().extractPathWithinPattern(bestMatchingPattern, path);
String url = "";
String domain = "";
String suffix = "";
url = handleArguments(sourceUrl, arguments);
if (URLUtils.isURL(url)) {
domain = arguments.split("/")[0];
suffix = arguments.substring(domain.length(), arguments.length());
} else {
return ResponseEntity.status(500).body("url is invalid");
}
domain = addProtocolToDomain(sourceUrl, domain);
return ResponseEntity.ok(shortUrlService.createShortUrlIfNeeded(domain, suffix, url, request));
}
private String addProtocolToDomain(String sourceUrl, String domain) {
if (("http:").equals(sourceUrl) || sourceUrl.equals("https:")) {
domain = sourceUrl + "//" + domain;
} else {
domain = "http://" + sourceUrl;
}
return domain;
}
private String handleArguments(String sourceUrl, String arguments) {
String url;
if (!arguments.isEmpty()) {
if (("http:").equals(sourceUrl) || sourceUrl.equals("https:")) {
url = sourceUrl + "//" + arguments;
} else {
url = "http://" + sourceUrl + '/' + arguments;
}
} else {
url = "http://" + sourceUrl;
}
return url;
}
}
| [
"root@ip-172-31-37-158.ap-southeast-1.compute.internal"
] | root@ip-172-31-37-158.ap-southeast-1.compute.internal |
0345d2acc19465b70ae31f16b6b1b362904224d2 | 707ca65514667ffed161b06d327edefd62bd4a61 | /src/Controller.java | 1ce1141da19bc73a2d88f0999b80f47c3d8a8989 | [] | no_license | hani1206/123180141_MVC_A | 962d92cdfdaaf9af9504a74fa11193a29d3c628b | d47bf1b4223e2b4b258948e7598954a5781044d9 | refs/heads/master | 2022-04-15T10:36:27.063052 | 2020-04-12T11:53:52 | 2020-04-12T11:53:52 | 255,071,938 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,493 | java | import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
public class Controller implements ActionListener{
Model model;
View view;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
if (model.getBanyakData() != 0){
String data[][] = model.read();
view.table.setModel(new JTable(data, view.namaKolom).getModel());
updateDataCombo(model.readNim());
} else {
JOptionPane.showMessageDialog(null, "Data Masih Kosong");
}
view.btnInsert.addActionListener(this);
view.btnReset1.addActionListener(this);
view.btnUpdate.addActionListener(this);
view.btnReset2.addActionListener(this);
view.table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
int baris = view.table.getSelectedRow();
int kolom = view.table.getSelectedColumn();
String data = view.table.getValueAt(baris, 0).toString();
int input = JOptionPane.showConfirmDialog(null,
"Apa Anda Ingin Menghapus Data " + data + " ?",
"Pilih Opsi..." , JOptionPane.YES_NO_OPTION);
if (input == 0){
model.delete(data);
String newData[][] = model.read();
view.table.setModel(new JTable(newData, view.namaKolom).getModel());
updateDataCombo(model.readNim());
}
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == view.btnInsert) {
String nim = view.getNim();
String nama = view.getNama();
String alamat = view.getAlamat();
if (nim.equals("")){
JOptionPane.showMessageDialog(null, "Nim Tidak Boleh Kosong");
} else if (nim.length() != 9){
JOptionPane.showMessageDialog(null, "Nim Harus 9 Digit");
} else {
model.insert(nim, nama, alamat);
String newData[][] = model.read();
view.table.setModel(new JTable(newData, view.namaKolom).getModel());
updateDataCombo(model.readNim());
}
} else if (e.getSource() == view.btnReset1){
view.tfNim.setText("");
view.tfNama.setText("");
view.tfAlamat.setText("");
} else if (e.getSource() == view.btnUpdate){
String nim = view.getNimCombo();
String nama = view.getNama2();
String alamat = view.getAlamat2();
if (nama.equals("") || alamat.equals("")){
JOptionPane.showMessageDialog(null, "Form Tidak Boleh Kosong");
} else {
model.update(nim, nama, alamat);
String newData[][] = model.read();
view.table.setModel(new JTable(newData, view.namaKolom).getModel());
updateDataCombo(model.readNim());
}
} else if (e.getSource() == view.btnReset2){
view.tfNama2.setText("");
view.tfAlamat2.setText("");
}
}
public void updateDataCombo(ArrayList<String> data){
view.daftarNim.removeAllItems();
for (String item : data) {
view.daftarNim.addItem(item);
}
}
} | [
"55271058+hani1206@users.noreply.github.com"
] | 55271058+hani1206@users.noreply.github.com |
137f37ca9d40f603dbb106e05a697df916747af6 | a6161964d68b2797c6d46123f440147e084f5245 | /src/com/onebit/hackjack/entity/Urusan.java | fd01bd9ef395218487afefbfa6f5c6363ed30940 | [] | no_license | virgiawan/HackJakSDK | b88fa0352459380f3193f8d52aac9211f56a6236 | 515f4e4f60cbdce43c91b844f3a8e7fc4b565d96 | refs/heads/master | 2016-09-11T09:03:47.670708 | 2014-04-17T13:49:33 | 2014-04-17T13:49:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 539 | java | package com.onebit.hackjack.entity;
import java.io.Serializable;
public class Urusan implements Serializable {
// define attribute
private static final long serialVersionUID = 56;
private String urusan;
private String namaUrusan;
// define getter
public String getUrusan() {
return urusan;
}
public String getNamaUrusan() {
return namaUrusan;
}
// define setter
public void setUrusan(String urusan) {
this.urusan = urusan;
}
public void setNamaUrusan(String namaUrusan) {
this.namaUrusan = namaUrusan;
}
}
| [
"virgiawan.huda.akbar@gmail.com"
] | virgiawan.huda.akbar@gmail.com |
a1cf7cb325defead31b50647e8117746495b01d2 | 6c3b114423c053f08a5496b2517fb8a655dce735 | /src/main/java/com/codecool/WorkerAnt.java | a53b7969f33ee53e49e89e483f49b8634d256573 | [] | no_license | CodecoolMSC2017/ant-colony-csanadH | 44393f29d6a155564e4f2bc6936c4f82bfcd27cd | e5c4e1e2f93d269b5a4349c290d0d62391382b3d | refs/heads/master | 2021-01-24T12:12:11.992896 | 2018-02-27T12:17:11 | 2018-02-27T12:17:11 | 123,124,748 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 572 | java | package com.codecool;
import java.util.Random;
public class WorkerAnt extends Ant {
private Random rand = new Random();
public WorkerAnt(int x, int y) {
super(x, y);
}
public void move() {
int randStep = rand.nextInt(4);
switch (randStep) {
case 0:
x += 1;
break;
case 1:
x -= 1;
break;
case 2:
y += 1;
break;
case 3:
y -= 1;
break;
}
}
}
| [
"hegedus.csanad96@gmail.com"
] | hegedus.csanad96@gmail.com |
6bc612b9c6d4df37b84c7a23628b6478fe3277a4 | 3dfc5ed8c92aa67ff052d98f953a9a83efd7f6b2 | /src/main/java/com/springbootsandbox/demo/domain/Customer.java | 116c9750c26591fb49b2c9e337fba18a3eead147 | [] | no_license | mattlukes/springbootsandbox-demo | 9bd9f5a6207af02b65784f520b8668ca35430fc4 | 8e4d6f4120755a75814e64aca637f3a9b69cff91 | refs/heads/master | 2020-09-12T03:43:57.636658 | 2019-11-24T19:27:08 | 2019-11-24T19:27:08 | 222,293,021 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 989 | java | package com.springbootsandbox.demo.domain;
import org.springframework.data.annotation.Id;
public class Customer {
@Id
public String id;
public String firstName;
public String lastName;
public Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
| [
"lukes.matthew@gmail.com"
] | lukes.matthew@gmail.com |
1c0103312b0823df7f1738d909e2ac4922e20624 | c7dcf2515dd3b6d24ba523add77ca0a2f7b66b62 | /culc/culcModels/culcFLQC.java | 75fb05a90b3c7efc711c4ccc980d7e25aae411e3 | [] | no_license | violinW/DoubtInvestigation | 460aabf79040e919bd62a048e3a2b1d9855d8c0e | 22ee2f82c31a74160a91bc0fbe0f72076ac2ed70 | refs/heads/master | 2021-09-06T11:47:52.058687 | 2018-02-06T07:02:35 | 2018-02-06T07:02:35 | 108,626,405 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,992 | java | package culcModels;
public class culcFLQC {
public static double initPut = 100000; //车款
public static double TG = 15000; //团购款
public static double initCloudBill = 100000 + 15000;
public static int initDays = (int)(365*4.6);
public static double initMadeMoney = 0;
public static double rate = 0.15;
public static double cushRate = 1;
public static double cushDays = 30;
public static int i = 1;
public static void main(String[] Args) {
dtType data = culcProfite(initDays, initCloudBill, initMadeMoney, 0, 0);
System.out.println("remainCloudBill: " + data.remainCloudBill + ", madeMoney: " + data.madeMoney + ", cash: " + data.cash);
}
public static dtType culcProfite(int days, double remainCloudBill, double madeMoney, double cash, double lastMadeCush) {
dtType dt = new dtType();
dt.remainCloudBill = remainCloudBill;
dt.madeMoney = madeMoney+ remainCloudBill * 0.0005 * 0.88;
dt.cash = cash;
days--;
double d = (float)(initDays - days)/cushDays;
if((int)d == d & d > 0) {
double canCush = Math.floor(dt.madeMoney/100)*100;
dt.cash = cash + canCush*cushRate-initPut*0.00015*30;
dt.remainCloudBill = dt.remainCloudBill + Math.floor(dt.remainCloudBill/100)*100*0.01 - dt.madeMoney/0.88 + canCush*(1-cushRate)/rate;
dt.madeMoney = dt.madeMoney - canCush;
System.out.println("remainCloudBill round " + (int)d + ": " + dt.remainCloudBill + ", canCush: " + canCush + ", 使用云付通现金: " + dt.cash + ", 用户现金: " + (1800*((int)d)+initPut*0.00015*30)+ ", 风险金额: " + (((initPut-(1800+initPut*0.00015*30)*((int)d))/initPut) *15000-dt.cash)+ ", madeBill: "+ remainCloudBill*0.01);
if(dt.cash >= initPut && i > 0) {
System.out.println("回本:" + dt.cash);
i--;
}
}
if(days > 0) {
return culcProfite(days, dt.remainCloudBill, dt.madeMoney, dt.cash, lastMadeCush);
}else {
return dt;
}
}
public static class dtType{
double remainCloudBill;
double madeMoney;
double cash;
}
}
| [
"violin@romenscd.cn"
] | violin@romenscd.cn |
18c15f20a0b89dfaf61084450d0afb32b1ec55ce | 9c3316a2d933fb87314d4e37152502d666592ed5 | /CoreJavaInterviewPractice/src/Strings/package-info.java | 4c20e8f3ae4d3b48a919c6b8e559f23913b833ea | [] | no_license | sohamKulkarni730/coreJavaWorkout | 7f6e42c865e5a8b501ac41687f569af69c8bbbc2 | 0c6d6950d0c5eeba8e0b7c0e51a27295e2a896e4 | refs/heads/master | 2020-06-24T21:42:53.015737 | 2019-12-21T05:18:48 | 2019-12-21T05:18:48 | 199,100,084 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 55 | java | /**
*
*/
/**
* @author AMOD
*
*/
package Strings; | [
"sohamkulkarni730@hotmail.com"
] | sohamkulkarni730@hotmail.com |
0b6d3da52b4d75b39d6d5e882b80c422f4b6df67 | 94d6347825838f82ad843c0479781b4a183eab46 | /src/guestbookVo/GuestBookVo.java | b32137493da6f4a2ccf61ebbe3d0eb806c8f5919 | [] | no_license | seula90/guestbook2 | 1089702c918f00695ef70c9e6654ea395795479f | 716c30c81ce442a375f6cc9eeb08375c815703d0 | refs/heads/master | 2016-09-05T20:04:21.055256 | 2015-05-07T08:42:31 | 2015-05-07T08:42:31 | 35,208,858 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 651 | java | package guestbookVo;
public class GuestBookVo {
private Long no;
private String name;
private String pwd;
private String msg;
private String date;
public Long getNo() {
return no;
}
public void setNo(Long no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
| [
"sra.park@samsung.com"
] | sra.park@samsung.com |
46d40566c34b2485b08581b977238e8f427901ba | 0717b59e180514cb944fe39d6356a1a08fc35b3e | /src/main/java/pl/coderslab/charity/controller/admin/CategoryController.java | 5cbae1be3188c979278730b47f42b6a6eac74843 | [] | no_license | FranciszekGrobelny/charitySite- | 19e769436581f966ac10ef77650bd826c35ab4eb | c994fca82db57db25711f192871f044f344c6c08 | refs/heads/master | 2022-11-18T06:50:13.227508 | 2020-07-13T11:29:07 | 2020-07-13T11:29:07 | 276,181,645 | 2 | 0 | null | 2020-07-13T11:29:09 | 2020-06-30T18:44:31 | Java | UTF-8 | Java | false | false | 1,644 | java | package pl.coderslab.charity.controller.admin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import pl.coderslab.charity.model.Category;
import pl.coderslab.charity.repository.CategoryRepository;
import java.util.List;
@RestController
@RequestMapping("/api/categories")
public class CategoryController {
private final CategoryRepository categoryRepository;
public CategoryController(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
}
@ApiOperation(value = "get all categories")
@GetMapping
public List<Category> getAllCategories(){
return categoryRepository.findAll();
}
@ApiOperation(value = "save category")
@PostMapping
public void createCategory(Category category){
categoryRepository.save(category);
}
@ApiOperation(value = "get category by id")
@GetMapping("/{id}")
public Category getSelectedCategory(@PathVariable Long id){
return categoryRepository.getOne(id);
}
@ApiOperation(value = "update category with specific id")
@PutMapping("/{id}")
public void updateCategory(@PathVariable Long id,
Category category ){
Category savedCategory = categoryRepository.getOne(id);
savedCategory.setName(category.getName());
categoryRepository.save(savedCategory);
}
@ApiOperation(value = "delete category by id")
@DeleteMapping("/{id}")
public void deleteCategory(@PathVariable Long id){
categoryRepository.deleteById(id);
}
}
| [
"franciszekgrobelny@gmail.com"
] | franciszekgrobelny@gmail.com |
1cb08987e931f08acf5a175a3577c3ad4c886c66 | 6cf7e828be882cbb7ec677257f1bf25692e1dd16 | /src/test/java/com/rkb/SpringBootConfigMicroservicesConfigurationApplicationTests.java | 370462916ff64e6415fe430dc0f8165a35c8b7f8 | [] | no_license | ramkbhattarai/MicroservicesConfiguration | 2a4d9b3b44fa967cac257f8513fccc3093eb917a | 511193b7c6b2942623c12865dac382e7094d1996 | refs/heads/master | 2021-03-18T07:45:59.242941 | 2020-03-13T12:12:11 | 2020-03-13T12:12:11 | 247,058,187 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 235 | java | package com.rkb;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringBootConfigMicroservicesConfigurationApplicationTests {
@Test
void contextLoads() {
}
}
| [
"ramkb466@gmail.com"
] | ramkb466@gmail.com |
0b620100209b807e75d75814018bfa62d34e4839 | 3d5923392d5ac8b376057ce07a25d1f441ac1453 | /src/com/alibaba/leetcode/middle/RemoveNthNodeFromEndOfListSolution.java | 64a0b5c9d242778a0a2a65058950b9a26d5e868a | [] | no_license | foolishboy66/LeetCode | 38047cf98ff9734e4941b847ee54a0e630e60aa1 | 739ec3be60f525d88773def405c601822ce5ba22 | refs/heads/master | 2021-06-18T01:52:24.116604 | 2021-03-21T16:00:14 | 2021-03-21T16:00:14 | 192,761,820 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,618 | java | package com.alibaba.leetcode.middle;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.leetcode.struct.ListNode;
import com.alibaba.leetcode.utils.ConvertUtils;
/**
* Given a linked list, remove the n-th node from the end of list and return its head.
*
* Example:
*
* Given linked list: 1->2->3->4->5, and n = 2.
*
* After removing the second node from the end, the linked list becomes 1->2->3->5. Note:
*
* Given n will always be valid.
*
* Follow up:
*
* Could you do this in one pass?
*
*
* @author wang
* @date 2019/07/03
*/
public class RemoveNthNodeFromEndOfListSolution {
public static void main(String[] args) {
ListNode node = new ListNode(1);
node.next = new ListNode(2);
node.next.next = new ListNode(3);
node.next.next.next = new ListNode(4);
node.next.next.next.next = new ListNode(5);
System.out.println(ConvertUtils.listNodeToStr(node));
System.out
.println(ConvertUtils.listNodeToStr(new RemoveNthNodeFromEndOfListSolution().removeNthFromEnd(node, 1)));
}
public ListNode removeNthFromEnd(ListNode head, int n) {
List<ListNode> list = new ArrayList<>();
ListNode node = head;
while (node != null) {
list.add(node);
node = node.next;
}
if (n == list.size()) {
// 第一个
return head.next;
}
ListNode delNode = list.get(list.size() - n);
ListNode preNode = list.get(list.size() - n - 1);
preNode.next = delNode.next;
return head;
}
}
| [
"835948617@qq.com"
] | 835948617@qq.com |
eafe7248a92d1e075bb5c62a6a475e92d532f925 | 92e04ad0c726ec84ef491c18447b383978360be9 | /SewMatchMaker/src/com/stfx/cli/sew/owl/vocubulary/Owl.java | 39faf5f83fbbf711a79648975699684dfa86db18 | [] | no_license | x2013ici/Sew | 167d74c670dddda268645e85a4808281f8e53c1c | af667d6246a92db12295daf1b332fae7f470f8ec | refs/heads/master | 2021-01-10T01:16:46.883929 | 2015-09-25T03:55:26 | 2015-09-25T03:55:26 | 43,106,867 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,683 | java | package com.stfx.cli.sew.owl.vocubulary;
import java.net.URI;
import com.stfx.cli.sew.owl.EntityFactory;
import com.stfx.cli.sew.owl.OwlClass;
import com.stfx.cli.sew.utilities.UriUtils;
/**
*
* @author Mostafijur Rahman
*
*/
public class Owl {
public final static String ns = "http://www.w3.org/2002/07/owl#";
public final static URI getURI() { return URI.create(ns); }
public final static OwlClass Thing =
EntityFactory.createClass(UriUtils.createURI(ns + "Thing"));
public final static OwlClass Nothing =
EntityFactory.createClass(UriUtils.createURI(ns + "Nothing"));
public final static URI versionInfo = URI.create(ns + "versionInfo");
public final static URI backwardCompatibleWith = URI.create(ns + "backwardCompatibleWith");
public final static URI priorVersion = URI.create(ns + "priorVersion");
public final static URI incompatibleWith = URI.create(ns + "incompatibleWith");
public final static URI sameAs = URI.create(ns + "sameAs");
public final static URI differentFrom = URI.create(ns + "differentFrom");
public final static URI bottomDataProperty = URI.create(ns + "BottomDataProperty");
public final static URI bottomObjectProperty = URI.create(ns + "BottomObjectProperty");
public final static URI topDataProperty = URI.create(ns + "TopDataProperty");
public final static URI topObjectProperty = URI.create(ns + "owl:TopObjectProperty");
public final static OwlClass Ontology =
EntityFactory.createClass(UriUtils.createURI(ns + "Ontology"));
public final static URI imports = URI.create(ns + "imports");
public final static URI inverseOf = URI.create(ns + "inverseOf");
}
| [
"mail.mostafij@gmail.com"
] | mail.mostafij@gmail.com |
a7057837d433f495f3b89419ab894b3957dde58f | 445d3e96f601d1b21993cd443d2f4d069952a672 | /KindelConnect/src/main/java/com/mycompany/kindelconnect/ProfesseurController.java | 278be611f4a2cd2e4492b86d7cc8ef90a1aa5f84 | [] | no_license | rachidoubahmane99/Kindel | 69a7cb2d472904d5dadc26f4e50abb1689142cd4 | b92f5ccef6bb4ceaea7ee2e2cd59194f53459702 | refs/heads/main | 2023-05-27T01:45:00.618635 | 2021-05-31T20:26:17 | 2021-05-31T20:26:17 | 356,692,310 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,475 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.kindelconnect;
import DbConnection.DbConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author rachid dev
*/
public class ProfesseurController {
Connection con = null;
public Statement stmt;
public ProfesseurController(){
}
public boolean verefierCompteProfesseur(String cin,String mdp) throws SQLException {
con = DbConnection.getConnection();
stmt = con.createStatement();
//String sql = "SELECT * FROM personne Where cin = ? and password = ?";
String query="select * from professeur where cin='"+cin+"' and password= '"+mdp+"' ";
ResultSet rs=stmt.executeQuery(query);
//LinkedList<Livre> livres= new LinkedList<Livre> ();
try {
if (!rs.next()) {
System.out.println("failed");
return false;
} else {
System.out.println("succesfully connected");
return true ;
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return true;
}
}
| [
"rachidoubahman99@gmail.com"
] | rachidoubahman99@gmail.com |
7d39fc20ef1d604a1bc69805c9005f7bdebd58ee | 97c8f17f7cb6dd25cea81669869f80c3a58e3bcc | /src/main/java/jhs/lc/geom/ParametricTransitFunctionSource.java | 295ca7e644de39573d34645e7eb137ca81e81cf6 | [
"Apache-2.0"
] | permissive | trippsapientae/sim-transit-lc | 070620f46ae4779994282a174447dcadf7e07ef4 | b4b333117c608a792432072d335cf092bd6dec53 | refs/heads/master | 2020-08-29T06:02:18.237139 | 2019-03-18T02:14:06 | 2019-03-18T02:14:06 | 217,949,553 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 222 | java | package jhs.lc.geom;
public interface ParametricTransitFunctionSource {
public TransitFunction getTransitFunction(double[] parameters);
public int getNumParameters();
public double getParameterScale(int paramIndex);
}
| [
"jsolorzano@logmein.com"
] | jsolorzano@logmein.com |
ccac42a61ea851a34f508e5aee59401f7e2322cf | 3bcd2c98f576a153206f13c207b81a839e2ee723 | /src/com/denksoft/springstarter/entity/BankAccount.java | ecb2b67380b8a7da02f5e870e206d401e5d38d9d | [
"BSD-3-Clause"
] | permissive | konstantin-yakimenko/springstarter | 12268ae72d36a9005a6b877d867746ec72cb0e4a | 4413b92a04da575bee71300e6264313e300a3b4b | refs/heads/master | 2021-01-19T04:52:12.206428 | 2016-06-17T12:19:46 | 2016-06-17T12:19:46 | 61,371,539 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,137 | java | /* Copyright (c) 2008, DENKSOFT SRL. All rights reserved.
This software is licensed under the BSD license available at
http://www.opensource.org/licenses/bsd-license.php, with these parameters:
<OWNER> = DENKSOFT SRL <ORGANIZATION> = DENKSOFT SRL <YEAR> = 2008
*/
package com.denksoft.springstarter.entity;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.LinkedList;
@Entity
public class BankAccount extends AbstractSecureObject implements Serializable {
private Date creationDate;
private String bankAccountNo;
private double balance;
@ManyToOne
private Customer customer = new Customer();
@OneToMany(mappedBy = "bankAccount")
private List<BankAccountOperation> operations = new LinkedList<BankAccountOperation>();
public BankAccount() {
this.creationDate = new Date();
}
public BankAccount(String bankAccountNo) {
this();
this.bankAccountNo = bankAccountNo;
}
public BankAccount(String bankAccountNo, double balance) {
this(bankAccountNo);
this.balance = balance;
}
public Date getCreationDate() {
return creationDate;
}
public String getBankAccountNo() {
return bankAccountNo;
}
public void setBankAccountNo(String bankAccountNo) {
this.bankAccountNo = bankAccountNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public List<BankAccountOperation> getOperations() {
return operations;
}
public void setOperations(List<BankAccountOperation> operations) {
this.operations = operations;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
/* public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}*/
} | [
"tech@inquarta.ru"
] | tech@inquarta.ru |
61edd8ca170e6062397f50867050647d1d084867 | 2d2fe1ec65a68711e02ddfe2b41248d36e8bf729 | /pedibus-backend/src/main/java/it/polito/ai/pedibusbackend/viewmodels/RideDTO.java | 6c083c8c4d3b13970e63eb38b41f164a3ee10136 | [] | no_license | FedeParola/ai-pedibus | 37b1eff5d1b62f82acae1e2ed19fe7ff3ffe1358 | 0e3e47da0337416a2a7043f2bf3c4b26f429b146 | refs/heads/master | 2022-04-05T07:38:00.283821 | 2020-02-13T10:35:12 | 2020-02-13T10:35:12 | 212,340,328 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 429 | java | package it.polito.ai.pedibusbackend.viewmodels;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RideDTO {
@NotNull
private Long id;
@NotNull
private Date date;
@NotNull
private Character direction;
@NotNull
private Boolean consolidated;
}
| [
"s255183@studenti.polito.it"
] | s255183@studenti.polito.it |
9a7bd90ceaeff510079e777a54bf1f5879223582 | f41fa6720c00aa2f2d02ef68bc018ee5eef34abe | /org.marc.shic/src/main/java/org/marc/shic/core/LocationDemographic.java | 5ea2c8b74eff6dcd4e0822c7b16d73d230fcb5c2 | [
"Apache-2.0"
] | permissive | MohawkMEDIC/SharedHealthIntegrationComponents | e27f85d59cce75b89b3bb698d9c2787d45ba3f84 | dd0a3e97b03613be57be9cd9489e095096bee024 | refs/heads/master | 2020-04-09T20:27:59.837535 | 2018-12-05T21:42:57 | 2018-12-05T21:42:57 | 160,574,146 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,347 | java | /**
* Copyright 2013 Mohawk College of Applied Arts and Technology
*
* 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.
*
*
* Date: October 29, 2013
*
*/
package org.marc.shic.core;
/**
*
* @author ibrahimm
*/
public class LocationDemographic extends Demographic {
private DomainIdentifier m_id;
private String m_name;
public LocationDemographic() {
super();
}
public LocationDemographic(DomainIdentifier id, String name, String phone,
PersonAddress address) {
super();
this.addIdentifier(id);
this.m_id = id;
this.m_name = name;
this.addPhone(phone);
this.addAddress(address);
}
public String getName() {
return m_name;
}
public void setName(String name) {
this.m_name = name;
}
public DomainIdentifier getId() {
return m_id;
}
public void setId(DomainIdentifier id) {
this.m_id = id;
}
}
| [
"nityan.khanna@mohawkcollege.ca"
] | nityan.khanna@mohawkcollege.ca |
5a48ba4f8404c6ca0565efee7812d219ec10a270 | 4a11add5f5c002e2c03953b4ffb6c28a30eb0842 | /app/src/main/java/com/wipro/wipro_music_player/model/UserSettingsModel.java | 70f2734b96186643c5b9e66cf09f78c37112c70e | [] | no_license | Torres1982/Wipro_Music_Player | 8c718a4a499be999397c7975d438ee47c7a4a128 | 9c779f4d4b054f5812fed52a367caf210ce158ea | refs/heads/master | 2020-06-05T07:45:23.563381 | 2020-02-07T12:43:39 | 2020-02-07T12:43:39 | 192,364,263 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,598 | java | package com.wipro.wipro_music_player.model;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class UserSettingsModel extends RealmObject {
@PrimaryKey
private long id;
private int defaultThemeStatus;
private int darkThemeStatus;
private int shuffleSwitchStatus;
private int repeatSwitchStatus;
private int songsListStatus;
private int sortingListStatus;
public UserSettingsModel() {}
public long getId() { return id; }
public int getDefaultThemeStatus() { return defaultThemeStatus; }
public int getDarkThemeStatus() { return darkThemeStatus; }
public int getShuffleSwitchStatus() { return shuffleSwitchStatus; }
public int getRepeatSwitchStatus() { return repeatSwitchStatus; }
public int getSongsListStatus() { return songsListStatus; }
public int getSortingListStatus() { return sortingListStatus; }
public void setId(long id) { this.id = id; }
public void setDefaultThemeStatus(int defaultThemeStatus) { this.defaultThemeStatus = defaultThemeStatus; }
public void setDarkThemeStatus(int darkThemeStatus) { this.darkThemeStatus = darkThemeStatus; }
public void setShuffleSwitchStatus(int shuffleSwitchStatus) { this.shuffleSwitchStatus = shuffleSwitchStatus; }
public void setRepeatSwitchStatus(int repeatSwitchStatus) { this.repeatSwitchStatus = repeatSwitchStatus; }
public void setSongsListStatus(int songsListStatus) { this.songsListStatus = songsListStatus; }
public void setSortingListStatus(int sortingListStatus) { this.sortingListStatus = sortingListStatus; }
}
| [
"artur.sukiennik82@gmail.com"
] | artur.sukiennik82@gmail.com |
548f8a71a393eadec75d99f4713249118b1db540 | f731737ed4313d0b04944e989ae7719dab386941 | /src/main/java/org/stathry/smartj/SmartJServer.java | 2c91f3af5cc389df1c2c71e9ae5a9be45745a139 | [] | no_license | yuanjkkang/smartj | 55585ba54a026d0452db711de58cd9258b66f651 | 67b8b3497d8e32e0783598b89264f273cbf3ee49 | refs/heads/master | 2020-04-02T20:48:16.385008 | 2018-10-26T05:03:19 | 2018-10-26T05:03:19 | 154,779,737 | 0 | 0 | null | 2018-10-26T05:02:13 | 2018-10-26T05:02:12 | null | UTF-8 | Java | false | false | 1,941 | java | package org.stathry.smartj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.stathry.smartj.view.JSONView;
import org.stathry.smartj.view.MybatisView;
import org.stathry.smartj.view.SmartJView;
import javax.swing.*;
import java.awt.*;
/**
* SmartJServer
* Created by dongdaiming on 2018-10-16 10:44
*/
public class SmartJServer {
private static final Logger LOGGER = LoggerFactory.getLogger(SmartJServer.class);
public static void main(String[] args) {
startSpringContext();
showSmartJClient();
while (true) {
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
}
}
}
private static void startSpringContext() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:spring-context.xml");
LOGGER.info("SmartJServer started.");
}
private static void showSmartJClient() {
// SmartJView.initGlobalFont(new Font("新宋体", Font.PLAIN, 12));
JPanel panelContainer = new JPanel();
panelContainer.setLayout(new GridBagLayout());
JPanel leftPanel = MybatisView.createPanel("MyBatis生成工具");
GridBagConstraints leftC = SmartJView.createGridBagConstraints(0, 0, 1.0, 0.0, GridBagConstraints.HORIZONTAL);
panelContainer.add(leftPanel, leftC);
JPanel rightPanel = JSONView.createPanel("JSON工具");
GridBagConstraints rightC = SmartJView.createGridBagConstraints(1, 0, 1.0, 1.0, GridBagConstraints.BOTH);
panelContainer.add(rightPanel, rightC);
panelContainer.setOpaque(true);
JFrame frame = SmartJView.createMainFrame("SmartJServer", 880, 600);
frame.setContentPane(panelContainer);
frame.setVisible(true);
}
}
| [
"dongdaiming@socian.com.cn"
] | dongdaiming@socian.com.cn |
5032497cb1ffe5d961aa1d627dbcb5afe15ed9b3 | 23b834312c5e7d3731b51cda3886b31d73580fa2 | /MykhailoKozakFileStorageServiceClient/src/main/java/lab/web/soap/GetListAllFiles.java | d405b0ce62b8d73ee73d04649f35d76bac1d9bae | [] | no_license | MykhailoKozak/FileStorageServiceClient | a14d91c705d4791de2c8210e3a6281848bf86f9d | bd8faad925c9bcd464b61aefe621e79bad778047 | refs/heads/master | 2020-04-27T22:49:46.081826 | 2019-03-11T14:45:29 | 2019-03-11T14:45:29 | 174,751,033 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 725 | java |
package lab.web.soap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getListAllFiles complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="getListAllFiles">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getListAllFiles1")
public class GetListAllFiles {
}
| [
"mykhailokozak1998@gmail.com"
] | mykhailokozak1998@gmail.com |
fb6780c9fcfcfc3f607628a6170858b44f7828c5 | f257d18d3fc11cd87abc587f7e77e230346cad68 | /src/main/java/com/shagaba/magazine/domain/Identifiable.java | 7e121a157e5f4535cd8fee341af05cdaee02d220 | [] | no_license | shagaba/magazine | 71362186127045a31f8504c9a5f6a0bd06fb8823 | 382bcaff57d996267516636bc1d79ac64fa1754c | refs/heads/master | 2021-01-21T13:15:17.832002 | 2016-05-23T21:41:03 | 2016-05-23T21:41:03 | 55,363,501 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 263 | java | package com.shagaba.magazine.domain;
import java.io.Serializable;
public interface Identifiable<ID extends Serializable> {
/**
* @return the id
*/
public ID getId();
/**
* @param id the id to set
*/
public void setId(ID id);
}
| [
"shai.gabai@shagaba.com"
] | shai.gabai@shagaba.com |
931addc2ddb1962c13279de3372e06e989c910fa | 51f05a845e5ccf97fcbc7a7161fc73c757bd6abe | /src/main/java/com/example/spring/dao/PersonDao.java | 97cc038af9ae246b84b77ae5904963ebb446d239 | [] | no_license | Eliza-H/SpringApplication | 3cebe9ff24040878c3fc15e34b624dbba951de86 | 47ace03f76b690534d827a2e65b20e48fc8bd64b | refs/heads/master | 2021-09-01T08:06:02.305144 | 2017-12-19T21:57:59 | 2017-12-19T21:57:59 | 104,775,259 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 228 | java | package com.example.spring.dao;
/**
* Created by elh on 06.09.17.
*/
import java.util.List;
import com.example.spring.model.Person;
public interface PersonDao {
void add(Person person);
List<Person> listPersons();
} | [
"gurievaliza@gmail.com"
] | gurievaliza@gmail.com |
23c2a5f5ebc49056436575329ec419f9409e5f08 | 2ba1ebe07175cc08fad982b4c6436bd145362180 | /src/main/java/com/warmer/dp/common/AbstractApplePhoneService.java | 79a1ce86c2fe4a2c540da876768b9bcef250322d | [] | no_license | MiracleTanC/designPattern | 4d47f172517127eeae15909d7a85f77d6fadeb9c | c8007642a6d131337b0f70c7d09cb447f0551753 | refs/heads/master | 2020-03-27T17:32:13.701218 | 2018-10-07T07:38:10 | 2018-10-07T07:38:10 | 146,857,651 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 355 | java | package com.warmer.dp.common;
import com.warmer.dp.service.AbstractFactoryService;
import com.warmer.dp.service.PhoneService;
import com.warmer.dp.service.impl.ApplePhoneServiceImpl;
public class AbstractApplePhoneService implements AbstractFactoryService{
@Override
public PhoneService GetPhoneService() {
return new ApplePhoneServiceImpl();
}
}
| [
"1130196938@qq.com"
] | 1130196938@qq.com |
fcdb2a0c0b90a58863c63b5bd42954894369da8b | b3fd344bfde27852a6a59f9a5fbda37edf304be2 | /app/src/androidTest/java/mgrzeszczak/com/github/seriesgeek/ApplicationTest.java | 4fdc840d6d7e0368207d315c1ceb032e29fa175b | [
"MIT"
] | permissive | mgrzeszczak/series-geek | e7eac38e294132e8bda16b4ccfcc0eae6c3c9286 | a1ff28b24ce586afafce097b7f22eacadea69af8 | refs/heads/master | 2021-03-27T09:57:13.885075 | 2017-06-14T14:57:11 | 2017-06-14T14:57:11 | 82,659,775 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 364 | java | package mgrzeszczak.com.github.seriesgeek;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"maciejgrzeszczak@gmail.com"
] | maciejgrzeszczak@gmail.com |
a4d5d0bb4680673c4db0693be4263c1a573f422e | d52ab012b10bab544769ade0e6e29126a8e3d403 | /src/basics/statics/StaticProblem.java | 2eb48ef00734cb6e8d8e7f72f7d6899bab84ae37 | [] | no_license | Aniruddha-Raje/javaBasics | dc2673aa56126b6aaffb6c4c1e618f790e2bac27 | 61898fd0fc5a6d18127a5c67fd3de5a17f4447b4 | refs/heads/master | 2021-01-23T16:28:27.203868 | 2019-01-08T03:40:41 | 2019-01-08T03:40:41 | 93,299,025 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 491 | java | /**
*
*/
package basics.statics;
/**
* @author Aniruddha.Raje
*
*/
public class StaticProblem {
static String str = "Hello";
private void changeValue(String s) {
str = s;
}
private String displayValue() {
return str;
}
public static void main(String[] args) {
StaticProblem ob1 = new StaticProblem();
StaticProblem ob2 = new StaticProblem();
ob2.changeValue("World");
System.out.println(ob1.displayValue());
System.out.println(ob2.displayValue());
}
}
| [
"aniruddha.raje@blazeclan.com"
] | aniruddha.raje@blazeclan.com |
a7f1ae9e5317952bf3b736fd9aa042717bfc7276 | fa1408365e2e3f372aa61e7d1e5ea5afcd652199 | /src/testcases/CWE190_Integer_Overflow/s01/CWE190_Integer_Overflow__byte_console_readLine_multiply_68b.java | 918094ae7d036a9c881d808ca0989527456bfe0e | [] | no_license | bqcuong/Juliet-Test-Case | 31e9c89c27bf54a07b7ba547eddd029287b2e191 | e770f1c3969be76fdba5d7760e036f9ba060957d | refs/heads/master | 2020-07-17T14:51:49.610703 | 2019-09-03T16:22:58 | 2019-09-03T16:22:58 | 206,039,578 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,491 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__byte_console_readLine_multiply_68b.java
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-68b.tmpl.java
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: console_readLine Read data from the console using readLine
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: multiply
* GoodSink: Ensure there will not be an overflow before multiplying data by 2
* BadSink : If data is positive, multiply by 2, which can cause an overflow
* Flow Variant: 68 Data flow: data passed as a member variable in the "a" class, which is used by a method in another class in the same package
*
* */
package testcases.CWE190_Integer_Overflow.s01;
import testcasesupport.*;
import javax.servlet.http.*;
public class CWE190_Integer_Overflow__byte_console_readLine_multiply_68b
{
public void badSink() throws Throwable
{
byte data = CWE190_Integer_Overflow__byte_console_readLine_multiply_68a.data;
if(data > 0) /* ensure we won't have an underflow */
{
/* POTENTIAL FLAW: if (data*2) > Byte.MAX_VALUE, this will overflow */
byte result = (byte)(data * 2);
IO.writeLine("result: " + result);
}
}
/* goodG2B() - use goodsource and badsink */
public void goodG2BSink() throws Throwable
{
byte data = CWE190_Integer_Overflow__byte_console_readLine_multiply_68a.data;
if(data > 0) /* ensure we won't have an underflow */
{
/* POTENTIAL FLAW: if (data*2) > Byte.MAX_VALUE, this will overflow */
byte result = (byte)(data * 2);
IO.writeLine("result: " + result);
}
}
/* goodB2G() - use badsource and goodsink */
public void goodB2GSink() throws Throwable
{
byte data = CWE190_Integer_Overflow__byte_console_readLine_multiply_68a.data;
if(data > 0) /* ensure we won't have an underflow */
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data < (Byte.MAX_VALUE/2))
{
byte result = (byte)(data * 2);
IO.writeLine("result: " + result);
}
else
{
IO.writeLine("data value is too large to perform multiplication.");
}
}
}
}
| [
"bqcuong2212@gmail.com"
] | bqcuong2212@gmail.com |
031dcc314959676bdf5952a530e33f7962e90738 | c9e44e050b8f1d87cc9bf45a87896a2ca10c96a6 | /src/main/java/io/github/nucleuspowered/nucleus/modules/teleport/handlers/TeleportHandler.java | aee0a731ea403a3ac706e1b56ccc049722247de9 | [
"MIT",
"Apache-2.0"
] | permissive | leelawd/Nucleus-1.1.10 | 815151b42cc7cdd9bfa990872de8c403eaf4f43f | 3e3d3ec212566b1f18b0786071c6906288432db6 | refs/heads/master | 2020-04-17T22:51:22.532164 | 2019-01-22T14:48:43 | 2019-01-22T14:48:43 | 167,011,427 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,611 | java | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.teleport.handlers;
import com.google.common.base.Preconditions;
import io.github.nucleuspowered.nucleus.Nucleus;
import io.github.nucleuspowered.nucleus.NucleusPlugin;
import io.github.nucleuspowered.nucleus.dataservices.modular.ModularUserService;
import io.github.nucleuspowered.nucleus.internal.PermissionRegistry;
import io.github.nucleuspowered.nucleus.internal.interfaces.CancellableTask;
import io.github.nucleuspowered.nucleus.internal.permissions.SubjectPermissionCache;
import io.github.nucleuspowered.nucleus.internal.teleport.NucleusTeleportHandler;
import io.github.nucleuspowered.nucleus.modules.jail.JailModule;
import io.github.nucleuspowered.nucleus.modules.jail.datamodules.JailUserDataModule;
import io.github.nucleuspowered.nucleus.modules.teleport.config.TeleportConfigAdapter;
import io.github.nucleuspowered.nucleus.modules.teleport.datamodules.TeleportUserDataModule;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextStyles;
import uk.co.drnaylor.quickstart.exceptions.IncorrectAdapterTypeException;
import uk.co.drnaylor.quickstart.exceptions.NoModuleException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
public class TeleportHandler {
private final NucleusPlugin plugin;
private final Map<UUID, TeleportPrep> ask = new HashMap<>();
private static final String tptoggleBypassPermission = PermissionRegistry.PERMISSIONS_PREFIX + "teleport.tptoggle.exempt";
private Text acceptDeny;
public TeleportHandler(NucleusPlugin plugin) {
this.plugin = plugin;
}
public TeleportBuilder getBuilder() {
return new TeleportBuilder(plugin);
}
public static boolean canBypassTpToggle(Subject from) {
return from.hasPermission(tptoggleBypassPermission);
}
public static boolean canTeleportTo(SubjectPermissionCache<? extends CommandSource> source, User to) {
if (source.getSubject() instanceof Player && !TeleportHandler.canBypassTpToggle(source)) {
if (!Nucleus.getNucleus().getUserDataManager().get(to).map(x -> x.get(TeleportUserDataModule.class).isTeleportToggled()).orElse(true)) {
source.getSubject().sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.fail.targettoggle", to.getName()));
return false;
}
}
return true;
}
public void addAskQuestion(UUID target, TeleportPrep tp) {
clearExpired();
get(target).ifPresent(this::cancel);
ask.put(target, tp);
}
public void clearExpired() {
Instant now = Instant.now();
ask.entrySet().stream().filter(x -> now.isAfter(x.getValue().getExpire())).map(Map.Entry::getKey).collect(Collectors.toList())
.forEach(x -> cancel(ask.remove(x)));
}
public boolean getAndExecute(UUID uuid) {
Optional<TeleportPrep> otp = get(uuid);
return otp.isPresent() && otp.get().tpbuilder.startTeleport();
}
public Optional<TeleportPrep> get(UUID uuid) {
clearExpired();
return Optional.ofNullable(ask.remove(uuid));
}
public boolean remove(UUID uuid) {
TeleportPrep tp = ask.remove(uuid);
cancel(tp);
return tp != null;
}
public Text getAcceptDenyMessage() {
if (acceptDeny == null) {
acceptDeny = Text.builder()
.append(Text.builder().append(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("standard.accept")).style(TextStyles.UNDERLINE)
.onHover(TextActions.showText(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.accept.hover")))
.onClick(TextActions.runCommand("/tpaccept")).build())
.append(Text.of(" - "))
.append(Text.builder().append(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("standard.deny")).style(TextStyles.UNDERLINE)
.onHover(TextActions.showText(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.deny.hover")))
.onClick(TextActions.runCommand("/tpdeny")).build())
.build();
}
return acceptDeny;
}
private void cancel(@Nullable TeleportPrep prep) {
if (prep == null) {
return;
}
if (prep.charged != null && prep.cost > 0) {
if (prep.charged.isOnline()) {
prep.charged.getPlayer().ifPresent(x -> x
.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.prep.cancel", plugin.getEconHelper().getCurrencySymbol(prep.cost))));
}
plugin.getEconHelper().depositInPlayer(prep.charged, prep.cost);
}
}
private static class TeleportTask implements CancellableTask {
private final Player playerToTeleport;
private final Player playerToTeleportTo;
private final Player charged;
private final double cost;
private final boolean safe;
private final CommandSource source;
private final NucleusPlugin plugin;
private final boolean silentSource;
private final boolean silentTarget;
private TeleportTask(NucleusPlugin plugin, CommandSource source, Player playerToTeleport, Player playerToTeleportTo, boolean safe, boolean silentSource, boolean silentTarget) {
this(plugin, source, playerToTeleport, playerToTeleportTo, null, 0, safe, silentSource, silentTarget);
}
private TeleportTask(NucleusPlugin plugin, CommandSource source, Player playerToTeleport, Player playerToTeleportTo, Player charged, double cost, boolean safe,
boolean silentSource, boolean silentTarget) {
this.plugin = plugin;
this.source = source;
this.playerToTeleport = playerToTeleport;
this.playerToTeleportTo = playerToTeleportTo;
this.cost = cost;
this.charged = charged;
this.safe = safe;
this.silentSource = silentSource;
this.silentTarget = silentTarget;
}
private void run() {
if (playerToTeleportTo.isOnline()) {
// If safe, get the teleport mode
NucleusTeleportHandler tpHandler = plugin.getTeleportHandler();
NucleusTeleportHandler.TeleportMode mode = safe ? tpHandler.getTeleportModeForPlayer(playerToTeleport) :
NucleusTeleportHandler.TeleportMode.NO_CHECK;
NucleusTeleportHandler.TeleportResult result =
tpHandler.teleportPlayer(playerToTeleport, playerToTeleportTo.getTransform(), mode, Cause.of(NamedCause.owner(this.source)));
if (!result.isSuccess()) {
if (!silentSource) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat(result ==
NucleusTeleportHandler.TeleportResult.FAILED_NO_LOCATION ? "teleport.nosafe" : "teleport.cancelled"));
}
onCancel();
return;
}
if (!source.equals(playerToTeleport) && !silentSource) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.success.source", playerToTeleport.getName(), playerToTeleportTo.getName()));
}
playerToTeleport.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.to.success", playerToTeleportTo.getName()));
if (!silentTarget) {
playerToTeleportTo.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.from.success", playerToTeleport.getName()));
}
} else {
if (!silentSource) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.fail.offline"));
}
onCancel();
}
}
@Override
public void accept(Task task) {
run();
}
@Override
public void onCancel() {
if (charged != null && cost > 0) {
plugin.getEconHelper().depositInPlayer(charged, cost);
}
}
}
@SuppressWarnings("SameParameterValue")
public static class TeleportBuilder {
private CommandSource source;
private Player from;
private Player to;
private Player charge;
private double cost;
private int warmupTime = 0;
private boolean bypassToggle = false;
private boolean safe;
private boolean silentSource = false;
private boolean silentTarget = false;
private final NucleusPlugin plugin;
private TeleportBuilder(NucleusPlugin plugin) {
this.plugin = plugin;
try {
this.safe = plugin.getModuleContainer().getConfigAdapterForModule("teleport", TeleportConfigAdapter.class)
.getNodeOrDefault().isUseSafeTeleport();
} catch (NoModuleException | IncorrectAdapterTypeException e) {
this.safe = true;
}
}
public TeleportBuilder setSafe(boolean safe) {
this.safe = safe;
return this;
}
public TeleportBuilder setSource(CommandSource source) {
this.source = source;
return this;
}
public TeleportBuilder setFrom(Player from) {
this.from = from;
return this;
}
public TeleportBuilder setTo(Player to) {
this.to = to;
return this;
}
public TeleportBuilder setCharge(Player charge) {
this.charge = charge;
return this;
}
public TeleportBuilder setCost(double cost) {
this.cost = cost;
return this;
}
public TeleportBuilder setWarmupTime(int warmupTime) {
this.warmupTime = warmupTime;
return this;
}
public TeleportBuilder setBypassToggle(boolean bypassToggle) {
this.bypassToggle = bypassToggle;
return this;
}
public TeleportBuilder setSilentSource(boolean silent) {
this.silentSource = silent;
return this;
}
public TeleportBuilder setSilentTarget(boolean silentTarget) {
this.silentTarget = silentTarget;
return this;
}
public boolean startTeleport() {
Preconditions.checkNotNull(from);
Preconditions.checkNotNull(to);
if (source == null) {
source = from;
}
if (from.equals(to)) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("command.teleport.self"));
return false;
}
ModularUserService toPlayer = plugin.getUserDataManager().get(to).get();
if (!bypassToggle && !toPlayer.get(TeleportUserDataModule.class).isTeleportToggled() && !canBypassTpToggle(source)) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.fail.targettoggle", to.getName()));
return false;
}
if (plugin.isModuleLoaded(JailModule.ID) &&
plugin.getUserDataManager().get(from).get().get(JailUserDataModule.class).getJailData().isPresent()) {
// Don't teleport a jailed subject.
if (!silentSource) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.fail.jailed", from.getName()));
}
return false;
}
TeleportTask tt;
if (cost > 0 && charge != null) {
tt = new TeleportTask(plugin, source, from, to, charge, cost, safe, silentSource, silentTarget);
} else {
tt = new TeleportTask(plugin, source, from, to, safe, silentSource, silentTarget);
}
if (warmupTime > 0) {
from.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("teleport.warmup", String.valueOf(warmupTime)));
plugin.getWarmupManager().addWarmup(from.getUniqueId(), Sponge.getScheduler().createTaskBuilder().delay(warmupTime, TimeUnit.SECONDS)
.execute(tt).name("NucleusPlugin - Teleport Waiter").submit(plugin));
} else {
tt.run();
}
return true;
}
}
public static class TeleportPrep {
private final Instant expire;
private final User charged;
private final double cost;
private final TeleportBuilder tpbuilder;
public TeleportPrep(Instant expire, User charged, double cost, TeleportBuilder tpbuilder) {
this.expire = expire;
this.charged = charged;
this.cost = cost;
this.tpbuilder = tpbuilder;
}
public Instant getExpire() {
return expire;
}
public User getCharged() {
return charged;
}
public double getCost() {
return cost;
}
public TeleportBuilder getTpbuilder() {
return tpbuilder;
}
}
}
| [
"leelawd123@gmail.com"
] | leelawd123@gmail.com |
209b5c3c01dc1b7b9b5b1a16b4a575af1db4f340 | 131c50a29ad34eedbc231362f6d845ad04af5150 | /azkarra-api/src/test/java/io/streamthoughts/azkarra/api/streams/rocksdb/DefaultRocksDBConfigSetterTest.java | a22c6952d5686f37e4a574278ac5dbd157abe2a0 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | arujit/azkarra-streams | d76474d945d68d20c7076944d623277b4fbfe89f | 4fd90efb8d0848b869d989155a38f45c920b390c | refs/heads/master | 2022-07-06T15:57:03.377519 | 2020-05-09T10:38:17 | 2020-05-09T10:43:48 | 262,531,268 | 1 | 0 | Apache-2.0 | 2020-05-09T09:03:43 | 2020-05-09T09:03:42 | null | UTF-8 | Java | false | false | 2,211 | java | /*
* Copyright 2019 StreamThoughts.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 io.streamthoughts.azkarra.api.streams.rocksdb;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.rocksdb.Options;
import java.util.HashMap;
import java.util.Map;
class DefaultRocksDBConfigSetterTest {
@Test
public void shouldBeConfiguredGivenValidConfiguration() {
DefaultRocksDBConfigSetter setter = new DefaultRocksDBConfigSetter();
Map<String, Object> config = new HashMap<>();
config.put(DefaultRocksDBConfigSetter.DefaultRocksDBConfigSetterConfig.ROCKSDB_LOG_DIR_CONFIG, "/log/dir");
config.put(DefaultRocksDBConfigSetter.DefaultRocksDBConfigSetterConfig.ROCKSDB_MAX_LOG_FILE_SIZE_CONFIG, "200");
config.put(DefaultRocksDBConfigSetter.DefaultRocksDBConfigSetterConfig.ROCKSDB_STATS_ENABLECONFIG, true);
config.put(DefaultRocksDBConfigSetter.DefaultRocksDBConfigSetterConfig.ROCKSDB_STATS_DUMP_PERIOD_SEC_CONFIG, "100");
setter.setConfig("storeName", new Options(), config);
DefaultRocksDBConfigSetter.DefaultRocksDBConfigSetterConfig configured = setter.getConfig();
Assertions.assertEquals(100, configured.dumpPeriodSec());
Assertions.assertEquals(true, configured.isStatisticsEnable());
Assertions.assertEquals("/log/dir", configured.logDir());
Assertions.assertEquals(200, configured.maxLogFileSize());
}
} | [
"florian.hussonnois@gmail.com"
] | florian.hussonnois@gmail.com |
34162f0530f75adfa36e1a2fb3b5a87ec7f0b5e6 | b7953aba1d2a32dda725bfb602fc2e8af0c5d61e | /Java/DesignPatterns/StructuralPattern/IteratorMethod.java | db293a532bb91903ee07d21bf2c6279e2ba5d31e | [] | no_license | parasdhawan17/JavaAndKotlinBasics | 732b7b3e7ce3a2f9932042728be75c1ac3c56805 | 4a2622f8ccc8fc5070e88d4b70fdf2885215c107 | refs/heads/main | 2023-08-21T12:31:51.052508 | 2021-10-07T07:53:09 | 2021-10-07T07:53:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,071 | java | package Java.DesignPatterns.StructuralPattern;
import java.util.ArrayList;
import java.util.List;
class Profile{
String id;
}
interface ProfileIterator{
Boolean hasNext();
Profile getNext();
}
interface SocialNetwork{
ProfileIterator createFriendsIterator(String profileId);
ProfileIterator createCoworkersIterator(String profileId);
}
class Facebook implements SocialNetwork{
@Override
public ProfileIterator createFriendsIterator(String profileId) {
return null;
}
@Override
public ProfileIterator createCoworkersIterator(String profileId) {
return null;
}
}
class FaceBookIterator implements ProfileIterator{
List<Profile> profiles = new ArrayList();
int currentPosition = 0;
@Override
public Boolean hasNext() {
return profiles.get(currentPosition)!=null;
}
@Override
public Profile getNext() {
currentPosition++;
return profiles.get(currentPosition);
}
}
public class IteratorMethod {
public static void main(String[] args){
}
}
| [
"parasdhawan@192.168.1.9"
] | parasdhawan@192.168.1.9 |
d8987a826929e06732013aae1eae11a108a6e434 | b92345ed5ceac2027bfe72ee126bd8cbef65568e | /HRDBMS/src/com/exascale/misc/AuxPairingHeap.java | 668e9b2b9846147ce249ea2fd094a572eb106be7 | [] | no_license | blinda1057/HRDBMS | 80fa54cf403f8c4a94ee26754c907f8a3e1257bb | 5825d0ab2bbc642dfde849ab36190d52e6e718e4 | refs/heads/merged | 2021-01-15T22:04:36.920316 | 2016-06-17T14:09:22 | 2016-06-17T14:09:22 | 61,378,150 | 0 | 0 | null | 2016-06-17T14:06:59 | 2016-06-17T14:06:58 | null | UTF-8 | Java | false | false | 3,911 | java | package com.exascale.misc;
import java.util.Comparator;
public final class AuxPairingHeap<E>
{
private final Comparator compare;
private Node node = null;
private Node aux = null;
private Node minPtr = null;
private Node minAuxPtr = null;
private int size = 0;
public AuxPairingHeap(Comparator compare)
{
this.compare = compare;
}
public E extractMin()
{
E retval = minPtr.data;
if (minPtr != node)
{
if (minPtr == aux)
{
aux = minPtr.right;
if (aux != null)
{
aux.left = null;
}
}
else
{
minPtr.left.right = minPtr.right;
if (minPtr.right != null)
{
minPtr.right.left = minPtr.left;
}
}
node = merge(node, mergePairsMP(aux));
minPtr = node;
aux = null;
minAuxPtr = null;
}
else
{
node = mergePairs(node.child);
if (minAuxPtr == null)
{
minPtr = node;
}
else
{
if (compare.compare(node.data, minAuxPtr.data) < 0)
{
minPtr = node;
}
else
{
minPtr = minAuxPtr;
}
}
}
size--;
return retval;
}
public E findMin()
{
return minPtr.data;
}
private Node mergePairs(Node list)
{
if (list == null)
{
return null;
}
if (list.right == null)
{
return list;
}
Node right = list.right;
Node rightRight = right.right;
list.right = null;
right.right = null;
right.left = null;
if (rightRight != null)
{
rightRight.left = null;
}
return merge(merge(list, right), mergePairs(rightRight));
}
private Node mergePairsMP(Node list)
{
if (list == null)
{
return null;
}
if (list.right == null)
{
return list;
}
Node last = null;
Node head = null;
while (true)
{
Node current = list;
Node right = current.right;
if (right == null && head != null)
{
right = head;
head = null;
}
list = right.right;
current.right = null;
right.right = null;
right.left = null;
if (list != null)
{
list.left = null;
}
Node newNode = merge(current, right);
if (list == null)
{
if (head == null)
{
return newNode;
}
else
{
list = head;
head = null;
last.right = newNode;
last = newNode;
}
}
else
{
if (last == null)
{
last = newNode;
head = newNode;
}
else
{
last.right = newNode;
last = newNode;
}
}
}
}
public void insert(E val)
{
Node valNode = new Node(val);
size++;
if (node == null)
{
node = valNode;
minPtr = valNode;
return;
}
else if (aux == null)
{
aux = valNode;
minAuxPtr = valNode;
}
else
{
valNode.right = aux;
aux.left = valNode;
aux = valNode;
}
if (compare.compare(valNode.data, minPtr.data) < 0)
{
minPtr = valNode;
minAuxPtr = valNode;
}
else if (minPtr == node && minAuxPtr != valNode && compare.compare(valNode.data, minAuxPtr.data) < 0)
{
minAuxPtr = valNode;
}
}
private Node merge(Node heap1, Node heap2)
{
if (heap2 == null)
{
return heap1;
}
else if (compare.compare(heap1.data, heap2.data) < 0)
{
heap2.right = heap1.child;
if (heap1.child != null)
{
heap1.child.left = heap2;
}
heap1.child = heap2;
return heap1;
}
else
{
heap1.right = heap2.child;
if (heap2.child != null)
{
heap2.child.left = heap1;
}
heap2.child = heap1;
return heap2;
}
}
public int size()
{
return size;
}
private class Node
{
private E data;
private Node child;
private Node right;
private Node left;
public Node(E data)
{
this.data = data;
}
}
} | [
"jasonar81@gmail.com"
] | jasonar81@gmail.com |
72f85faef36d79703b836783a99c8ee9286e24a5 | 95d20c83d8aff34e314c56a3ecb2b87c9fa9fc86 | /Ghidra/Framework/Graph/src/main/java/ghidra/graph/viewer/shape/VisualGraphShapePickSupport.java | 317eaefe2996d2ebdf07286ffc63a165da3dd142 | [
"GPL-1.0-or-later",
"GPL-3.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | NationalSecurityAgency/ghidra | 969fe0d2ca25cb8ac72f66f0f90fc7fb2dbfa68d | 7cc135eb6bfabd166cbc23f7951dae09a7e03c39 | refs/heads/master | 2023-08-31T21:20:23.376055 | 2023-08-29T23:08:54 | 2023-08-29T23:08:54 | 173,228,436 | 45,212 | 6,204 | Apache-2.0 | 2023-09-14T18:00:39 | 2019-03-01T03:27:48 | Java | UTF-8 | Java | false | false | 3,404 | java | /* ###
* IP: GHIDRA
*
* 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 ghidra.graph.viewer.shape;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.*;
import java.util.Collection;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.visualization.VisualizationServer;
import edu.uci.ics.jung.visualization.picking.ShapePickSupport;
import ghidra.graph.viewer.*;
public class VisualGraphShapePickSupport<V extends VisualVertex, E extends VisualEdge<V>>
extends ShapePickSupport<V, E> {
public VisualGraphShapePickSupport(VisualizationServer<V, E> viewer) {
super(viewer);
}
@Override
protected Collection<V> getFilteredVertices(Layout<V, E> layout) {
return GraphViewerUtils.createCollectionWithZOrderBySelection(
super.getFilteredVertices(layout));
}
/**
* Overridden to handle edge picking with our custom edge placement. The painting and picking
* algorithms in Jung are all hard-coded to transform loop edges to above the vertex--there
* is no way to plug our own transformation into Jung :(
*
* @param layout
* @param viewSpaceX The x under which to look for an edge (view coordinates)
* @param viewSpaceY The y under which to look for an edge (view coordinates)
* @return The closest edge to the given point; null if no edge near the point
*/
@Override
public E getEdge(Layout<V, E> layout, double viewSpaceX, double viewSpaceY) {
Point2D viewSpacePoint = new Point2D.Double(viewSpaceX, viewSpaceY);
Point graphSpacePoint =
GraphViewerUtils.translatePointFromViewSpaceToGraphSpace(viewSpacePoint, vv);
// create a box around the given point the size of 'pickSize'
Rectangle2D pickArea = new Rectangle2D.Float(graphSpacePoint.x - pickSize / 2,
graphSpacePoint.y - pickSize / 2, pickSize, pickSize);
E closestEdge = null;
double smallestDistance = Double.MAX_VALUE;
for (E e : getFilteredEdges(layout)) {
Shape edgeShape = GraphViewerUtils.getEdgeShapeInGraphSpace(vv, e);
if (edgeShape == null) {
continue;
}
// because of the transform, the edgeShape is now a GeneralPath
// see if this edge is the closest of any that intersect
if (edgeShape.intersects(pickArea)) {
float[] coords = new float[6];
GeneralPath path = new GeneralPath(edgeShape);
PathIterator iterator = path.getPathIterator(null);
if (iterator.isDone()) {
// not sure how this can happen--0 length edge?
continue;
}
iterator.next();
iterator.currentSegment(coords);
float segmentX = coords[0];
float segmentY = coords[1];
float deltaX = segmentX - graphSpacePoint.x;
float deltaY = segmentY - graphSpacePoint.y;
float currentDistance = deltaX * deltaX + deltaY * deltaY;
if (currentDistance < smallestDistance) {
smallestDistance = currentDistance;
closestEdge = e;
}
}
}
return closestEdge;
}
}
| [
"46821332+nsadeveloper789@users.noreply.github.com"
] | 46821332+nsadeveloper789@users.noreply.github.com |
d6fe79c7408546602c8d3f0209c8bf7d3d598dde | eda1d947e0db4f14ebfe1a5644a686e80092e3e1 | /AccountsService/src/main/java/com/example/accounts/controller/AccountRestController.java | e548376576c9eb06a182c3d5745420052e43de90 | [] | no_license | cmecatl/SpringBootAndMongoSolution | 47023cd93726c101be92cab0faeaf1fc7b1a32b1 | f1044bb1a3903f4431576224d08068491c687885 | refs/heads/master | 2020-03-28T00:38:59.687786 | 2018-09-07T04:26:18 | 2018-09-07T04:26:18 | 147,437,208 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,161 | java | package com.example.accounts.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.accounts.model.Account;
import com.example.accounts.service.AccountService;
@RestController
@RequestMapping("/")
public class AccountRestController
{
@Autowired
AccountService accountService;
/**
*
*/
@RequestMapping(value = "/accounts/{account}", method = RequestMethod.GET)
public ResponseEntity<?> getAccount( @PathVariable("account") String accountId )
{
Account account = accountService.findById( accountId );
if( account == null )
{
return new ResponseEntity<Exception>( new Exception( "Account with id " + accountId + " not found" ), HttpStatus.NOT_FOUND );
}
return new ResponseEntity<Account>( account, HttpStatus.OK );
}
/**
*
*/
@RequestMapping(value = "/accounts/", method = RequestMethod.POST)
public ResponseEntity<?> registerAccount( @RequestBody Account account)
{
try
{
accountService.register( account );
return new ResponseEntity<Account>( account, HttpStatus.CREATED);
}
catch( Exception e )
{
return new ResponseEntity<Account>( account, HttpStatus.INTERNAL_SERVER_ERROR );
}
}
/**
*
*/
@RequestMapping(value = "/accounts/", method = RequestMethod.PUT)
public ResponseEntity<?> saveAccount( @RequestBody Account account)
{
try
{
accountService.save( account );
return new ResponseEntity<Account>( account, HttpStatus.OK);
}
catch( Exception e )
{
return new ResponseEntity<Account>( account, HttpStatus.INTERNAL_SERVER_ERROR );
}
}
} | [
"noreply@github.com"
] | cmecatl.noreply@github.com |
1f22eca98be3d0b359c790f6bd376dc01d442999 | 32f16a28517694a30a810df1fb2449a154335632 | /app/src/main/assets/RecyclerView.java | eb7c2593f23b60b7ed21a5dfa486eb395a2ff984 | [] | no_license | xqgdmg/RecyclerViewStudy | 9cdeb7206b20f46d5b2c04dd7b3d9f2d8c68ad05 | 96d4dbce1d645281397e58329f6307696da7ee3a | refs/heads/master | 2020-04-12T22:33:52.396994 | 2018-12-22T08:41:20 | 2018-12-22T08:41:20 | 162,792,593 | 0 | 0 | null | 2018-12-22T07:53:15 | 2018-12-22T07:53:15 | null | UTF-8 | Java | false | false | 543,235 | java | /*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.study.xuan.recyclerviewcode;
import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static android.support.v4.view.ViewCompat.TYPE_NON_TOUCH;
import static android.support.v4.view.ViewCompat.TYPE_TOUCH;
import static com.study.xuan.recyclerviewcode.Orientation.getChildViewHolderInt;
import static com.study.xuan.recyclerviewcode.Orientation.mAdapterHelper;
import static com.study.xuan.recyclerviewcode.Orientation.mChildHelper;
import static com.study.xuan.recyclerviewcode.Orientation.mState;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.Observable;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.annotation.CallSuper;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import android.support.annotation.VisibleForTesting;
import android.support.v4.os.TraceCompat;
import android.support.v4.view.AbsSavedState;
import android.support.v4.view.InputDeviceCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.NestedScrollingChild2;
import android.support.v4.view.NestedScrollingChildHelper;
import android.support.v4.view.ScrollingView;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.widget.EdgeEffectCompat;
import android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.Display;
import android.view.FocusFinder;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.Interpolator;
import android.widget.EdgeEffect;
import android.widget.LinearLayout;
import android.widget.OverScroller;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A flexible view for providing a limited window into a large data set.
* <p>
* <h3>Glossary of terms:</h3>
* <p>
* <ul>
* <li><em>Adapter:</em> A subclass of {@link Adapter} responsible for providing views
* that represent items in a data set.</li>
* <li><em>Position:</em> The position of a data item within an <em>Adapter</em>.</li>
* <li><em>Index:</em> The index of an attached child view as used in a call to
* {@link ViewGroup#getChildAt}. Contrast with <em>Position.</em></li>
* <li><em>Binding:</em> The process of preparing a child view to display data corresponding
* to a <em>position</em> within the adapter.</li>
* <li><em>Recycle (view):</em> A view previously used to display data for a specific adapter
* position may be placed in a cache for later reuse to display the same type of data again
* later. This can drastically improve performance by skipping initial layout inflation
* or construction.</li>
* <li><em>Scrap (view):</em> A child view that has entered into a temporarily detached
* state during layout. Scrap views may be reused without becoming fully detached
* from the parent RecyclerView, either unmodified if no rebinding is required or modified
* by the adapter if the view was considered <em>dirty</em>.</li>
* <li><em>Dirty (view):</em> A child view that must be rebound by the adapter before
* being displayed.</li>
* </ul>
* <p>
* <h4>Positions in RecyclerView:</h4>
* <p>
* RecyclerView introduces an additional level of abstraction between the {@link Adapter} and
* {@link LayoutManager} to be able to detect data set changes in batches during a layout
* calculation. This saves LayoutManager from tracking adapter changes to calculate animations.
* It also helps with performance because all view bindings happen at the same time and unnecessary
* bindings are avoided.
* <p>
* For this reason, there are two types of <code>position</code> related methods in RecyclerView:
* <ul>
* <li>layout position: Position of an item in the latest layout calculation. This is the
* position from the LayoutManager's perspective.</li>
* <li>adapter position: Position of an item in the adapter. This is the position from
* the Adapter's perspective.</li>
* </ul>
* <p>
* These two positions are the same except the time between dispatching <code>adapter.notify*
* </code> events and calculating the updated layout.
* <p>
* Methods that return or receive <code>*LayoutPosition*</code> use position as of the latest
* layout calculation (e.g. {@link ViewHolder#getLayoutPosition()},
* {@link #findViewHolderForLayoutPosition(int)}). These positions include all changes until the
* last layout calculation. You can rely on these positions to be consistent with what user is
* currently seeing on the screen. For example, if you have a list of items on the screen and user
* asks for the 5<sup>th</sup> element, you should use these methods as they'll match what user
* is seeing.
* <p>
* The other set of position related methods are in the form of
* <code>*AdapterPosition*</code>. (e.g. {@link ViewHolder#getAdapterPosition()},
* {@link #findViewHolderForAdapterPosition(int)}) You should use these methods when you need to
* work with up-to-date adapter positions even if they may not have been reflected to layout yet.
* For example, if you want to access the item in the adapter on a ViewHolder click, you should use
* {@link ViewHolder#getAdapterPosition()}. Beware that these methods may not be able to calculate
* adapter positions if {@link Adapter#notifyDataSetChanged()} has been called and new layout has
* not yet been calculated. For this reasons, you should carefully handle {@link #NO_POSITION} or
* <code>null</code> results from these methods.
* <p>
* When writing a {@link LayoutManager} you almost always want to use layout positions whereas when
* writing an {@link Adapter}, you probably want to use adapter positions.
*
* @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_layoutManager
**/
public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild2 {
static final String TAG = "RecyclerView";
static final boolean DEBUG = false;
static final boolean VERBOSE_TRACING = false;
private static final int[] NESTED_SCROLLING_ATTRS =
{16843830 * /
/* android.R.attr.nestedScrollingEnabled **/
};
private static final int[]CLIP_TO_PADDING_ATTR={android.R.attr.clipToPadding};
/**
* On Kitkat and JB MR2, there is a bug which prevents DisplayList from being invalidated if
* a View is two levels deep(wrt to ViewHolder.itemView). DisplayList can be invalidated by
* setting View's visibility to INVISIBLE when View is detached. On Kitkat and JB MR2, Recycler
* recursively traverses itemView and invalidates display list for each ViewGroup that matches
* this criteria.
**/
static final boolean FORCE_INVALIDATE_DISPLAY_LIST=Build.VERSION.SDK_INT==18
||Build.VERSION.SDK_INT==19||Build.VERSION.SDK_INT==20;
/**
* On M+, an unspecified measure spec may include a hint which we can use. On older platforms,
* this value might be garbage. To save LayoutManagers from it, RecyclerView sets the size to
* 0 when mode is unspecified.
**/
static final boolean ALLOW_SIZE_IN_UNSPECIFIED_SPEC=Build.VERSION.SDK_INT>=23;
static final boolean POST_UPDATES_ON_ANIMATION=Build.VERSION.SDK_INT>=16;
/**
* On L+, with RenderThread, the UI thread has idle time after it has passed a frame off to
* RenderThread but before the next frame begins. We schedule prefetch work in this window.
**/
private static final boolean ALLOW_THREAD_GAP_WORK=Build.VERSION.SDK_INT>=21;
/**
* FocusFinder#findNextFocus is broken on ICS MR1 and older for View.FOCUS_BACKWARD direction.
* We convert it to an absolute direction such as FOCUS_DOWN or FOCUS_LEFT.
**/
private static final boolean FORCE_ABS_FOCUS_SEARCH_DIRECTION=Build.VERSION.SDK_INT<=15;
/**
* on API 15-, a focused child can still be considered a focused child of RV even after
* it's being removed or its focusable flag is set to false. This is because when this focused
* child is detached, the reference to this child is not removed in clearFocus. API 16 and above
* properly handle this case by calling ensureInputFocusOnFirstFocusable or rootViewRequestFocus
* to request focus on a new child, which will clear the focus on the old (detached) child as a
* side-effect.
**/
private static final boolean IGNORE_DETACHED_FOCUSED_CHILD=Build.VERSION.SDK_INT<=15;
static final boolean DISPATCH_TEMP_DETACH=false;
/** @hide **/
@RestrictTo(LIBRARY_GROUP)
@IntDef({HORIZONTAL, VERTICAL})
@Retention(RetentionPolicy.SOURCE)
public @interface Orientation {
}
public static final int HORIZONTAL = LinearLayout.HORIZONTAL;
public static final int VERTICAL = LinearLayout.VERTICAL;
public static final int NO_POSITION = -1;
public static final long NO_ID = -1;
public static final int INVALID_TYPE = -1;
/**
* Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates
* that the RecyclerView should use the standard touch slop for smooth,
* continuous scrolling.
**/
public static final int TOUCH_SLOP_DEFAULT = 0;
/**
* Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates
* that the RecyclerView should use the standard touch slop for scrolling
* widgets that snap to a page or other coarse-grained barrier.
**/
public static final int TOUCH_SLOP_PAGING = 1;
static final int MAX_SCROLL_DURATION = 2000;
/**
* RecyclerView is calculating a scroll.
* If there are too many of these in Systrace, some Views inside RecyclerView might be causing
* it. Try to avoid using EditText, focusable views or handle them with care.
**/
static final String TRACE_SCROLL_TAG = "RV Scroll";
/**
* OnLayout has been called by the View system.
* If this shows up too many times in Systrace, make sure the children of RecyclerView do not
* update themselves directly. This will cause a full re-layout but when it happens via the
* Adapter notifyItemChanged, RecyclerView can avoid full layout calculation.
**/
private static final String TRACE_ON_LAYOUT_TAG = "RV OnLayout";
/**
* NotifyDataSetChanged or equal has been called.
* If this is taking a long time, try sending granular notify adapter changes instead of just
* calling notifyDataSetChanged or setAdapter / swapAdapter. Adding stable ids to your adapter
* might help.
**/
private static final String TRACE_ON_DATA_SET_CHANGE_LAYOUT_TAG = "RV FullInvalidate";
/**
* RecyclerView is doing a layout for partial adapter updates (we know what has changed)
* If this is taking a long time, you may have dispatched too many Adapter updates causing too
* many Views being rebind. Make sure all are necessary and also prefer using notify*Range
* methods.
**/
private static final String TRACE_HANDLE_ADAPTER_UPDATES_TAG = "RV PartialInvalidate";
/**
* RecyclerView is rebinding a View.
* If this is taking a lot of time, consider optimizing your layout or make sure you are not
* doing extra operations in onBindViewHolder call.
**/
static final String TRACE_BIND_VIEW_TAG = "RV OnBindView";
/**
* RecyclerView is attempting to pre-populate off screen views.
**/
static final String TRACE_PREFETCH_TAG = "RV Prefetch";
/**
* RecyclerView is attempting to pre-populate off screen itemviews within an off screen
* RecyclerView.
**/
static final String TRACE_NESTED_PREFETCH_TAG = "RV Nested Prefetch";
/**
* RecyclerView is creating a new View.
* If too many of these present in Systrace:
* - There might be a problem in Recycling (e.g. custom Animations that set transient state and
* prevent recycling or ItemAnimator not implementing the contract properly. ({@link
* > Adapter#onFailedToRecycleView(ViewHolder)})
*
* - There might be too many item view types.
* > Try merging them
*
* - There might be too many itemChange animations and not enough space in RecyclerPool.
* >Try increasing your pool size and item cache size.
**/
static final String TRACE_CREATE_VIEW_TAG = "RV CreateView";
private static final Class<?>[] LAYOUT_MANAGER_CONSTRUCTOR_SIGNATURE =
new Class[]{Context.class, AttributeSet.class, int.class, int.class};
private final RecyclerViewDataObserver mObserver = new RecyclerViewDataObserver();
final Recycler mRecycler = new Recycler();
private SavedState mPendingSavedState;
/**
* Handles adapter updates
**/
AdapterHelper mAdapterHelper;
/**
* Handles abstraction between LayoutManager children and RecyclerView children
**/
ChildHelper mChildHelper;
/**
* Keeps data about views to be used for animations
**/
final ViewInfoStore mViewInfoStore = new ViewInfoStore();
/**
* Prior to L, there is no way to query this variable which is why we override the setter and
* track it here.
**/
boolean mClipToPadding;
/**
* Note: this Runnable is only ever posted if:
* 1) We've been through first layout
* 2) We know we have a fixed size (mHasFixedSize)
* 3) We're attached
**/
final Runnable mUpdateChildViewsRunnable = new Runnable() {
@Override
public void run() {
if (!mFirstLayoutComplete || isLayoutRequested()) {
// a layout request will happen, we should not do layout here.
return;
}
if (!mIsAttached) {
requestLayout();
// if we are not attached yet, mark us as requiring layout and skip
return;
}
if (mLayoutFrozen) {
mLayoutRequestEaten = true;
return; //we'll process updates when ice age ends.
}
consumePendingUpdateOperations();
}
};
final Rect mTempRect = new Rect();
private final Rect mTempRect2 = new Rect();
final RectF mTempRectF = new RectF();
Adapter mAdapter;
@VisibleForTesting
LayoutManager mLayout;
RecyclerListener mRecyclerListener;
final ArrayList<ItemDecoration> mItemDecorations = new ArrayList<>();
private final ArrayList<OnItemTouchListener> mOnItemTouchListeners =
new ArrayList<>();
private OnItemTouchListener mActiveOnItemTouchListener;
boolean mIsAttached;
boolean mHasFixedSize;
boolean mEnableFastScroller;
@VisibleForTesting
boolean mFirstLayoutComplete;
// Counting lock to control whether we should ignore requestLayout calls from children or not.
private int mEatRequestLayout = 0;
boolean mLayoutRequestEaten;
boolean mLayoutFrozen;
private boolean mIgnoreMotionEventTillDown;
// binary OR of change events that were eaten during a layout or scroll.
private int mEatenAccessibilityChangeFlags;
boolean mAdapterUpdateDuringMeasure;
private final AccessibilityManager mAccessibilityManager;
private List<OnChildAttachStateChangeListener> mOnChildAttachStateListeners;
/**
* Set to true when an adapter data set changed notification is received.
* In that case, we cannot run any animations since we don't know what happened until layout.
*
* Attached items are invalid until next layout, at which point layout will animate/replace
* items as necessary, building up content from the (effectively) new adapter from scratch.
*
* Cached items must be discarded when setting this to true, so that the cache may be freely
* used by prefetching until the next layout occurs.
*
* @see #setDataSetChangedAfterLayout()
**/
boolean mDataSetHasChangedAfterLayout = false;
/**
* This variable is incremented during a dispatchLayout and/or scroll.
* Some methods should not be called during these periods (e.g. adapter data change).
* Doing so will create hard to find bugs so we better check it and throw an exception.
*
* @see #assertInLayoutOrScroll(String)
* @see #assertNotInLayoutOrScroll(String)
**/
private int mLayoutOrScrollCounter = 0;
/**
* Similar to mLayoutOrScrollCounter but logs a warning instead of throwing an exception
* (for API compatibility).
* <p>
* It is a bad practice for a developer to update the data in a scroll callback since it is
* potentially called during a layout.
**/
private int mDispatchScrollCounter = 0;
private EdgeEffect mLeftGlow, mTopGlow, mRightGlow, mBottomGlow;
ItemAnimator mItemAnimator = new DefaultItemAnimator();
private static final int INVALID_POINTER = -1;
/**
* The RecyclerView is not currently scrolling.
* @see #getScrollState()
**/
public static final int SCROLL_STATE_IDLE = 0;
/**
* The RecyclerView is currently being dragged by outside input such as user touch input.
* @see #getScrollState()
**/
public static final int SCROLL_STATE_DRAGGING = 1;
/**
* The RecyclerView is currently animating to a final position while not under
* outside control.
* @see #getScrollState()
**/
public static final int SCROLL_STATE_SETTLING = 2;
static final long FOREVER_NS = Long.MAX_VALUE;
// Touch/scrolling handling
private int mScrollState = SCROLL_STATE_IDLE;
private int mScrollPointerId = INVALID_POINTER;
private VelocityTracker mVelocityTracker;
private int mInitialTouchX;
private int mInitialTouchY;
private int mLastTouchX;
private int mLastTouchY;
private int mTouchSlop;
private OnFlingListener mOnFlingListener;
private final int mMinFlingVelocity;
private final int mMaxFlingVelocity;
// This value is used when handling rotary encoder generic motion events.
private float mScaledHorizontalScrollFactor = Float.MIN_VALUE;
private float mScaledVerticalScrollFactor = Float.MIN_VALUE;
private boolean mPreserveFocusAfterLayout = true;
final ViewFlinger mViewFlinger = new ViewFlinger();
GapWorker mGapWorker;
GapWorker.LayoutPrefetchRegistryImpl mPrefetchRegistry =
ALLOW_THREAD_GAP_WORK ? new GapWorker.LayoutPrefetchRegistryImpl() : null;
final State mState = new State();
private OnScrollListener mScrollListener;
private List<OnScrollListener> mScrollListeners;
// For use in item animations
boolean mItemsAddedOrRemoved = false;
boolean mItemsChanged = false;
private ItemAnimator.ItemAnimatorListener mItemAnimatorListener =
new ItemAnimatorRestoreListener();
boolean mPostedAnimatorRunner = false;
RecyclerViewAccessibilityDelegate mAccessibilityDelegate;
private ChildDrawingOrderCallback mChildDrawingOrderCallback;
// simple array to keep min and max child position during a layout calculation
// preserved not to create a new one in each layout pass
private final int[] mMinMaxLayoutPositions = new int[2];
private NestedScrollingChildHelper mScrollingChildHelper;
private final int[] mScrollOffset = new int[2];
private final int[] mScrollConsumed = new int[2];
private final int[] mNestedOffsets = new int[2];
/**
* These are views that had their a11y importance changed during a layout. We defer these events
* until the end of the layout because a11y service may make sync calls back to the RV while
* the View's state is undefined.
**/
@VisibleForTesting
final List<ViewHolder> mPendingAccessibilityImportanceChange = new ArrayList<>();
private Runnable mItemAnimatorRunner = new Runnable() {
@Override
public void run() {
if (mItemAnimator != null) {
mItemAnimator.runPendingAnimations();
}
mPostedAnimatorRunner = false;
}
};
static final Interpolator sQuinticInterpolator = new Interpolator() {
@Override
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
/**
* The callback to convert view info diffs into animations.
**/
private final ViewInfoStore.ProcessCallback mViewInfoProcessCallback =
new ViewInfoStore.ProcessCallback() {
@Override
public void processDisappeared(ViewHolder viewHolder, @NonNull ItemHolderInfo info,
@Nullable ItemHolderInfo postInfo) {
mRecycler.unscrapView(viewHolder);
animateDisappearance(viewHolder, info, postInfo);
}
@Override
public void processAppeared(ViewHolder viewHolder,
ItemHolderInfo preInfo, ItemHolderInfo info) {
animateAppearance(viewHolder, preInfo, info);
}
@Override
public void processPersistent(ViewHolder viewHolder,
@NonNull ItemHolderInfo preInfo, @NonNull ItemHolderInfo postInfo) {
viewHolder.setIsRecyclable(false);
if (mDataSetHasChangedAfterLayout) {
// since it was rebound, use change instead as we'll be mapping them from
// stable ids. If stable ids were false, we would not be running any
// animations
if (mItemAnimator.animateChange(viewHolder, viewHolder, preInfo,
postInfo)) {
postAnimationRunner();
}
} else if (mItemAnimator.animatePersistence(viewHolder, preInfo, postInfo)) {
postAnimationRunner();
}
}
@Override
public void unused(ViewHolder viewHolder) {
mLayout.removeAndRecycleView(viewHolder.itemView, mRecycler);
}
};
public RecyclerView(Context context) {
this(context, null);
}
public RecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public RecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, CLIP_TO_PADDING_ATTR, defStyle, 0);
mClipToPadding = a.getBoolean(0, true);
a.recycle();
} else {
mClipToPadding = true;
}
setScrollContainer(true);
setFocusableInTouchMode(true);
final ViewConfiguration vc = ViewConfiguration.get(context);
mTouchSlop = vc.getScaledTouchSlop();
mScaledHorizontalScrollFactor =
ViewConfigurationCompat.getScaledHorizontalScrollFactor(vc, context);
mScaledVerticalScrollFactor =
ViewConfigurationCompat.getScaledVerticalScrollFactor(vc, context);
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
setWillNotDraw(getOverScrollMode() == View.OVER_SCROLL_NEVER);
mItemAnimator.setListener(mItemAnimatorListener);
initAdapterManager();
initChildrenHelper();
// If not explicitly specified this view is important for accessibility.
if (ViewCompat.getImportantForAccessibility(this)
== ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(this,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
mAccessibilityManager = (AccessibilityManager) getContext()
.getSystemService(Context.ACCESSIBILITY_SERVICE);
setAccessibilityDelegateCompat(new RecyclerViewAccessibilityDelegate(this));
// Create the layoutManager if specified.
boolean nestedScrollingEnabled = true;
if (attrs != null) {
int defStyleRes = 0;
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecyclerView,
defStyle, defStyleRes);
String layoutManagerName = a.getString(R.styleable.RecyclerView_layoutManager);
int descendantFocusability = a.getInt(
R.styleable.RecyclerView_android_descendantFocusability, -1);
if (descendantFocusability == -1) {
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
}
mEnableFastScroller = a.getBoolean(R.styleable.RecyclerView_fastScrollEnabled, false);
if (mEnableFastScroller) {
StateListDrawable verticalThumbDrawable = (StateListDrawable) a
.getDrawable(R.styleable.RecyclerView_fastScrollVerticalThumbDrawable);
Drawable verticalTrackDrawable = a
.getDrawable(R.styleable.RecyclerView_fastScrollVerticalTrackDrawable);
StateListDrawable horizontalThumbDrawable = (StateListDrawable) a
.getDrawable(R.styleable.RecyclerView_fastScrollHorizontalThumbDrawable);
Drawable horizontalTrackDrawable = a
.getDrawable(R.styleable.RecyclerView_fastScrollHorizontalTrackDrawable);
initFastScroller(verticalThumbDrawable, verticalTrackDrawable,
horizontalThumbDrawable, horizontalTrackDrawable);
}
a.recycle();
createLayoutManager(context, layoutManagerName, attrs, defStyle, defStyleRes);
if (Build.VERSION.SDK_INT >= 21) {
a = context.obtainStyledAttributes(attrs, NESTED_SCROLLING_ATTRS,
defStyle, defStyleRes);
nestedScrollingEnabled = a.getBoolean(0, true);
a.recycle();
}
} else {
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
}
// Re-set whether nested scrolling is enabled so that it is set on all API levels
setNestedScrollingEnabled(nestedScrollingEnabled);
}
/**
* Label appended to all public exception strings, used to help find which RV in an app is
* hitting an exception.
**/
String exceptionLabel() {
return " " + super.toString()
+ ", adapter:" + mAdapter
+ ", layout:" + mLayout
+ ", context:" + getContext();
}
/**
* Returns the accessibility delegate compatibility implementation used by the RecyclerView.
* @return An instance of AccessibilityDelegateCompat used by RecyclerView
**/
public RecyclerViewAccessibilityDelegate getCompatAccessibilityDelegate() {
return mAccessibilityDelegate;
}
/**
* Sets the accessibility delegate compatibility implementation used by RecyclerView.
* @param accessibilityDelegate The accessibility delegate to be used by RecyclerView.
**/
public void setAccessibilityDelegateCompat(
RecyclerViewAccessibilityDelegate accessibilityDelegate) {
mAccessibilityDelegate = accessibilityDelegate;
ViewCompat.setAccessibilityDelegate(this, mAccessibilityDelegate);
}
/**
* Instantiate and set a LayoutManager, if specified in the attributes.
**/
private void createLayoutManager(Context context, String className, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
if (className != null) {
className = className.trim();
if (!className.isEmpty()) {
className = getFullClassName(context, className);
try {
ClassLoader classLoader;
if (isInEditMode()) {
// Stupid layoutlib cannot handle simple class loaders.
classLoader = this.getClass().getClassLoader();
} else {
classLoader = context.getClassLoader();
}
Class<? extends LayoutManager> layoutManagerClass =
classLoader.loadClass(className).asSubclass(LayoutManager.class);
Constructor<? extends LayoutManager> constructor;
Object[] constructorArgs = null;
try {
constructor = layoutManagerClass
.getConstructor(LAYOUT_MANAGER_CONSTRUCTOR_SIGNATURE);
constructorArgs = new Object[]{context, attrs, defStyleAttr, defStyleRes};
} catch (NoSuchMethodException e) {
try {
constructor = layoutManagerClass.getConstructor();
} catch (NoSuchMethodException e1) {
e1.initCause(e);
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Error creating LayoutManager " + className, e1);
}
}
constructor.setAccessible(true);
setLayoutManager(constructor.newInstance(constructorArgs));
} catch (ClassNotFoundException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Unable to find LayoutManager " + className, e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Could not instantiate the LayoutManager: " + className, e);
} catch (InstantiationException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Could not instantiate the LayoutManager: " + className, e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Cannot access non-public constructor " + className, e);
} catch (ClassCastException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Class is not a LayoutManager " + className, e);
}
}
}
}
private String getFullClassName(Context context, String className) {
if (className.charAt(0) == '.') {
return context.getPackageName() + className;
}
if (className.contains(".")) {
return className;
}
return RecyclerView.class.getPackage().getName() + '.' + className;
}
private void initChildrenHelper() {
mChildHelper = new ChildHelper(new ChildHelper.Callback() {
@Override
public int getChildCount() {
return RecyclerView.this.getChildCount();
}
@Override
public void addView(View child, int index) {
if (VERBOSE_TRACING) {
TraceCompat.beginSection("RV addView");
}
RecyclerView.this.addView(child, index);
if (VERBOSE_TRACING) {
TraceCompat.endSection();
}
dispatchChildAttached(child);
}
@Override
public int indexOfChild(View view) {
return RecyclerView.this.indexOfChild(view);
}
@Override
public void removeViewAt(int index) {
final View child = RecyclerView.this.getChildAt(index);
if (child != null) {
dispatchChildDetached(child);
// Clear any android.view.animation.Animation that may prevent the item from
// detaching when being removed. If a child is re-added before the
// lazy detach occurs, it will receive invalid attach/detach sequencing.
child.clearAnimation();
}
if (VERBOSE_TRACING) {
TraceCompat.beginSection("RV removeViewAt");
}
RecyclerView.this.removeViewAt(index);
if (VERBOSE_TRACING) {
TraceCompat.endSection();
}
}
@Override
public View getChildAt(int offset) {
return RecyclerView.this.getChildAt(offset);
}
@Override
public void removeAllViews() {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
dispatchChildDetached(child);
// Clear any android.view.animation.Animation that may prevent the item from
// detaching when being removed. If a child is re-added before the
// lazy detach occurs, it will receive invalid attach/detach sequencing.
child.clearAnimation();
}
RecyclerView.this.removeAllViews();
}
@Override
public ViewHolder getChildViewHolder(View view) {
return getChildViewHolderInt(view);
}
@Override
public void attachViewToParent(View child, int index,
ViewGroup.LayoutParams layoutParams) {
final ViewHolder vh = getChildViewHolderInt(child);
if (vh != null) {
if (!vh.isTmpDetached() && !vh.shouldIgnore()) {
throw new IllegalArgumentException("Called attach on a child which is not"
+ " detached: " + vh + exceptionLabel());
}
if (DEBUG) {
Log.d(TAG, "reAttach " + vh);
}
vh.clearTmpDetachFlag();
}
RecyclerView.this.attachViewToParent(child, index, layoutParams);
}
@Override
public void detachViewFromParent(int offset) {
final View view = getChildAt(offset);
if (view != null) {
final ViewHolder vh = getChildViewHolderInt(view);
if (vh != null) {
if (vh.isTmpDetached() && !vh.shouldIgnore()) {
throw new IllegalArgumentException("called detach on an already"
+ " detached child " + vh + exceptionLabel());
}
if (DEBUG) {
Log.d(TAG, "tmpDetach " + vh);
}
vh.addFlags(ViewHolder.FLAG_TMP_DETACHED);
}
}
RecyclerView.this.detachViewFromParent(offset);
}
@Override
public void onEnteredHiddenState(View child) {
final ViewHolder vh = getChildViewHolderInt(child);
if (vh != null) {
vh.onEnteredHiddenState(RecyclerView.this);
}
}
@Override
public void onLeftHiddenState(View child) {
final ViewHolder vh = getChildViewHolderInt(child);
if (vh != null) {
vh.onLeftHiddenState(RecyclerView.this);
}
}
});
}
void initAdapterManager() {
mAdapterHelper = new AdapterHelper(new AdapterHelper.Callback() {
@Override
public ViewHolder findViewHolder(int position) {
final ViewHolder vh = findViewHolderForPosition(position, true);
if (vh == null) {
return null;
}
// ensure it is not hidden because for adapter helper, the only thing matter is that
// LM thinks view is a child.
if (mChildHelper.isHidden(vh.itemView)) {
if (DEBUG) {
Log.d(TAG, "assuming view holder cannot be find because it is hidden");
}
return null;
}
return vh;
}
@Override
public void offsetPositionsForRemovingInvisible(int start, int count) {
//处理影响的ViewHolder和没有影响的ViewHolder
offsetPositionRecordsForRemove(start, count, true);
mItemsAddedOrRemoved = true;
mState.mDeletedInvisibleItemCountSincePreviousLayout += count;
}
@Override
public void offsetPositionsForRemovingLaidOutOrNewView(
int positionStart, int itemCount) {
offsetPositionRecordsForRemove(positionStart, itemCount, false);
mItemsAddedOrRemoved = true;
}
@Override
public void markViewHoldersUpdated(int positionStart, int itemCount, Object payload) {
viewRangeUpdate(positionStart, itemCount, payload);
mItemsChanged = true;
}
@Override
public void onDispatchFirstPass(AdapterHelper.UpdateOp op) {
dispatchUpdate(op);
}
void dispatchUpdate(AdapterHelper.UpdateOp op) {
switch (op.cmd) {
case AdapterHelper.UpdateOp.ADD:
mLayout.onItemsAdded(RecyclerView.this, op.positionStart, op.itemCount);
break;
case AdapterHelper.UpdateOp.REMOVE:
mLayout.onItemsRemoved(RecyclerView.this, op.positionStart, op.itemCount);
break;
case AdapterHelper.UpdateOp.UPDATE:
mLayout.onItemsUpdated(RecyclerView.this, op.positionStart, op.itemCount,
op.payload);
break;
case AdapterHelper.UpdateOp.MOVE:
mLayout.onItemsMoved(RecyclerView.this, op.positionStart, op.itemCount, 1);
break;
}
}
@Override
public void onDispatchSecondPass(AdapterHelper.UpdateOp op) {
dispatchUpdate(op);
}
@Override
public void offsetPositionsForAdd(int positionStart, int itemCount) {
offsetPositionRecordsForInsert(positionStart, itemCount);
mItemsAddedOrRemoved = true;
}
@Override
public void offsetPositionsForMove(int from, int to) {
offsetPositionRecordsForMove(from, to);
// should we create mItemsMoved ?
mItemsAddedOrRemoved = true;
}
});
}
/**
* RecyclerView can perform several optimizations if it can know in advance that RecyclerView's
* size is not affected by the adapter contents. RecyclerView can still change its size based
* on other factors (e.g. its parent's size) but this size calculation cannot depend on the
* size of its children or contents of its adapter (except the number of items in the adapter).
* <p>
* If your use of RecyclerView falls into this category, set this to {@code true}. It will allow
* RecyclerView to avoid invalidating the whole layout when its adapter contents change.
*
* @param hasFixedSize true if adapter changes cannot affect the size of the RecyclerView.
**/
public void setHasFixedSize(boolean hasFixedSize) {
mHasFixedSize = hasFixedSize;
}
/**
* @return true if the app has specified that changes in adapter content cannot change
* the size of the RecyclerView itself.
**/
public boolean hasFixedSize() {
return mHasFixedSize;
}
@Override
public void setClipToPadding(boolean clipToPadding) {
if (clipToPadding != mClipToPadding) {
invalidateGlows();
}
mClipToPadding = clipToPadding;
super.setClipToPadding(clipToPadding);
if (mFirstLayoutComplete) {
requestLayout();
}
}
/**
* Returns whether this RecyclerView will clip its children to its padding, and resize (but
* not clip) any EdgeEffect to the padded region, if padding is present.
* <p>
* By default, children are clipped to the padding of their parent
* RecyclerView. This clipping behavior is only enabled if padding is non-zero.
*
* @return true if this RecyclerView clips children to its padding and resizes (but doesn't
* clip) any EdgeEffect to the padded region, false otherwise.
*
* @attr name android:clipToPadding
**/
@Override
public boolean getClipToPadding() {
return mClipToPadding;
}
/**
* Configure the scrolling touch slop for a specific use case.
*
* Set up the RecyclerView's scrolling motion threshold based on common usages.
* Valid arguments are {@link #TOUCH_SLOP_DEFAULT} and {@link #TOUCH_SLOP_PAGING}.
*
* @param slopConstant One of the <code>TOUCH_SLOP_</code> constants representing
* the intended usage of this RecyclerView
**/
public void setScrollingTouchSlop(int slopConstant) {
final ViewConfiguration vc = ViewConfiguration.get(getContext());
switch (slopConstant) {
default:
Log.w(TAG, "setScrollingTouchSlop(): bad argument constant "
+ slopConstant + "; using default value");
// fall-through
case TOUCH_SLOP_DEFAULT:
mTouchSlop = vc.getScaledTouchSlop();
break;
case TOUCH_SLOP_PAGING:
mTouchSlop = vc.getScaledPagingTouchSlop();
break;
}
}
/**
* Swaps the current adapter with the provided one. It is similar to
* {@link #setAdapter(Adapter)} but assumes existing adapter and the new adapter uses the same
* {@link ViewHolder} and does not clear the RecycledViewPool.
* <p>
* Note that it still calls onAdapterChanged callbacks.
*
* @param adapter The new adapter to set, or null to set no adapter.
* @param removeAndRecycleExistingViews If set to true, RecyclerView will recycle all existing
* Views. If adapters have stable ids and/or you want to
* animate the disappearing views, you may prefer to set
* this to false.
* @see #setAdapter(Adapter)
**/
public void swapAdapter(Adapter adapter, boolean removeAndRecycleExistingViews) {
// bail out if layout is frozen
setLayoutFrozen(false);
setAdapterInternal(adapter, true, removeAndRecycleExistingViews);
requestLayout();
}
/**
* Set a new adapter to provide child views on demand.
* <p>
* When adapter is changed, all existing views are recycled back to the pool. If the pool has
* only one adapter, it will be cleared.
*
* @param adapter The new adapter to set, or null to set no adapter.
* @see #swapAdapter(Adapter, boolean)
**/
public void setAdapter(Adapter adapter) {
// bail out if layout is frozen
setLayoutFrozen(false);
//注册观察者
setAdapterInternal(adapter, false, true);
requestLayout();
}
/**
* Removes and recycles all views - both those currently attached, and those in the Recycler.
**/
void removeAndRecycleViews() {
// end all running animations
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
// Since animations are ended, mLayout.children should be equal to
// recyclerView.children. This may not be true if item animator's end does not work as
// expected. (e.g. not release children instantly). It is safer to use mLayout's child
// count.
if (mLayout != null) {
mLayout.removeAndRecycleAllViews(mRecycler);
mLayout.removeAndRecycleScrapInt(mRecycler);
}
// we should clear it here before adapters are swapped to ensure correct callbacks.
mRecycler.clear();
}
/**
* Replaces the current adapter with the new one and triggers listeners.
* @param adapter The new adapter
* @param compatibleWithPrevious If true, the new adapter is using the same View Holders and
* item types with the current adapter (helps us avoid cache
* invalidation).
* @param removeAndRecycleViews If true, we'll remove and recycle all existing views. If
* compatibleWithPrevious is false, this parameter is ignored.
**/
private void setAdapterInternal(Adapter adapter, boolean compatibleWithPrevious,
boolean removeAndRecycleViews) {
if (mAdapter != null) {
mAdapter.unregisterAdapterDataObserver(mObserver);
mAdapter.onDetachedFromRecyclerView(this);
}
if (!compatibleWithPrevious || removeAndRecycleViews) {
removeAndRecycleViews();
}
mAdapterHelper.reset();
final Adapter oldAdapter = mAdapter;
mAdapter = adapter;
if (adapter != null) {
adapter.registerAdapterDataObserver(mObserver);
adapter.onAttachedToRecyclerView(this);
}
if (mLayout != null) {
mLayout.onAdapterChanged(oldAdapter, mAdapter);
}
mRecycler.onAdapterChanged(oldAdapter, mAdapter, compatibleWithPrevious);
mState.mStructureChanged = true;
setDataSetChangedAfterLayout();
}
/**
* Retrieves the previously set adapter or null if no adapter is set.
*
* @return The previously set adapter
* @see #setAdapter(Adapter)
**/
public Adapter getAdapter() {
return mAdapter;
}
/**
* Register a listener that will be notified whenever a child view is recycled.
*
* <p>This listener will be called when a LayoutManager or the RecyclerView decides
* that a child view is no longer needed. If an application associates expensive
* or heavyweight data with item views, this may be a good place to release
* or free those resources.</p>
*
* @param listener Listener to register, or null to clear
**/
public void setRecyclerListener(RecyclerListener listener) {
mRecyclerListener = listener;
}
/**
* <p>Return the offset of the RecyclerView's text baseline from the its top
* boundary. If the LayoutManager of this RecyclerView does not support baseline alignment,
* this method returns -1.</p>
*
* @return the offset of the baseline within the RecyclerView's bounds or -1
* if baseline alignment is not supported
**/
@Override
public int getBaseline() {
if (mLayout != null) {
return mLayout.getBaseline();
} else {
return super.getBaseline();
}
}
/**
* Register a listener that will be notified whenever a child view is attached to or detached
* from RecyclerView.
*
* <p>This listener will be called when a LayoutManager or the RecyclerView decides
* that a child view is no longer needed. If an application associates expensive
* or heavyweight data with item views, this may be a good place to release
* or free those resources.</p>
*
* @param listener Listener to register
**/
public void addOnChildAttachStateChangeListener(OnChildAttachStateChangeListener listener) {
if (mOnChildAttachStateListeners == null) {
mOnChildAttachStateListeners = new ArrayList<>();
}
mOnChildAttachStateListeners.add(listener);
}
/**
* Removes the provided listener from child attached state listeners list.
*
* @param listener Listener to unregister
**/
public void removeOnChildAttachStateChangeListener(OnChildAttachStateChangeListener listener) {
if (mOnChildAttachStateListeners == null) {
return;
}
mOnChildAttachStateListeners.remove(listener);
}
/**
* Removes all listeners that were added via
* {@link #addOnChildAttachStateChangeListener(OnChildAttachStateChangeListener)}.
**/
public void clearOnChildAttachStateChangeListeners() {
if (mOnChildAttachStateListeners != null) {
mOnChildAttachStateListeners.clear();
}
}
/**
* Set the {@link LayoutManager} that this RecyclerView will use.
*
* <p>In contrast to other adapter-backed views such as {@link android.widget.ListView}
* or {@link android.widget.GridView}, RecyclerView allows client code to provide custom
* layout arrangements for child views. These arrangements are controlled by the
* {@link LayoutManager}. A LayoutManager must be provided for RecyclerView to function.</p>
*
* <p>Several default strategies are provided for common uses such as lists and grids.</p>
*
* @param layout LayoutManager to use
**/
public void setLayoutManager(LayoutManager layout) {
if (layout == mLayout) {
return;
}
stopScroll();
// TODO We should do this switch a dispatchLayout pass and animate children. There is a good
// chance that LayoutManagers will re-use views.
if (mLayout != null) {
// end all running animations
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
mLayout.removeAndRecycleAllViews(mRecycler);
mLayout.removeAndRecycleScrapInt(mRecycler);
mRecycler.clear();
if (mIsAttached) {
mLayout.dispatchDetachedFromWindow(this, mRecycler);
}
mLayout.setRecyclerView(null);
mLayout = null;
} else {
mRecycler.clear();
}
// this is just a defensive measure for faulty item animators.
mChildHelper.removeAllViewsUnfiltered();
mLayout = layout;
if (layout != null) {
if (layout.mRecyclerView != null) {
throw new IllegalArgumentException("LayoutManager " + layout
+ " is already attached to a RecyclerView:"
+ layout.mRecyclerView.exceptionLabel());
}
mLayout.setRecyclerView(this);
if (mIsAttached) {
mLayout.dispatchAttachedToWindow(this);
}
}
mRecycler.updateViewCacheSize();
requestLayout();
}
/**
* Set a {@link OnFlingListener} for this {@link RecyclerView}.
* <p>
* If the {@link OnFlingListener} is set then it will receive
* calls to {@link #fling(int, int)} and will be able to intercept them.
*
* @param onFlingListener The {@link OnFlingListener} instance.
**/
public void setOnFlingListener(@Nullable OnFlingListener onFlingListener) {
mOnFlingListener = onFlingListener;
}
/**
* Get the current {@link OnFlingListener} from this {@link RecyclerView}.
*
* @return The {@link OnFlingListener} instance currently set (can be null).
**/
@Nullable
public OnFlingListener getOnFlingListener() {
return mOnFlingListener;
}
@Override
protected Parcelable onSaveInstanceState() {
SavedState state = new SavedState(super.onSaveInstanceState());
if (mPendingSavedState != null) {
state.copyFrom(mPendingSavedState);
} else if (mLayout != null) {
state.mLayoutState = mLayout.onSaveInstanceState();
} else {
state.mLayoutState = null;
}
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
mPendingSavedState = (SavedState) state;
super.onRestoreInstanceState(mPendingSavedState.getSuperState());
if (mLayout != null && mPendingSavedState.mLayoutState != null) {
mLayout.onRestoreInstanceState(mPendingSavedState.mLayoutState);
}
}
/**
* Override to prevent freezing of any views created by the adapter.
**/
@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
dispatchFreezeSelfOnly(container);
}
/**
* Override to prevent thawing of any views created by the adapter.
**/
@Override
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
dispatchThawSelfOnly(container);
}
/**
* Adds a view to the animatingViews list.
* mAnimatingViews holds the child views that are currently being kept around
* purely for the purpose of being animated out of view. They are drawn as a regular
* part of the child list of the RecyclerView, but they are invisible to the LayoutManager
* as they are managed separately from the regular child views.
* @param viewHolder The ViewHolder to be removed
**/
private void addAnimatingView(ViewHolder viewHolder) {
final View view = viewHolder.itemView;
final boolean alreadyParented = view.getParent() == this;
mRecycler.unscrapView(getChildViewHolder(view));
if (viewHolder.isTmpDetached()) {
// re-attach
mChildHelper.attachViewToParent(view, -1, view.getLayoutParams(), true);
} else if (!alreadyParented) {
mChildHelper.addView(view, true);
} else {
mChildHelper.hide(view);
}
}
/**
* Removes a view from the animatingViews list.
* @param view The view to be removed
* @see #addAnimatingView(RecyclerView.ViewHolder)
* @return true if an animating view is removed
**/
boolean removeAnimatingView(View view) {
eatRequestLayout();
final boolean removed = mChildHelper.removeViewIfHidden(view);
if (removed) {
final ViewHolder viewHolder = getChildViewHolderInt(view);
mRecycler.unscrapView(viewHolder);
mRecycler.recycleViewHolderInternal(viewHolder);
if (DEBUG) {
Log.d(TAG, "after removing animated view: " + view + ", " + this);
}
}
// only clear request eaten flag if we removed the view.
resumeRequestLayout(!removed);
return removed;
}
/**
* Return the {@link LayoutManager} currently responsible for
* layout policy for this RecyclerView.
*
* @return The currently bound LayoutManager
**/
public LayoutManager getLayoutManager() {
return mLayout;
}
/**
* Retrieve this RecyclerView's {@link RecycledViewPool}. This method will never return null;
* if no pool is set for this view a new one will be created. See
* {@link #setRecycledViewPool(RecycledViewPool) setRecycledViewPool} for more information.
*
* @return The pool used to store recycled item views for reuse.
* @see #setRecycledViewPool(RecycledViewPool)
**/
public RecycledViewPool getRecycledViewPool() {
return mRecycler.getRecycledViewPool();
}
/**
* Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views.
* This can be useful if you have multiple RecyclerViews with adapters that use the same
* view types, for example if you have several data sets with the same kinds of item views
* displayed by a {@link android.support.v4.view.ViewPager ViewPager}.
*
* @param pool Pool to set. If this parameter is null a new pool will be created and used.
**/
public void setRecycledViewPool(RecycledViewPool pool) {
mRecycler.setRecycledViewPool(pool);
}
/**
* Sets a new {@link ViewCacheExtension} to be used by the Recycler.
*
* @param extension ViewCacheExtension to be used or null if you want to clear the existing one.
*
* @see ViewCacheExtension#getViewForPositionAndType(Recycler, int, int)
**/
public void setViewCacheExtension(ViewCacheExtension extension) {
mRecycler.setViewCacheExtension(extension);
}
/**
* Set the number of offscreen views to retain before adding them to the potentially shared
* {@link #getRecycledViewPool() recycled view pool}.
*
* <p>The offscreen view cache stays aware of changes in the attached adapter, allowing
* a LayoutManager to reuse those views unmodified without needing to return to the adapter
* to rebind them.</p>
*
* @param size Number of views to cache offscreen before returning them to the general
* recycled view pool
**/
public void setItemViewCacheSize(int size) {
mRecycler.setViewCacheSize(size);
}
/**
* Return the current scrolling state of the RecyclerView.
*
* @return {@link #SCROLL_STATE_IDLE}, {@link #SCROLL_STATE_DRAGGING} or
* {@link #SCROLL_STATE_SETTLING}
**/
public int getScrollState() {
return mScrollState;
}
void setScrollState(int state) {
if (state == mScrollState) {
return;
}
if (DEBUG) {
Log.d(TAG, "setting scroll state to " + state + " from " + mScrollState,
new Exception());
}
mScrollState = state;
if (state != SCROLL_STATE_SETTLING) {
stopScrollersInternal();
}
dispatchOnScrollStateChanged(state);
}
/**
* Add an {@link ItemDecoration} to this RecyclerView. Item decorations can
* affect both measurement and drawing of individual item views.
*
* <p>Item decorations are ordered. Decorations placed earlier in the list will
* be run/queried/drawn first for their effects on item views. Padding added to views
* will be nested; a padding added by an earlier decoration will mean further
* item decorations in the list will be asked to draw/pad within the previous decoration's
* given area.</p>
*
* @param decor Decoration to add
* @param index Position in the decoration chain to insert this decoration at. If this value
* is negative the decoration will be added at the end.
**/
public void addItemDecoration(ItemDecoration decor, int index) {
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot add item decoration during a scroll or"
+ " layout");
}
if (mItemDecorations.isEmpty()) {
setWillNotDraw(false);
}
if (index < 0) {
mItemDecorations.add(decor);
} else {
mItemDecorations.add(index, decor);
}
markItemDecorInsetsDirty();
requestLayout();
}
/**
* Add an {@link ItemDecoration} to this RecyclerView. Item decorations can
* affect both measurement and drawing of individual item views.
*
* <p>Item decorations are ordered. Decorations placed earlier in the list will
* be run/queried/drawn first for their effects on item views. Padding added to views
* will be nested; a padding added by an earlier decoration will mean further
* item decorations in the list will be asked to draw/pad within the previous decoration's
* given area.</p>
*
* @param decor Decoration to add
**/
public void addItemDecoration(ItemDecoration decor) {
addItemDecoration(decor, -1);
}
/**
* Returns an {@link ItemDecoration} previously added to this RecyclerView.
*
* @param index The index position of the desired ItemDecoration.
* @return the ItemDecoration at index position, or null if invalid index.
**/
public ItemDecoration getItemDecorationAt(int index) {
final int size = getItemDecorationCount();
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(index + " is an invalid index for size " + size);
}
return mItemDecorations.get(index);
}
/**
* Returns the number of {@link ItemDecoration} currently added to this RecyclerView.
*
* @return number of ItemDecorations currently added added to this RecyclerView.
**/
public int getItemDecorationCount() {
return mItemDecorations.size();
}
/**
* Removes the {@link ItemDecoration} associated with the supplied index position.
*
* @param index The index position of the ItemDecoration to be removed.
**/
public void removeItemDecorationAt(int index) {
final int size = getItemDecorationCount();
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(index + " is an invalid index for size " + size);
}
removeItemDecoration(getItemDecorationAt(index));
}
/**
* Remove an {@link ItemDecoration} from this RecyclerView.
*
* <p>The given decoration will no longer impact the measurement and drawing of
* item views.</p>
*
* @param decor Decoration to remove
* @see #addItemDecoration(ItemDecoration)
**/
public void removeItemDecoration(ItemDecoration decor) {
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot remove item decoration during a scroll or"
+ " layout");
}
mItemDecorations.remove(decor);
if (mItemDecorations.isEmpty()) {
setWillNotDraw(getOverScrollMode() == View.OVER_SCROLL_NEVER);
}
markItemDecorInsetsDirty();
requestLayout();
}
/**
* Sets the {@link ChildDrawingOrderCallback} to be used for drawing children.
* <p>
* See {@link ViewGroup#getChildDrawingOrder(int, int)} for details. Calling this method will
* always call {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean)}. The parameter will be
* true if childDrawingOrderCallback is not null, false otherwise.
* <p>
* Note that child drawing order may be overridden by View's elevation.
*
* @param childDrawingOrderCallback The ChildDrawingOrderCallback to be used by the drawing
* system.
**/
public void setChildDrawingOrderCallback(ChildDrawingOrderCallback childDrawingOrderCallback) {
if (childDrawingOrderCallback == mChildDrawingOrderCallback) {
return;
}
mChildDrawingOrderCallback = childDrawingOrderCallback;
setChildrenDrawingOrderEnabled(mChildDrawingOrderCallback != null);
}
/**
* Set a listener that will be notified of any changes in scroll state or position.
*
* @param listener Listener to set or null to clear
*
* @deprecated Use {@link #addOnScrollListener(OnScrollListener)} and
* {@link #removeOnScrollListener(OnScrollListener)}
**/
@Deprecated
public void setOnScrollListener(OnScrollListener listener) {
mScrollListener = listener;
}
/**
* Add a listener that will be notified of any changes in scroll state or position.
*
* <p>Components that add a listener should take care to remove it when finished.
* Other components that take ownership of a view may call {@link #clearOnScrollListeners()}
* to remove all attached listeners.</p>
*
* @param listener listener to set or null to clear
**/
public void addOnScrollListener(OnScrollListener listener) {
if (mScrollListeners == null) {
mScrollListeners = new ArrayList<>();
}
mScrollListeners.add(listener);
}
/**
* Remove a listener that was notified of any changes in scroll state or position.
*
* @param listener listener to set or null to clear
**/
public void removeOnScrollListener(OnScrollListener listener) {
if (mScrollListeners != null) {
mScrollListeners.remove(listener);
}
}
/**
* Remove all secondary listener that were notified of any changes in scroll state or position.
**/
public void clearOnScrollListeners() {
if (mScrollListeners != null) {
mScrollListeners.clear();
}
}
/**
* Convenience method to scroll to a certain position.
*
* RecyclerView does not implement scrolling logic, rather forwards the call to
* {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)}
* @param position Scroll to this adapter position
* @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)
**/
public void scrollToPosition(int position) {
if (mLayoutFrozen) {
return;
}
stopScroll();
if (mLayout == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return;
}
mLayout.scrollToPosition(position);
awakenScrollBars();
}
void jumpToPositionForSmoothScroller(int position) {
if (mLayout == null) {
return;
}
mLayout.scrollToPosition(position);
awakenScrollBars();
}
/**
* Starts a smooth scroll to an adapter position.
* <p>
* To support smooth scrolling, you must override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} and create a
* {@link SmoothScroller}.
* <p>
* {@link LayoutManager} is responsible for creating the actual scroll action. If you want to
* provide a custom smooth scroll logic, override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} in your
* LayoutManager.
*
* @param position The adapter position to scroll to
* @see LayoutManager#smoothScrollToPosition(RecyclerView, State, int)
**/
public void smoothScrollToPosition(int position) {
if (mLayoutFrozen) {
return;
}
if (mLayout == null) {
Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return;
}
mLayout.smoothScrollToPosition(this, mState, position);
}
@Override
public void scrollTo(int x, int y) {
Log.w(TAG, "RecyclerView does not support scrolling to an absolute position. "
+ "Use scrollToPosition instead");
}
@Override
public void scrollBy(int x, int y) {
if (mLayout == null) {
Log.e(TAG, "Cannot scroll without a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return;
}
if (mLayoutFrozen) {
return;
}
final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
final boolean canScrollVertical = mLayout.canScrollVertically();
if (canScrollHorizontal || canScrollVertical) {
scrollByInternal(canScrollHorizontal ? x : 0, canScrollVertical ? y : 0, null);
}
}
/**
* Helper method reflect data changes to the state.
* <p>
* Adapter changes during a scroll may trigger a crash because scroll assumes no data change
* but data actually changed.
* <p>
* This method consumes all deferred changes to avoid that case.
**/
void consumePendingUpdateOperations() {
if (!mFirstLayoutComplete || mDataSetHasChangedAfterLayout) {
TraceCompat.beginSection(TRACE_ON_DATA_SET_CHANGE_LAYOUT_TAG);
dispatchLayout();
TraceCompat.endSection();
return;
}
if (!mAdapterHelper.hasPendingUpdates()) {
return;
}
// if it is only an item change (no add-remove-notifyDataSetChanged) we can check if any
// of the visible items is affected and if not, just ignore the change.
if (mAdapterHelper.hasAnyUpdateTypes(AdapterHelper.UpdateOp.UPDATE) && !mAdapterHelper
.hasAnyUpdateTypes(AdapterHelper.UpdateOp.ADD | AdapterHelper.UpdateOp.REMOVE
| AdapterHelper.UpdateOp.MOVE)) {
TraceCompat.beginSection(TRACE_HANDLE_ADAPTER_UPDATES_TAG);
eatRequestLayout();
onEnterLayoutOrScroll();
mAdapterHelper.preProcess();
if (!mLayoutRequestEaten) {
if (hasUpdatedView()) {
dispatchLayout();
} else {
// no need to layout, clean state
mAdapterHelper.consumePostponedUpdates();
}
}
resumeRequestLayout(true);
onExitLayoutOrScroll();
TraceCompat.endSection();
} else if (mAdapterHelper.hasPendingUpdates()) {
TraceCompat.beginSection(TRACE_ON_DATA_SET_CHANGE_LAYOUT_TAG);
dispatchLayout();
TraceCompat.endSection();
}
}
/**
* @return True if an existing view holder needs to be updated
**/
private boolean hasUpdatedView() {
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder == null || holder.shouldIgnore()) {
continue;
}
if (holder.isUpdated()) {
return true;
}
}
return false;
}
/**
* Does not perform bounds checking. Used by internal methods that have already validated input.
* <p>
* It also reports any unused scroll request to the related EdgeEffect.
*
* @param x The amount of horizontal scroll request
* @param y The amount of vertical scroll request
* @param ev The originating MotionEvent, or null if not from a touch event.
*
* @return Whether any scroll was consumed in either direction.
**/
boolean scrollByInternal(int x, int y, MotionEvent ev) {
int unconsumedX = 0, unconsumedY = 0;
int consumedX = 0, consumedY = 0;
consumePendingUpdateOperations();
if (mAdapter != null) {
eatRequestLayout();
onEnterLayoutOrScroll();
TraceCompat.beginSection(TRACE_SCROLL_TAG);
fillRemainingScrollValues(mState);
if (x != 0) {
consumedX = mLayout.scrollHorizontallyBy(x, mRecycler, mState);
unconsumedX = x - consumedX;
}
if (y != 0) {
consumedY = mLayout.scrollVerticallyBy(y, mRecycler, mState);
unconsumedY = y - consumedY;
}
TraceCompat.endSection();
repositionShadowingViews();
onExitLayoutOrScroll();
resumeRequestLayout(false);
}
if (!mItemDecorations.isEmpty()) {
invalidate();
}
if (dispatchNestedScroll(consumedX, consumedY, unconsumedX, unconsumedY, mScrollOffset,
TYPE_TOUCH)) {
// Update the last touch co-ords, taking any scroll offset into account
mLastTouchX -= mScrollOffset[0];
mLastTouchY -= mScrollOffset[1];
if (ev != null) {
ev.offsetLocation(mScrollOffset[0], mScrollOffset[1]);
}
mNestedOffsets[0] += mScrollOffset[0];
mNestedOffsets[1] += mScrollOffset[1];
} else if (getOverScrollMode() != View.OVER_SCROLL_NEVER) {
if (ev != null && !MotionEventCompat.isFromSource(ev, InputDevice.SOURCE_MOUSE)) {
pullGlows(ev.getX(), unconsumedX, ev.getY(), unconsumedY);
}
considerReleasingGlowsOnScroll(x, y);
}
if (consumedX != 0 || consumedY != 0) {
dispatchOnScrolled(consumedX, consumedY);
}
if (!awakenScrollBars()) {
invalidate();
}
return consumedX != 0 || consumedY != 0;
}
/**
* <p>Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal
* range. This value is used to compute the length of the thumb within the scrollbar's track.
* </p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollExtent()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeHorizontalScrollOffset(RecyclerView.State)} in your
* LayoutManager. </p>
*
* @return The horizontal offset of the scrollbar's thumb
* @see android.support.v7.widget.RecyclerView.LayoutManager#computeHorizontalScrollOffset
* (RecyclerView.State)
**/
@Override
public int computeHorizontalScrollOffset() {
if (mLayout == null) {
return 0;
}
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollOffset(mState) : 0;
}
/**
* <p>Compute the horizontal extent of the horizontal scrollbar's thumb within the
* horizontal range. This value is used to compute the length of the thumb within the
* scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The horizontal extent of the scrollbar's thumb
* @see RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)
**/
@Override
public int computeHorizontalScrollExtent() {
if (mLayout == null) {
return 0;
}
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollExtent(mState) : 0;
}
/**
* <p>Compute the horizontal range that the horizontal scrollbar represents.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeHorizontalScrollExtent()} and {@link #computeHorizontalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The total horizontal range represented by the vertical scrollbar
* @see RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)
**/
@Override
public int computeHorizontalScrollRange() {
if (mLayout == null) {
return 0;
}
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollRange(mState) : 0;
}
/**
* <p>Compute the vertical offset of the vertical scrollbar's thumb within the vertical range.
* This value is used to compute the length of the thumb within the scrollbar's track. </p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollExtent()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeVerticalScrollOffset(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The vertical offset of the scrollbar's thumb
* @see android.support.v7.widget.RecyclerView.LayoutManager#computeVerticalScrollOffset
* (RecyclerView.State)
**/
@Override
public int computeVerticalScrollOffset() {
if (mLayout == null) {
return 0;
}
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollOffset(mState) : 0;
}
/**
* <p>Compute the vertical extent of the vertical scrollbar's thumb within the vertical range.
* This value is used to compute the length of the thumb within the scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The vertical extent of the scrollbar's thumb
* @see RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)
**/
@Override
public int computeVerticalScrollExtent() {
if (mLayout == null) {
return 0;
}
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollExtent(mState) : 0;
}
/**
* <p>Compute the vertical range that the vertical scrollbar represents.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeVerticalScrollExtent()} and {@link #computeVerticalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The total vertical range represented by the vertical scrollbar
* @see RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)
**/
@Override
public int computeVerticalScrollRange() {
if (mLayout == null) {
return 0;
}
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollRange(mState) : 0;
}
void eatRequestLayout() {
mEatRequestLayout++;
if (mEatRequestLayout == 1 && !mLayoutFrozen) {
mLayoutRequestEaten = false;
}
}
void resumeRequestLayout(boolean performLayoutChildren) {
if (mEatRequestLayout < 1) {
//noinspection PointlessBooleanExpression
if (DEBUG) {
throw new IllegalStateException("invalid eat request layout count"
+ exceptionLabel());
}
mEatRequestLayout = 1;
}
if (!performLayoutChildren) {
// Reset the layout request eaten counter.
// This is necessary since eatRequest calls can be nested in which case the other
// call will override the inner one.
// for instance:
// eat layout for process adapter updates
// eat layout for dispatchLayout
// a bunch of req layout calls arrive
mLayoutRequestEaten = false;
}
if (mEatRequestLayout == 1) {
// when layout is frozen we should delay dispatchLayout()
if (performLayoutChildren && mLayoutRequestEaten && !mLayoutFrozen
&& mLayout != null && mAdapter != null) {
dispatchLayout();
}
if (!mLayoutFrozen) {
mLayoutRequestEaten = false;
}
}
mEatRequestLayout--;
}
/**
* Enable or disable layout and scroll. After <code>setLayoutFrozen(true)</code> is called,
* Layout requests will be postponed until <code>setLayoutFrozen(false)</code> is called;
* child views are not updated when RecyclerView is frozen, {@link #smoothScrollBy(int, int)},
* {@link #scrollBy(int, int)}, {@link #scrollToPosition(int)} and
* {@link #smoothScrollToPosition(int)} are dropped; TouchEvents and GenericMotionEvents are
* dropped; {@link LayoutManager#onFocusSearchFailed(View, int, Recycler, State)} will not be
* called.
*
* <p>
* <code>setLayoutFrozen(true)</code> does not prevent app from directly calling {@link
* LayoutManager#scrollToPosition(int)}, {@link LayoutManager#smoothScrollToPosition(
*RecyclerView, State, int)}.
* <p>
* {@link #setAdapter(Adapter)} and {@link #swapAdapter(Adapter, boolean)} will automatically
* stop frozen.
* <p>
* Note: Running ItemAnimator is not stopped automatically, it's caller's
* responsibility to call ItemAnimator.end().
*
* @param frozen true to freeze layout and scroll, false to re-enable.
**/
public void setLayoutFrozen(boolean frozen) {
if (frozen != mLayoutFrozen) {
assertNotInLayoutOrScroll("Do not setLayoutFrozen in layout or scroll");
if (!frozen) {
mLayoutFrozen = false;
if (mLayoutRequestEaten && mLayout != null && mAdapter != null) {
requestLayout();
}
mLayoutRequestEaten = false;
} else {
final long now = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
onTouchEvent(cancelEvent);
mLayoutFrozen = true;
mIgnoreMotionEventTillDown = true;
stopScroll();
}
}
}
/**
* Returns true if layout and scroll are frozen.
*
* @return true if layout and scroll are frozen
* @see #setLayoutFrozen(boolean)
**/
public boolean isLayoutFrozen() {
return mLayoutFrozen;
}
/**
* Animate a scroll by the given amount of pixels along either axis.
*
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
**/
public void smoothScrollBy(int dx, int dy) {
smoothScrollBy(dx, dy, null);
}
/**
* Animate a scroll by the given amount of pixels along either axis.
*
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param interpolator {@link Interpolator} to be used for scrolling. If it is
* {@code null}, RecyclerView is going to use the default interpolator.
**/
public void smoothScrollBy(int dx, int dy, Interpolator interpolator) {
if (mLayout == null) {
Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return;
}
if (mLayoutFrozen) {
return;
}
if (!mLayout.canScrollHorizontally()) {
dx = 0;
}
if (!mLayout.canScrollVertically()) {
dy = 0;
}
if (dx != 0 || dy != 0) {
mViewFlinger.smoothScrollBy(dx, dy, interpolator);
}
}
/**
* Begin a standard fling with an initial velocity along each axis in pixels per second.
* If the velocity given is below the system-defined minimum this method will return false
* and no fling will occur.
*
* @param velocityX Initial horizontal velocity in pixels per second
* @param velocityY Initial vertical velocity in pixels per second
* @return true if the fling was started, false if the velocity was too low to fling or
* LayoutManager does not support scrolling in the axis fling is issued.
*
* @see LayoutManager#canScrollVertically()
* @see LayoutManager#canScrollHorizontally()
**/
public boolean fling(int velocityX, int velocityY) {
if (mLayout == null) {
Log.e(TAG, "Cannot fling without a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return false;
}
if (mLayoutFrozen) {
return false;
}
final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
final boolean canScrollVertical = mLayout.canScrollVertically();
if (!canScrollHorizontal || Math.abs(velocityX) < mMinFlingVelocity) {
velocityX = 0;
}
if (!canScrollVertical || Math.abs(velocityY) < mMinFlingVelocity) {
velocityY = 0;
}
if (velocityX == 0 && velocityY == 0) {
// If we don't have any velocity, return false
return false;
}
if (!dispatchNestedPreFling(velocityX, velocityY)) {
final boolean canScroll = canScrollHorizontal || canScrollVertical;
dispatchNestedFling(velocityX, velocityY, canScroll);
if (mOnFlingListener != null && mOnFlingListener.onFling(velocityX, velocityY)) {
return true;
}
if (canScroll) {
int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE;
if (canScrollHorizontal) {
nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL;
}
if (canScrollVertical) {
nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL;
}
startNestedScroll(nestedScrollAxis, TYPE_NON_TOUCH);
velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity));
velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity));
mViewFlinger.fling(velocityX, velocityY);
return true;
}
}
return false;
}
/**
* Stop any current scroll in progress, such as one started by
* {@link #smoothScrollBy(int, int)}, {@link #fling(int, int)} or a touch-initiated fling.
**/
public void stopScroll() {
setScrollState(SCROLL_STATE_IDLE);
stopScrollersInternal();
}
/**
* Similar to {@link #stopScroll()} but does not set the state.
**/
private void stopScrollersInternal() {
mViewFlinger.stop();
if (mLayout != null) {
mLayout.stopSmoothScroller();
}
}
/**
* Returns the minimum velocity to start a fling.
*
* @return The minimum velocity to start a fling
**/
public int getMinFlingVelocity() {
return mMinFlingVelocity;
}
/**
* Returns the maximum fling velocity used by this RecyclerView.
*
* @return The maximum fling velocity used by this RecyclerView.
**/
public int getMaxFlingVelocity() {
return mMaxFlingVelocity;
}
/**
* Apply a pull to relevant overscroll glow effects
**/
private void pullGlows(float x, float overscrollX, float y, float overscrollY) {
boolean invalidate = false;
if (overscrollX < 0) {
ensureLeftGlow();
EdgeEffectCompat.onPull(mLeftGlow, -overscrollX / getWidth(), 1f - y / getHeight());
invalidate = true;
} else if (overscrollX > 0) {
ensureRightGlow();
EdgeEffectCompat.onPull(mRightGlow, overscrollX / getWidth(), y / getHeight());
invalidate = true;
}
if (overscrollY < 0) {
ensureTopGlow();
EdgeEffectCompat.onPull(mTopGlow, -overscrollY / getHeight(), x / getWidth());
invalidate = true;
} else if (overscrollY > 0) {
ensureBottomGlow();
EdgeEffectCompat.onPull(mBottomGlow, overscrollY / getHeight(), 1f - x / getWidth());
invalidate = true;
}
if (invalidate || overscrollX != 0 || overscrollY != 0) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private void releaseGlows() {
boolean needsInvalidate = false;
if (mLeftGlow != null) {
mLeftGlow.onRelease();
needsInvalidate = mLeftGlow.isFinished();
}
if (mTopGlow != null) {
mTopGlow.onRelease();
needsInvalidate |= mTopGlow.isFinished();
}
if (mRightGlow != null) {
mRightGlow.onRelease();
needsInvalidate |= mRightGlow.isFinished();
}
if (mBottomGlow != null) {
mBottomGlow.onRelease();
needsInvalidate |= mBottomGlow.isFinished();
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
void considerReleasingGlowsOnScroll(int dx, int dy) {
boolean needsInvalidate = false;
if (mLeftGlow != null && !mLeftGlow.isFinished() && dx > 0) {
mLeftGlow.onRelease();
needsInvalidate = mLeftGlow.isFinished();
}
if (mRightGlow != null && !mRightGlow.isFinished() && dx < 0) {
mRightGlow.onRelease();
needsInvalidate |= mRightGlow.isFinished();
}
if (mTopGlow != null && !mTopGlow.isFinished() && dy > 0) {
mTopGlow.onRelease();
needsInvalidate |= mTopGlow.isFinished();
}
if (mBottomGlow != null && !mBottomGlow.isFinished() && dy < 0) {
mBottomGlow.onRelease();
needsInvalidate |= mBottomGlow.isFinished();
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
void absorbGlows(int velocityX, int velocityY) {
if (velocityX < 0) {
ensureLeftGlow();
mLeftGlow.onAbsorb(-velocityX);
} else if (velocityX > 0) {
ensureRightGlow();
mRightGlow.onAbsorb(velocityX);
}
if (velocityY < 0) {
ensureTopGlow();
mTopGlow.onAbsorb(-velocityY);
} else if (velocityY > 0) {
ensureBottomGlow();
mBottomGlow.onAbsorb(velocityY);
}
if (velocityX != 0 || velocityY != 0) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
void ensureLeftGlow() {
if (mLeftGlow != null) {
return;
}
mLeftGlow = new EdgeEffect(getContext());
if (mClipToPadding) {
mLeftGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
} else {
mLeftGlow.setSize(getMeasuredHeight(), getMeasuredWidth());
}
}
void ensureRightGlow() {
if (mRightGlow != null) {
return;
}
mRightGlow = new EdgeEffect(getContext());
if (mClipToPadding) {
mRightGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
} else {
mRightGlow.setSize(getMeasuredHeight(), getMeasuredWidth());
}
}
void ensureTopGlow() {
if (mTopGlow != null) {
return;
}
mTopGlow = new EdgeEffect(getContext());
if (mClipToPadding) {
mTopGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
} else {
mTopGlow.setSize(getMeasuredWidth(), getMeasuredHeight());
}
}
void ensureBottomGlow() {
if (mBottomGlow != null) {
return;
}
mBottomGlow = new EdgeEffect(getContext());
if (mClipToPadding) {
mBottomGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
} else {
mBottomGlow.setSize(getMeasuredWidth(), getMeasuredHeight());
}
}
void invalidateGlows() {
mLeftGlow = mRightGlow = mTopGlow = mBottomGlow = null;
}
/**
* Since RecyclerView is a collection ViewGroup that includes virtual children (items that are
* in the Adapter but not visible in the UI), it employs a more involved focus search strategy
* that differs from other ViewGroups.
* <p>
* It first does a focus search within the RecyclerView. If this search finds a View that is in
* the focus direction with respect to the currently focused View, RecyclerView returns that
* child as the next focus target. When it cannot find such child, it calls
* {@link LayoutManager#onFocusSearchFailed(View, int, Recycler, State)} to layout more Views
* in the focus search direction. If LayoutManager adds a View that matches the
* focus search criteria, it will be returned as the focus search result. Otherwise,
* RecyclerView will call parent to handle the focus search like a regular ViewGroup.
* <p>
* When the direction is {@link View#FOCUS_FORWARD} or {@link View#FOCUS_BACKWARD}, a View that
* is not in the focus direction is still valid focus target which may not be the desired
* behavior if the Adapter has more children in the focus direction. To handle this case,
* RecyclerView converts the focus direction to an absolute direction and makes a preliminary
* focus search in that direction. If there are no Views to gain focus, it will call
* {@link LayoutManager#onFocusSearchFailed(View, int, Recycler, State)} before running a
* focus search with the original (relative) direction. This allows RecyclerView to provide
* better candidates to the focus search while still allowing the view system to take focus from
* the RecyclerView and give it to a more suitable child if such child exists.
*
* @param focused The view that currently has focus
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, {@link View#FOCUS_FORWARD},
* {@link View#FOCUS_BACKWARD} or 0 for not applicable.
*
* @return A new View that can be the next focus after the focused View
**/
@Override
public View focusSearch(View focused, int direction) {
View result = mLayout.onInterceptFocusSearch(focused, direction);
if (result != null) {
return result;
}
final boolean canRunFocusFailure = mAdapter != null && mLayout != null
&& !isComputingLayout() && !mLayoutFrozen;
final FocusFinder ff = FocusFinder.getInstance();
if (canRunFocusFailure
&& (direction == View.FOCUS_FORWARD || direction == View.FOCUS_BACKWARD)) {
// convert direction to absolute direction and see if we have a view there and if not
// tell LayoutManager to add if it can.
boolean needsFocusFailureLayout = false;
if (mLayout.canScrollVertically()) {
final int absDir =
direction == View.FOCUS_FORWARD ? View.FOCUS_DOWN : View.FOCUS_UP;
final View found = ff.findNextFocus(this, focused, absDir);
needsFocusFailureLayout = found == null;
if (FORCE_ABS_FOCUS_SEARCH_DIRECTION) {
// Workaround for broken FOCUS_BACKWARD in API 15 and older devices.
direction = absDir;
}
}
if (!needsFocusFailureLayout && mLayout.canScrollHorizontally()) {
boolean rtl = mLayout.getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL;
final int absDir = (direction == View.FOCUS_FORWARD) ^ rtl
? View.FOCUS_RIGHT : View.FOCUS_LEFT;
final View found = ff.findNextFocus(this, focused, absDir);
needsFocusFailureLayout = found == null;
if (FORCE_ABS_FOCUS_SEARCH_DIRECTION) {
// Workaround for broken FOCUS_BACKWARD in API 15 and older devices.
direction = absDir;
}
}
if (needsFocusFailureLayout) {
consumePendingUpdateOperations();
final View focusedItemView = findContainingItemView(focused);
if (focusedItemView == null) {
// panic, focused view is not a child anymore, cannot call super.
return null;
}
eatRequestLayout();
mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState);
resumeRequestLayout(false);
}
result = ff.findNextFocus(this, focused, direction);
} else {
result = ff.findNextFocus(this, focused, direction);
if (result == null && canRunFocusFailure) {
consumePendingUpdateOperations();
final View focusedItemView = findContainingItemView(focused);
if (focusedItemView == null) {
// panic, focused view is not a child anymore, cannot call super.
return null;
}
eatRequestLayout();
result = mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState);
resumeRequestLayout(false);
}
}
if (result != null && !result.hasFocusable()) {
if (getFocusedChild() == null) {
// Scrolling to this unfocusable view is not meaningful since there is no currently
// focused view which RV needs to keep visible.
return super.focusSearch(focused, direction);
}
// If the next view returned by onFocusSearchFailed in layout manager has no focusable
// views, we still scroll to that view in order to make it visible on the screen.
// If it's focusable, framework already calls RV's requestChildFocus which handles
// bringing this newly focused item onto the screen.
requestChildOnScreen(result, null);
return focused;
}
return isPreferredNextFocus(focused, result, direction)
? result : super.focusSearch(focused, direction);
}
/**
* Checks if the new focus candidate is a good enough candidate such that RecyclerView will
* assign it as the next focus View instead of letting view hierarchy decide.
* A good candidate means a View that is aligned in the focus direction wrt the focused View
* and is not the RecyclerView itself.
* When this method returns false, RecyclerView will let the parent make the decision so the
* same View may still get the focus as a result of that search.
**/
private boolean isPreferredNextFocus(View focused, View next, int direction) {
if (next == null || next == this) {
return false;
}
if (focused == null) {
return true;
}
mTempRect.set(0, 0, focused.getWidth(), focused.getHeight());
mTempRect2.set(0, 0, next.getWidth(), next.getHeight());
offsetDescendantRectToMyCoords(focused, mTempRect);
offsetDescendantRectToMyCoords(next, mTempRect2);
final int rtl = mLayout.getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL ? -1 : 1;
int rightness = 0;
if ((mTempRect.left < mTempRect2.left
|| mTempRect.right <= mTempRect2.left)
&& mTempRect.right < mTempRect2.right) {
rightness = 1;
} else if ((mTempRect.right > mTempRect2.right
|| mTempRect.left >= mTempRect2.right)
&& mTempRect.left > mTempRect2.left) {
rightness = -1;
}
int downness = 0;
if ((mTempRect.top < mTempRect2.top
|| mTempRect.bottom <= mTempRect2.top)
&& mTempRect.bottom < mTempRect2.bottom) {
downness = 1;
} else if ((mTempRect.bottom > mTempRect2.bottom
|| mTempRect.top >= mTempRect2.bottom)
&& mTempRect.top > mTempRect2.top) {
downness = -1;
}
switch (direction) {
case View.FOCUS_LEFT:
return rightness < 0;
case View.FOCUS_RIGHT:
return rightness > 0;
case View.FOCUS_UP:
return downness < 0;
case View.FOCUS_DOWN:
return downness > 0;
case View.FOCUS_FORWARD:
return downness > 0 || (downness == 0 && rightness * rtl >= 0);
case View.FOCUS_BACKWARD:
return downness < 0 || (downness == 0 && rightness * rtl <= 0);
}
throw new IllegalArgumentException("Invalid direction: " + direction + exceptionLabel());
}
@Override
public void requestChildFocus(View child, View focused) {
if (!mLayout.onRequestChildFocus(this, mState, child, focused) && focused != null) {
requestChildOnScreen(child, focused);
}
super.requestChildFocus(child, focused);
}
/**
* Requests that the given child of the RecyclerView be positioned onto the screen. This method
* can be called for both unfocusable and focusable child views. For unfocusable child views,
* the {@param focused} parameter passed is null, whereas for a focusable child, this parameter
* indicates the actual descendant view within this child view that holds the focus.
* @param child The child view of this RecyclerView that wants to come onto the screen.
* @param focused The descendant view that actually has the focus if child is focusable, null
* otherwise.
**/
private void requestChildOnScreen(@NonNull View child, @Nullable View focused) {
View rectView = (focused != null) ? focused : child;
mTempRect.set(0, 0, rectView.getWidth(), rectView.getHeight());
// get item decor offsets w/o refreshing. If they are invalid, there will be another
// layout pass to fix them, then it is LayoutManager's responsibility to keep focused
// View in viewport.
final ViewGroup.LayoutParams focusedLayoutParams = rectView.getLayoutParams();
if (focusedLayoutParams instanceof LayoutParams) {
// if focused child has item decors, use them. Otherwise, ignore.
final LayoutParams lp = (LayoutParams) focusedLayoutParams;
if (!lp.mInsetsDirty) {
final Rect insets = lp.mDecorInsets;
mTempRect.left -= insets.left;
mTempRect.right += insets.right;
mTempRect.top -= insets.top;
mTempRect.bottom += insets.bottom;
}
}
if (focused != null) {
offsetDescendantRectToMyCoords(focused, mTempRect);
offsetRectIntoDescendantCoords(child, mTempRect);
}
mLayout.requestChildRectangleOnScreen(this, child, mTempRect, !mFirstLayoutComplete,
(focused == null));
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
return mLayout.requestChildRectangleOnScreen(this, child, rect, immediate);
}
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
if (mLayout == null || !mLayout.onAddFocusables(this, views, direction, focusableMode)) {
super.addFocusables(views, direction, focusableMode);
}
}
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
if (isComputingLayout()) {
// if we are in the middle of a layout calculation, don't let any child take focus.
// RV will handle it after layout calculation is finished.
return false;
}
return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mLayoutOrScrollCounter = 0;
mIsAttached = true;
mFirstLayoutComplete = mFirstLayoutComplete && !isLayoutRequested();
if (mLayout != null) {
mLayout.dispatchAttachedToWindow(this);
}
mPostedAnimatorRunner = false;
if (ALLOW_THREAD_GAP_WORK) {
// Register with gap worker
mGapWorker = GapWorker.sGapWorker.get();
if (mGapWorker == null) {
mGapWorker = new GapWorker();
// break 60 fps assumption if data from display appears valid
// NOTE: we only do this query once, statically, because it's very expensive (> 1ms)
Display display = ViewCompat.getDisplay(this);
float refreshRate = 60.0f;
if (!isInEditMode() && display != null) {
float displayRefreshRate = display.getRefreshRate();
if (displayRefreshRate >= 30.0f) {
refreshRate = displayRefreshRate;
}
}
mGapWorker.mFrameIntervalNs = (long) (1000000000 / refreshRate);
GapWorker.sGapWorker.set(mGapWorker);
}
mGapWorker.add(this);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
stopScroll();
mIsAttached = false;
if (mLayout != null) {
mLayout.dispatchDetachedFromWindow(this, mRecycler);
}
mPendingAccessibilityImportanceChange.clear();
removeCallbacks(mItemAnimatorRunner);
mViewInfoStore.onDetach();
if (ALLOW_THREAD_GAP_WORK) {
// Unregister with gap worker
mGapWorker.remove(this);
mGapWorker = null;
}
}
/**
* Returns true if RecyclerView is attached to window.
**/
@Override
public boolean isAttachedToWindow() {
return mIsAttached;
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is not</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertNotInLayoutOrScroll(String)
**/
void assertInLayoutOrScroll(String message) {
if (!isComputingLayout()) {
if (message == null) {
throw new IllegalStateException("Cannot call this method unless RecyclerView is "
+ "computing a layout or scrolling" + exceptionLabel());
}
throw new IllegalStateException(message + exceptionLabel());
}
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertInLayoutOrScroll(String)
**/
void assertNotInLayoutOrScroll(String message) {
if (isComputingLayout()) {
if (message == null) {
throw new IllegalStateException("Cannot call this method while RecyclerView is "
+ "computing a layout or scrolling" + exceptionLabel());
}
throw new IllegalStateException(message);
}
if (mDispatchScrollCounter > 0) {
Log.w(TAG, "Cannot call this method in a scroll callback. Scroll callbacks might"
+ "be run during a measure & layout pass where you cannot change the"
+ "RecyclerView data. Any method call that might change the structure"
+ "of the RecyclerView or the adapter contents should be postponed to"
+ "the next frame.",
new IllegalStateException("" + exceptionLabel()));
}
}
/**
* Add an {@link OnItemTouchListener} to intercept touch events before they are dispatched
* to child views or this view's standard scrolling behavior.
*
* <p>Client code may use listeners to implement item manipulation behavior. Once a listener
* returns true from
* {@link OnItemTouchListener#onInterceptTouchEvent(RecyclerView, MotionEvent)} its
* {@link OnItemTouchListener#onTouchEvent(RecyclerView, MotionEvent)} method will be called
* for each incoming MotionEvent until the end of the gesture.</p>
*
* @param listener Listener to add
* @see SimpleOnItemTouchListener
**/
public void addOnItemTouchListener(OnItemTouchListener listener) {
mOnItemTouchListeners.add(listener);
}
/**
* Remove an {@link OnItemTouchListener}. It will no longer be able to intercept touch events.
*
* @param listener Listener to remove
**/
public void removeOnItemTouchListener(OnItemTouchListener listener) {
mOnItemTouchListeners.remove(listener);
if (mActiveOnItemTouchListener == listener) {
mActiveOnItemTouchListener = null;
}
}
private boolean dispatchOnItemTouchIntercept(MotionEvent e) {
final int action = e.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_DOWN) {
mActiveOnItemTouchListener = null;
}
final int listenerCount = mOnItemTouchListeners.size();
for (int i = 0; i < listenerCount; i++) {
final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
if (listener.onInterceptTouchEvent(this, e) && action != MotionEvent.ACTION_CANCEL) {
mActiveOnItemTouchListener = listener;
return true;
}
}
return false;
}
private boolean dispatchOnItemTouch(MotionEvent e) {
final int action = e.getAction();
if (mActiveOnItemTouchListener != null) {
if (action == MotionEvent.ACTION_DOWN) {
// Stale state from a previous gesture, we're starting a new one. Clear it.
mActiveOnItemTouchListener = null;
} else {
mActiveOnItemTouchListener.onTouchEvent(this, e);
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Clean up for the next gesture.
mActiveOnItemTouchListener = null;
}
return true;
}
}
// Listeners will have already received the ACTION_DOWN via dispatchOnItemTouchIntercept
// as called from onInterceptTouchEvent; skip it.
if (action != MotionEvent.ACTION_DOWN) {
final int listenerCount = mOnItemTouchListeners.size();
for (int i = 0; i < listenerCount; i++) {
final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
if (listener.onInterceptTouchEvent(this, e)) {
mActiveOnItemTouchListener = listener;
return true;
}
}
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (mLayoutFrozen) {
// When layout is frozen, RV does not intercept the motion event.
// A child view e.g. a button may still get the click.
return false;
}
if (dispatchOnItemTouchIntercept(e)) {
cancelTouch();
return true;
}
if (mLayout == null) {
return false;
}
final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
final boolean canScrollVertically = mLayout.canScrollVertically();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(e);
final int action = e.getActionMasked();
final int actionIndex = e.getActionIndex();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (mIgnoreMotionEventTillDown) {
mIgnoreMotionEventTillDown = false;
}
mScrollPointerId = e.getPointerId(0);
mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
if (mScrollState == SCROLL_STATE_SETTLING) {
getParent().requestDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
}
// Clear the nested offsets
mNestedOffsets[0] = mNestedOffsets[1] = 0;
int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE;
if (canScrollHorizontally) {
nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL;
}
if (canScrollVertically) {
nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL;
}
startNestedScroll(nestedScrollAxis, TYPE_TOUCH);
break;
case MotionEvent.ACTION_POINTER_DOWN:
mScrollPointerId = e.getPointerId(actionIndex);
mInitialTouchX = mLastTouchX = (int) (e.getX(actionIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY(actionIndex) + 0.5f);
break;
case MotionEvent.ACTION_MOVE: {
final int index = e.findPointerIndex(mScrollPointerId);
if (index < 0) {
Log.e(TAG, "Error processing scroll; pointer index for id "
+ mScrollPointerId + " not found. Did any MotionEvents get skipped?");
return false;
}
final int x = (int) (e.getX(index) + 0.5f);
final int y = (int) (e.getY(index) + 0.5f);
if (mScrollState != SCROLL_STATE_DRAGGING) {
final int dx = x - mInitialTouchX;
final int dy = y - mInitialTouchY;
boolean startScroll = false;
if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
mLastTouchX = x;
startScroll = true;
}
if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
mLastTouchY = y;
startScroll = true;
}
if (startScroll) {
setScrollState(SCROLL_STATE_DRAGGING);
}
}
}
break;
case MotionEvent.ACTION_POINTER_UP: {
onPointerUp(e);
}
break;
case MotionEvent.ACTION_UP: {
mVelocityTracker.clear();
stopNestedScroll(TYPE_TOUCH);
}
break;
case MotionEvent.ACTION_CANCEL: {
cancelTouch();
}
}
return mScrollState == SCROLL_STATE_DRAGGING;
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
final int listenerCount = mOnItemTouchListeners.size();
for (int i = 0; i < listenerCount; i++) {
final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
listener.onRequestDisallowInterceptTouchEvent(disallowIntercept);
}
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (mLayoutFrozen || mIgnoreMotionEventTillDown) {
return false;
}
if (dispatchOnItemTouch(e)) {
cancelTouch();
return true;
}
if (mLayout == null) {
return false;
}
final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
final boolean canScrollVertically = mLayout.canScrollVertically();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
boolean eventAddedToVelocityTracker = false;
final MotionEvent vtev = MotionEvent.obtain(e);
final int action = e.getActionMasked();
final int actionIndex = e.getActionIndex();
if (action == MotionEvent.ACTION_DOWN) {
mNestedOffsets[0] = mNestedOffsets[1] = 0;
}
vtev.offsetLocation(mNestedOffsets[0], mNestedOffsets[1]);
switch (action) {
case MotionEvent.ACTION_DOWN: {
mScrollPointerId = e.getPointerId(0);
mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE;
if (canScrollHorizontally) {
nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL;
}
if (canScrollVertically) {
nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL;
}
startNestedScroll(nestedScrollAxis, TYPE_TOUCH);
}
break;
case MotionEvent.ACTION_POINTER_DOWN: {
mScrollPointerId = e.getPointerId(actionIndex);
mInitialTouchX = mLastTouchX = (int) (e.getX(actionIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY(actionIndex) + 0.5f);
}
break;
case MotionEvent.ACTION_MOVE: {
final int index = e.findPointerIndex(mScrollPointerId);
if (index < 0) {
Log.e(TAG, "Error processing scroll; pointer index for id "
+ mScrollPointerId + " not found. Did any MotionEvents get skipped?");
return false;
}
final int x = (int) (e.getX(index) + 0.5f);
final int y = (int) (e.getY(index) + 0.5f);
int dx = mLastTouchX - x;
int dy = mLastTouchY - y;
if (dispatchNestedPreScroll(dx, dy, mScrollConsumed, mScrollOffset, TYPE_TOUCH)) {
dx -= mScrollConsumed[0];
dy -= mScrollConsumed[1];
vtev.offsetLocation(mScrollOffset[0], mScrollOffset[1]);
// Updated the nested offsets
mNestedOffsets[0] += mScrollOffset[0];
mNestedOffsets[1] += mScrollOffset[1];
}
if (mScrollState != SCROLL_STATE_DRAGGING) {
boolean startScroll = false;
if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
if (dx > 0) {
dx -= mTouchSlop;
} else {
dx += mTouchSlop;
}
startScroll = true;
}
if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
if (dy > 0) {
dy -= mTouchSlop;
} else {
dy += mTouchSlop;
}
startScroll = true;
}
if (startScroll) {
setScrollState(SCROLL_STATE_DRAGGING);
}
}
if (mScrollState == SCROLL_STATE_DRAGGING) {
mLastTouchX = x - mScrollOffset[0];
mLastTouchY = y - mScrollOffset[1];
if (scrollByInternal(
canScrollHorizontally ? dx : 0,
canScrollVertically ? dy : 0,
vtev)) {
getParent().requestDisallowInterceptTouchEvent(true);
}
if (mGapWorker != null && (dx != 0 || dy != 0)) {
mGapWorker.postFromTraversal(this, dx, dy);
}
}
}
break;
case MotionEvent.ACTION_POINTER_UP: {
onPointerUp(e);
}
break;
case MotionEvent.ACTION_UP: {
mVelocityTracker.addMovement(vtev);
eventAddedToVelocityTracker = true;
mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity);
final float xvel = canScrollHorizontally
? -mVelocityTracker.getXVelocity(mScrollPointerId) : 0;
final float yvel = canScrollVertically
? -mVelocityTracker.getYVelocity(mScrollPointerId) : 0;
if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) {
setScrollState(SCROLL_STATE_IDLE);
}
resetTouch();
}
break;
case MotionEvent.ACTION_CANCEL: {
cancelTouch();
}
break;
}
if (!eventAddedToVelocityTracker) {
mVelocityTracker.addMovement(vtev);
}
vtev.recycle();
return true;
}
private void resetTouch() {
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
stopNestedScroll(TYPE_TOUCH);
releaseGlows();
}
private void cancelTouch() {
resetTouch();
setScrollState(SCROLL_STATE_IDLE);
}
private void onPointerUp(MotionEvent e) {
final int actionIndex = e.getActionIndex();
if (e.getPointerId(actionIndex) == mScrollPointerId) {
// Pick a new pointer to pick up the slack.
final int newIndex = actionIndex == 0 ? 1 : 0;
mScrollPointerId = e.getPointerId(newIndex);
mInitialTouchX = mLastTouchX = (int) (e.getX(newIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY(newIndex) + 0.5f);
}
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (mLayout == null) {
return false;
}
if (mLayoutFrozen) {
return false;
}
if (event.getAction() == MotionEventCompat.ACTION_SCROLL) {
final float vScroll, hScroll;
if ((event.getSource() & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) {
if (mLayout.canScrollVertically()) {
// Inverse the sign of the vertical scroll to align the scroll orientation
// with AbsListView.
vScroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
} else {
vScroll = 0f;
}
if (mLayout.canScrollHorizontally()) {
hScroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
} else {
hScroll = 0f;
}
} else if ((event.getSource() & InputDeviceCompat.SOURCE_ROTARY_ENCODER) != 0) {
final float axisScroll = event.getAxisValue(MotionEventCompat.AXIS_SCROLL);
if (mLayout.canScrollVertically()) {
// Invert the sign of the vertical scroll to align the scroll orientation
// with AbsListView.
vScroll = -axisScroll;
hScroll = 0f;
} else if (mLayout.canScrollHorizontally()) {
vScroll = 0f;
hScroll = axisScroll;
} else {
vScroll = 0f;
hScroll = 0f;
}
} else {
vScroll = 0f;
hScroll = 0f;
}
if (vScroll != 0 || hScroll != 0) {
scrollByInternal((int) (hScroll * mScaledHorizontalScrollFactor),
(int) (vScroll * mScaledVerticalScrollFactor), event);
}
}
return false;
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
if (mLayout == null) {
//layoutManager没有设置的话,直接走default的方法,所以会未空白
defaultOnMeasure(widthSpec, heightSpec);
return;
}
if (mLayout.mAutoMeasure) {
final int widthMode = MeasureSpec.getMode(widthSpec);
final int heightMode = MeasureSpec.getMode(heightSpec);
final boolean skipMeasure = widthMode == MeasureSpec.EXACTLY
&& heightMode == MeasureSpec.EXACTLY;
mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
//如果测量是绝对值,则跳过measure过程直接走layout
if (skipMeasure || mAdapter == null) {
return;
}
if (mState.mLayoutStep == State.STEP_START) {
//mLayoutStep默认值是 State.STEP_START
dispatchLayoutStep1();
//执行完dispatchLayoutStep1()后是State.STEP_LAYOUT
}
// set dimensions in 2nd step. Pre-layout should happen with old dimensions for
// consistency
mLayout.setMeasureSpecs(widthSpec, heightSpec);
mState.mIsMeasuring = true;
//真正执行LayoutManager绘制的地方
dispatchLayoutStep2();
//执行完后是State.STEP_ANIMATIONS
// now we can get the width and height from the children.
mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec);
//宽高都不确定的时候,会绘制两次!消耗性能
// if RecyclerView has non-exact width and height and if there is at least one child
// which also has non-exact width & height, we have to re-measure.
if (mLayout.shouldMeasureTwice()) {
mLayout.setMeasureSpecs(
MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
mState.mIsMeasuring = true;
dispatchLayoutStep2();
// now we can get the width and height from the children.
mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec);
}
} else {
if (mHasFixedSize) {
mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
return;
}
// custom onMeasure
//notify的时候会设为true
if (mAdapterUpdateDuringMeasure) {
eatRequestLayout();
onEnterLayoutOrScroll();
processAdapterUpdatesAndSetAnimationFlags();
onExitLayoutOrScroll();
if (mState.mRunPredictiveAnimations) {
mState.mInPreLayout = true;
} else {
// consume remaining updates to provide a consistent state with the layout pass.
mAdapterHelper.consumeUpdatesInOnePass();
mState.mInPreLayout = false;
}
mAdapterUpdateDuringMeasure = false;
resumeRequestLayout(false);
} else if (mState.mRunPredictiveAnimations) {
// If mAdapterUpdateDuringMeasure is false and mRunPredictiveAnimations is true:
// this means there is already an onMeasure() call performed to handle the pending
// adapter change, two onMeasure() calls can happen if RV is a child of LinearLayout
// with layout_width=MATCH_PARENT. RV cannot call LM.onMeasure() second time
// because getViewForPosition() will crash when LM uses a child to measure.
setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
return;
}
if (mAdapter != null) {
mState.mItemCount = mAdapter.getItemCount();
} else {
mState.mItemCount = 0;
}
eatRequestLayout();
mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
resumeRequestLayout(false);
mState.mInPreLayout = false; // clear
}
}
/**
* Used when onMeasure is called before layout manager is set
**/
void defaultOnMeasure(int widthSpec, int heightSpec) {
// calling LayoutManager here is not pretty but that API is already public and it is better
// than creating another method since this is internal.
final int width = LayoutManager.chooseSize(widthSpec,
getPaddingLeft() + getPaddingRight(),
ViewCompat.getMinimumWidth(this));
final int height = LayoutManager.chooseSize(heightSpec,
getPaddingTop() + getPaddingBottom(),
ViewCompat.getMinimumHeight(this));
setMeasuredDimension(width, height);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw || h != oldh) {
invalidateGlows();
// layout's w/h are updated during measure/layout steps.
}
}
/**
* Sets the {@link ItemAnimator} that will handle animations involving changes
* to the items in this RecyclerView. By default, RecyclerView instantiates and
* uses an instance of {@link DefaultItemAnimator}. Whether item animations are
* enabled for the RecyclerView depends on the ItemAnimator and whether
* the LayoutManager {@link LayoutManager#supportsPredictiveItemAnimations()
* supports item animations}.
*
* @param animator The ItemAnimator being set. If null, no animations will occur
* when changes occur to the items in this RecyclerView.
**/
public void setItemAnimator(ItemAnimator animator) {
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
mItemAnimator.setListener(null);
}
mItemAnimator = animator;
if (mItemAnimator != null) {
mItemAnimator.setListener(mItemAnimatorListener);
}
}
void onEnterLayoutOrScroll() {
mLayoutOrScrollCounter++;
}
void onExitLayoutOrScroll() {
onExitLayoutOrScroll(true);
}
void onExitLayoutOrScroll(boolean enableChangeEvents) {
mLayoutOrScrollCounter--;
if (mLayoutOrScrollCounter < 1) {
if (DEBUG && mLayoutOrScrollCounter < 0) {
throw new IllegalStateException("layout or scroll counter cannot go below zero."
+ "Some calls are not matching" + exceptionLabel());
}
mLayoutOrScrollCounter = 0;
if (enableChangeEvents) {
dispatchContentChangedIfNecessary();
dispatchPendingImportantForAccessibilityChanges();
}
}
}
boolean isAccessibilityEnabled() {
return mAccessibilityManager != null && mAccessibilityManager.isEnabled();
}
private void dispatchContentChangedIfNecessary() {
final int flags = mEatenAccessibilityChangeFlags;
mEatenAccessibilityChangeFlags = 0;
if (flags != 0 && isAccessibilityEnabled()) {
final AccessibilityEvent event = AccessibilityEvent.obtain();
event.setEventType(AccessibilityEventCompat.TYPE_WINDOW_CONTENT_CHANGED);
AccessibilityEventCompat.setContentChangeTypes(event, flags);
sendAccessibilityEventUnchecked(event);
}
}
/**
* Returns whether RecyclerView is currently computing a layout.
* <p>
* If this method returns true, it means that RecyclerView is in a lockdown state and any
* attempt to update adapter contents will result in an exception because adapter contents
* cannot be changed while RecyclerView is trying to compute the layout.
* <p>
* It is very unlikely that your code will be running during this state as it is
* called by the framework when a layout traversal happens or RecyclerView starts to scroll
* in response to system events (touch, accessibility etc).
* <p>
* This case may happen if you have some custom logic to change adapter contents in
* response to a View callback (e.g. focus change callback) which might be triggered during a
* layout calculation. In these cases, you should just postpone the change using a Handler or a
* similar mechanism.
*
* @return <code>true</code> if RecyclerView is currently computing a layout, <code>false</code>
* otherwise
**/
public boolean isComputingLayout() {
return mLayoutOrScrollCounter > 0;
}
/**
* Returns true if an accessibility event should not be dispatched now. This happens when an
* accessibility request arrives while RecyclerView does not have a stable state which is very
* hard to handle for a LayoutManager. Instead, this method records necessary information about
* the event and dispatches a window change event after the critical section is finished.
*
* @return True if the accessibility event should be postponed.
**/
boolean shouldDeferAccessibilityEvent(AccessibilityEvent event) {
if (isComputingLayout()) {
int type = 0;
if (event != null) {
type = AccessibilityEventCompat.getContentChangeTypes(event);
}
if (type == 0) {
type = AccessibilityEventCompat.CONTENT_CHANGE_TYPE_UNDEFINED;
}
mEatenAccessibilityChangeFlags |= type;
return true;
}
return false;
}
@Override
public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
if (shouldDeferAccessibilityEvent(event)) {
return;
}
super.sendAccessibilityEventUnchecked(event);
}
/**
* Gets the current ItemAnimator for this RecyclerView. A null return value
* indicates that there is no animator and that item changes will happen without
* any animations. By default, RecyclerView instantiates and
* uses an instance of {@link DefaultItemAnimator}.
*
* @return ItemAnimator The current ItemAnimator. If null, no animations will occur
* when changes occur to the items in this RecyclerView.
**/
public ItemAnimator getItemAnimator() {
return mItemAnimator;
}
/**
* Post a runnable to the next frame to run pending item animations. Only the first such
* request will be posted, governed by the mPostedAnimatorRunner flag.
**/
void postAnimationRunner() {
if (!mPostedAnimatorRunner && mIsAttached) {
ViewCompat.postOnAnimation(this, mItemAnimatorRunner);
mPostedAnimatorRunner = true;
}
}
private boolean predictiveItemAnimationsEnabled() {
return (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations());
}
/**
* Consumes adapter updates and calculates which type of animations we want to run.
* Called in onMeasure and dispatchLayout.
* <p>
* This method may process only the pre-layout state of updates or all of them.
**/
/**
* 在onMeasure和dispatchLayout1和dispatchLayout2中调用
*/
private void processAdapterUpdatesAndSetAnimationFlags() {
if (mDataSetHasChangedAfterLayout) {
// Processing these items have no value since data set changed unexpectedly.
// Instead, we just reset it.
mAdapterHelper.reset();
mLayout.onItemsChanged(this);
}
// simple animations are a subset of advanced animations (which will cause a
// pre-layout step)
// If layout supports predictive animations, pre-process to decide if we want to run them
//两个都会遍历
if (predictiveItemAnimationsEnabled()) {
mAdapterHelper.preProcess();
} else {
mAdapterHelper.consumeUpdatesInOnePass();
}
boolean animationTypeSupported = mItemsAddedOrRemoved || mItemsChanged;
mState.mRunSimpleAnimations = mFirstLayoutComplete
&& mItemAnimator != null
&& (mDataSetHasChangedAfterLayout
|| animationTypeSupported
|| mLayout.mRequestedSimpleAnimations)
&& (!mDataSetHasChangedAfterLayout
|| mAdapter.hasStableIds());
mState.mRunPredictiveAnimations = mState.mRunSimpleAnimations
&& animationTypeSupported
&& !mDataSetHasChangedAfterLayout
&& predictiveItemAnimationsEnabled();
}
/**
* Wrapper around layoutChildren() that handles animating changes caused by layout.
* Animations work on the assumption that there are five different kinds of items
* in play:
* PERSISTENT: items are visible before and after layout
* REMOVED: items were visible before layout and were removed by the app
* ADDED: items did not exist before layout and were added by the app
* DISAPPEARING: items exist in the data set before/after, but changed from
* visible to non-visible in the process of layout (they were moved off
* screen as a side-effect of other changes)
* APPEARING: items exist in the data set before/after, but changed from
* non-visible to visible in the process of layout (they were moved on
* screen as a side-effect of other changes)
* The overall approach figures out what items exist before/after layout and
* infers one of the five above states for each of the items. Then the animations
* are set up accordingly:
* PERSISTENT views are animated via
* {@link ItemAnimator#animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)}
* DISAPPEARING views are animated via
* {@link ItemAnimator#animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)}
* APPEARING views are animated via
* {@link ItemAnimator#animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)}
* and changed views are animated via
* {@link ItemAnimator#animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)}.
**/
void dispatchLayout() {
if (mAdapter == null) {
Log.e(TAG, "No adapter attached; skipping layout");
// leave the state in START
return;
}
if (mLayout == null) {
Log.e(TAG, "No layout manager attached; skipping layout");
// leave the state in START
return;
}
mState.mIsMeasuring = false;
if (mState.mLayoutStep == State.STEP_START) {
dispatchLayoutStep1();
mLayout.setExactMeasureSpecsFrom(this);
dispatchLayoutStep2();
} else if (mAdapterHelper.hasUpdates() || mLayout.getWidth() != getWidth()
|| mLayout.getHeight() != getHeight()) {
// First 2 steps are done in onMeasure but looks like we have to run again due to
// changed size.
mLayout.setExactMeasureSpecsFrom(this);
dispatchLayoutStep2();
} else {
// always make sure we sync them (to ensure mode is exact)
mLayout.setExactMeasureSpecsFrom(this);
}
dispatchLayoutStep3();
}
private void saveFocusInfo() {
View child = null;
if (mPreserveFocusAfterLayout && hasFocus() && mAdapter != null) {
child = getFocusedChild();
}
final ViewHolder focusedVh = child == null ? null : findContainingViewHolder(child);
if (focusedVh == null) {
resetFocusInfo();
} else {
mState.mFocusedItemId = mAdapter.hasStableIds() ? focusedVh.getItemId() : NO_ID;
// mFocusedItemPosition should hold the current adapter position of the previously
// focused item. If the item is removed, we store the previous adapter position of the
// removed item.
mState.mFocusedItemPosition = mDataSetHasChangedAfterLayout ? NO_POSITION
: (focusedVh.isRemoved() ? focusedVh.mOldPosition
: focusedVh.getAdapterPosition());
mState.mFocusedSubChildId = getDeepestFocusedViewWithId(focusedVh.itemView);
}
}
private void resetFocusInfo() {
mState.mFocusedItemId = NO_ID;
mState.mFocusedItemPosition = NO_POSITION;
mState.mFocusedSubChildId = View.NO_ID;
}
/**
* Finds the best view candidate to request focus on using mFocusedItemPosition index of the
* previously focused item. It first traverses the adapter forward to find a focusable candidate
* and if no such candidate is found, it reverses the focus search direction for the items
* before the mFocusedItemPosition'th index;
* @return The best candidate to request focus on, or null if no such candidate exists. Null
* indicates all the existing adapter items are unfocusable.
**/
@Nullable
private View findNextViewToFocus() {
int startFocusSearchIndex = mState.mFocusedItemPosition != -1 ? mState.mFocusedItemPosition
: 0;
ViewHolder nextFocus;
final int itemCount = mState.getItemCount();
for (int i = startFocusSearchIndex; i < itemCount; i++) {
nextFocus = findViewHolderForAdapterPosition(i);
if (nextFocus == null) {
break;
}
if (nextFocus.itemView.hasFocusable()) {
return nextFocus.itemView;
}
}
final int limit = Math.min(itemCount, startFocusSearchIndex);
for (int i = limit - 1; i >= 0; i--) {
nextFocus = findViewHolderForAdapterPosition(i);
if (nextFocus == null) {
return null;
}
if (nextFocus.itemView.hasFocusable()) {
return nextFocus.itemView;
}
}
return null;
}
private void recoverFocusFromState() {
if (!mPreserveFocusAfterLayout || mAdapter == null || !hasFocus()
|| getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS
|| (getDescendantFocusability() == FOCUS_BEFORE_DESCENDANTS && isFocused())) {
// No-op if either of these cases happens:
// 1. RV has no focus, or 2. RV blocks focus to its children, or 3. RV takes focus
// before its children and is focused (i.e. it already stole the focus away from its
// descendants).
return;
}
// only recover focus if RV itself has the focus or the focused view is hidden
if (!isFocused()) {
final View focusedChild = getFocusedChild();
if (IGNORE_DETACHED_FOCUSED_CHILD
&& (focusedChild.getParent() == null || !focusedChild.hasFocus())) {
// Special handling of API 15-. A focused child can be invalid because mFocus is not
// cleared when the child is detached (mParent = null),
// This happens because clearFocus on API 15- does not invalidate mFocus of its
// parent when this child is detached.
// For API 16+, this is not an issue because requestFocus takes care of clearing the
// prior detached focused child. For API 15- the problem happens in 2 cases because
// clearChild does not call clearChildFocus on RV: 1. setFocusable(false) is called
// for the current focused item which calls clearChild or 2. when the prior focused
// child is removed, removeDetachedView called in layout step 3 which calls
// clearChild. We should ignore this invalid focused child in all our calculations
// for the next view to receive focus, and apply the focus recovery logic instead.
if (mChildHelper.getChildCount() == 0) {
// No children left. Request focus on the RV itself since one of its children
// was holding focus previously.
requestFocus();
return;
}
} else if (!mChildHelper.isHidden(focusedChild)) {
// If the currently focused child is hidden, apply the focus recovery logic.
// Otherwise return, i.e. the currently (unhidden) focused child is good enough :/.
return;
}
}
ViewHolder focusTarget = null;
// RV first attempts to locate the previously focused item to request focus on using
// mFocusedItemId. If such an item no longer exists, it then makes a best-effort attempt to
// find the next best candidate to request focus on based on mFocusedItemPosition.
if (mState.mFocusedItemId != NO_ID && mAdapter.hasStableIds()) {
focusTarget = findViewHolderForItemId(mState.mFocusedItemId);
}
View viewToFocus = null;
if (focusTarget == null || mChildHelper.isHidden(focusTarget.itemView)
|| !focusTarget.itemView.hasFocusable()) {
if (mChildHelper.getChildCount() > 0) {
// At this point, RV has focus and either of these conditions are true:
// 1. There's no previously focused item either because RV received focused before
// layout, or the previously focused item was removed, or RV doesn't have stable IDs
// 2. Previous focus child is hidden, or 3. Previous focused child is no longer
// focusable. In either of these cases, we make sure that RV still passes down the
// focus to one of its focusable children using a best-effort algorithm.
viewToFocus = findNextViewToFocus();
}
} else {
// looks like the focused item has been replaced with another view that represents the
// same item in the adapter. Request focus on that.
viewToFocus = focusTarget.itemView;
}
if (viewToFocus != null) {
if (mState.mFocusedSubChildId != NO_ID) {
View child = viewToFocus.findViewById(mState.mFocusedSubChildId);
if (child != null && child.isFocusable()) {
viewToFocus = child;
}
}
viewToFocus.requestFocus();
}
}
private int getDeepestFocusedViewWithId(View view) {
int lastKnownId = view.getId();
while (!view.isFocused() && view instanceof ViewGroup && view.hasFocus()) {
view = ((ViewGroup) view).getFocusedChild();
final int id = view.getId();
if (id != View.NO_ID) {
lastKnownId = view.getId();
}
}
return lastKnownId;
}
final void fillRemainingScrollValues(State state) {
if (getScrollState() == SCROLL_STATE_SETTLING) {
final OverScroller scroller = mViewFlinger.mScroller;
state.mRemainingScrollHorizontal = scroller.getFinalX() - scroller.getCurrX();
state.mRemainingScrollVertical = scroller.getFinalY() - scroller.getCurrY();
} else {
state.mRemainingScrollHorizontal = 0;
state.mRemainingScrollVertical = 0;
}
}
/**
* The first step of a layout where we;
* - process adapter updates
* - decide which animation should run
* - save information about current views
* - If necessary, run predictive layout and save its information
**/
/**
* 1.处理Adapter的更新
* 2.决定那些动画需要执行
* 3.保存当前View的信息
* 4.如果必要的话,执行上一个Layout的操作并且保存他的信息
**/
private void dispatchLayoutStep1() {
mState.assertLayoutStep(State.STEP_START);
fillRemainingScrollValues(mState);
mState.mIsMeasuring = false;
eatRequestLayout();
mViewInfoStore.clear();
onEnterLayoutOrScroll();
processAdapterUpdatesAndSetAnimationFlags();
saveFocusInfo();
mState.mTrackOldChangeHolders = mState.mRunSimpleAnimations && mItemsChanged;
mItemsAddedOrRemoved = mItemsChanged = false;
mState.mInPreLayout = mState.mRunPredictiveAnimations;
mState.mItemCount = mAdapter.getItemCount();
findMinMaxChildLayoutPositions(mMinMaxLayoutPositions);
if (mState.mRunSimpleAnimations) {
// Step 0: Find out where all non-removed items are, pre-layout
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore() || (holder.isInvalid() && !mAdapter.hasStableIds())) {
continue;
}
final ItemHolderInfo animationInfo = mItemAnimator
.recordPreLayoutInformation(mState, holder,
ItemAnimator.buildAdapterChangeFlagsForAnimations(holder),
holder.getUnmodifiedPayloads());
mViewInfoStore.addToPreLayout(holder, animationInfo);
if (mState.mTrackOldChangeHolders && holder.isUpdated() && !holder.isRemoved()
&& !holder.shouldIgnore() && !holder.isInvalid()) {
long key = getChangedHolderKey(holder);
// This is NOT the only place where a ViewHolder is added to old change holders
// list. There is another case where:
// * A VH is currently hidden but not deleted
// * The hidden item is changed in the adapter
// * Layout manager decides to layout the item in the pre-Layout pass (step1)
// When this case is detected, RV will un-hide that view and add to the old
// change holders list.
mViewInfoStore.addToOldChangeHolders(key, holder);
}
}
}
if (mState.mRunPredictiveAnimations) {
// Step 1: run prelayout: This will use the old positions of items. The layout manager
// is expected to layout everything, even removed items (though not to add removed
// items back to the container). This gives the pre-layout position of APPEARING views
// which come into existence as part of the real layout.
// Save old positions so that LayoutManager can run its mapping logic.
saveOldPositions();
final boolean didStructureChange = mState.mStructureChanged;
mState.mStructureChanged = false;
// temporarily disable flag because we are asking for previous layout
mLayout.onLayoutChildren(mRecycler, mState);
mState.mStructureChanged = didStructureChange;
for (int i = 0; i < mChildHelper.getChildCount(); ++i) {
final View child = mChildHelper.getChildAt(i);
final ViewHolder viewHolder = getChildViewHolderInt(child);
if (viewHolder.shouldIgnore()) {
continue;
}
if (!mViewInfoStore.isInPreLayout(viewHolder)) {
int flags = ItemAnimator.buildAdapterChangeFlagsForAnimations(viewHolder);
boolean wasHidden = viewHolder
.hasAnyOfTheFlags(ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);
if (!wasHidden) {
flags |= ItemAnimator.FLAG_APPEARED_IN_PRE_LAYOUT;
}
final ItemHolderInfo animationInfo = mItemAnimator.recordPreLayoutInformation(
mState, viewHolder, flags, viewHolder.getUnmodifiedPayloads());
if (wasHidden) {
recordAnimationInfoIfBouncedHiddenView(viewHolder, animationInfo);
} else {
mViewInfoStore.addToAppearedInPreLayoutHolders(viewHolder, animationInfo);
}
}
}
// we don't process disappearing list because they may re-appear in post layout pass.
clearOldPositions();
} else {
clearOldPositions();
}
onExitLayoutOrScroll();
resumeRequestLayout(false);
mState.mLayoutStep = State.STEP_LAYOUT;
}
/**
* The second layout step where we do the actual layout of the views for the final state.
* This step might be run multiple times if necessary (e.g. measure).
**/
private void dispatchLayoutStep2() {
eatRequestLayout();
onEnterLayoutOrScroll();
mState.assertLayoutStep(State.STEP_LAYOUT | State.STEP_ANIMATIONS);
mAdapterHelper.consumeUpdatesInOnePass();
//重写的getItemCount方法
mState.mItemCount = mAdapter.getItemCount();
mState.mDeletedInvisibleItemCountSincePreviousLayout = 0;
// Step 2: Run layout
mState.mInPreLayout = false;
mLayout.onLayoutChildren(mRecycler, mState);
mState.mStructureChanged = false;
mPendingSavedState = null;
// onLayoutChildren may have caused client code to disable item animations; re-check
mState.mRunSimpleAnimations = mState.mRunSimpleAnimations && mItemAnimator != null;
mState.mLayoutStep = State.STEP_ANIMATIONS;
onExitLayoutOrScroll();
resumeRequestLayout(false);
}
/**
* The final step of the layout where we save the information about views for animations,
* trigger animations and do any necessary cleanup.
**/
/**
* 重置一些参数
**/
private void dispatchLayoutStep3() {
mState.assertLayoutStep(State.STEP_ANIMATIONS);
eatRequestLayout();
onEnterLayoutOrScroll();
//又变为了State.STEP_START
mState.mLayoutStep = State.STEP_START;
if (mState.mRunSimpleAnimations) {
// Step 3: Find out where things are now, and process change animations.
// traverse list in reverse because we may call animateChange in the loop which may
// remove the target view holder.
for (int i = mChildHelper.getChildCount() - 1; i >= 0; i--) {
ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore()) {
continue;
}
long key = getChangedHolderKey(holder);
final ItemHolderInfo animationInfo = mItemAnimator
.recordPostLayoutInformation(mState, holder);
ViewHolder oldChangeViewHolder = mViewInfoStore.getFromOldChangeHolders(key);
if (oldChangeViewHolder != null && !oldChangeViewHolder.shouldIgnore()) {
// run a change animation
// If an Item is CHANGED but the updated version is disappearing, it creates
// a conflicting case.
// Since a view that is marked as disappearing is likely to be going out of
// bounds, we run a change animation. Both views will be cleaned automatically
// once their animations finish.
// On the other hand, if it is the same view holder instance, we run a
// disappearing animation instead because we are not going to rebind the updated
// VH unless it is enforced by the layout manager.
final boolean oldDisappearing = mViewInfoStore.isDisappearing(
oldChangeViewHolder);
final boolean newDisappearing = mViewInfoStore.isDisappearing(holder);
if (oldDisappearing && oldChangeViewHolder == holder) {
// run disappear animation instead of change
mViewInfoStore.addToPostLayout(holder, animationInfo);
} else {
final ItemHolderInfo preInfo = mViewInfoStore.popFromPreLayout(
oldChangeViewHolder);
// we add and remove so that any post info is merged.
mViewInfoStore.addToPostLayout(holder, animationInfo);
ItemHolderInfo postInfo = mViewInfoStore.popFromPostLayout(holder);
if (preInfo == null) {
handleMissingPreInfoForChangeError(key, holder, oldChangeViewHolder);
} else {
animateChange(oldChangeViewHolder, holder, preInfo, postInfo,
oldDisappearing, newDisappearing);
}
}
} else {
mViewInfoStore.addToPostLayout(holder, animationInfo);
}
}
// Step 4: Process view info lists and trigger animations
mViewInfoStore.process(mViewInfoProcessCallback);
}
mLayout.removeAndRecycleScrapInt(mRecycler);
mState.mPreviousLayoutItemCount = mState.mItemCount;
mDataSetHasChangedAfterLayout = false;
mState.mRunSimpleAnimations = false;
mState.mRunPredictiveAnimations = false;
mLayout.mRequestedSimpleAnimations = false;
if (mRecycler.mChangedScrap != null) {
mRecycler.mChangedScrap.clear();
}
if (mLayout.mPrefetchMaxObservedInInitialPrefetch) {
// Initial prefetch has expanded cache, so reset until next prefetch.
// This prevents initial prefetches from expanding the cache permanently.
mLayout.mPrefetchMaxCountObserved = 0;
mLayout.mPrefetchMaxObservedInInitialPrefetch = false;
mRecycler.updateViewCacheSize();
}
mLayout.onLayoutCompleted(mState);
onExitLayoutOrScroll();
resumeRequestLayout(false);
mViewInfoStore.clear();
if (didChildRangeChange(mMinMaxLayoutPositions[0], mMinMaxLayoutPositions[1])) {
dispatchOnScrolled(0, 0);
}
recoverFocusFromState();
resetFocusInfo();
}
/**
* This handles the case where there is an unexpected VH missing in the pre-layout map.
* <p>
* We might be able to detect the error in the application which will help the developer to
* resolve the issue.
* <p>
* If it is not an expected error, we at least print an error to notify the developer and ignore
* the animation.
*
* https://code.google.com/p/android/issues/detail?id=193958
*
* @param key The change key
* @param holder Current ViewHolder
* @param oldChangeViewHolder Changed ViewHolder
**/
private void handleMissingPreInfoForChangeError(long key,
ViewHolder holder, ViewHolder oldChangeViewHolder) {
// check if two VH have the same key, if so, print that as an error
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = mChildHelper.getChildAt(i);
ViewHolder other = getChildViewHolderInt(view);
if (other == holder) {
continue;
}
final long otherKey = getChangedHolderKey(other);
if (otherKey == key) {
if (mAdapter != null && mAdapter.hasStableIds()) {
throw new IllegalStateException("Two different ViewHolders have the same stable"
+ " ID. Stable IDs in your adapter MUST BE unique and SHOULD NOT"
+ " change.\n ViewHolder 1:" + other + " \n View Holder 2:" + holder
+ exceptionLabel());
} else {
throw new IllegalStateException("Two different ViewHolders have the same change"
+ " ID. This might happen due to inconsistent Adapter update events or"
+ " if the LayoutManager lays out the same View multiple times."
+ "\n ViewHolder 1:" + other + " \n View Holder 2:" + holder
+ exceptionLabel());
}
}
}
// Very unlikely to happen but if it does, notify the developer.
Log.e(TAG, "Problem while matching changed view holders with the new"
+ "ones. The pre-layout information for the change holder " + oldChangeViewHolder
+ " cannot be found but it is necessary for " + holder + exceptionLabel());
}
/**
* Records the animation information for a view holder that was bounced from hidden list. It
* also clears the bounce back flag.
**/
void recordAnimationInfoIfBouncedHiddenView(ViewHolder viewHolder,
ItemHolderInfo animationInfo) {
// looks like this view bounced back from hidden list!
viewHolder.setFlags(0, ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);
if (mState.mTrackOldChangeHolders && viewHolder.isUpdated()
&& !viewHolder.isRemoved() && !viewHolder.shouldIgnore()) {
long key = getChangedHolderKey(viewHolder);
mViewInfoStore.addToOldChangeHolders(key, viewHolder);
}
mViewInfoStore.addToPreLayout(viewHolder, animationInfo);
}
private void findMinMaxChildLayoutPositions(int[] into) {
final int count = mChildHelper.getChildCount();
if (count == 0) {
into[0] = NO_POSITION;
into[1] = NO_POSITION;
return;
}
int minPositionPreLayout = Integer.MAX_VALUE;
int maxPositionPreLayout = Integer.MIN_VALUE;
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore()) {
continue;
}
final int pos = holder.getLayoutPosition();
if (pos < minPositionPreLayout) {
minPositionPreLayout = pos;
}
if (pos > maxPositionPreLayout) {
maxPositionPreLayout = pos;
}
}
into[0] = minPositionPreLayout;
into[1] = maxPositionPreLayout;
}
private boolean didChildRangeChange(int minPositionPreLayout, int maxPositionPreLayout) {
findMinMaxChildLayoutPositions(mMinMaxLayoutPositions);
return mMinMaxLayoutPositions[0] != minPositionPreLayout
|| mMinMaxLayoutPositions[1] != maxPositionPreLayout;
}
@Override
protected void removeDetachedView(View child, boolean animate) {
ViewHolder vh = getChildViewHolderInt(child);
if (vh != null) {
if (vh.isTmpDetached()) {
vh.clearTmpDetachFlag();
} else if (!vh.shouldIgnore()) {
throw new IllegalArgumentException("Called removeDetachedView with a view which"
+ " is not flagged as tmp detached." + vh + exceptionLabel());
}
}
// Clear any android.view.animation.Animation that may prevent the item from
// detaching when being removed. If a child is re-added before the
// lazy detach occurs, it will receive invalid attach/detach sequencing.
child.clearAnimation();
dispatchChildDetached(child);
super.removeDetachedView(child, animate);
}
/**
* Returns a unique key to be used while handling change animations.
* It might be child's position or stable id depending on the adapter type.
**/
long getChangedHolderKey(ViewHolder holder) {
return mAdapter.hasStableIds() ? holder.getItemId() : holder.mPosition;
}
void animateAppearance(@NonNull ViewHolder itemHolder,
@Nullable ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo) {
itemHolder.setIsRecyclable(false);
if (mItemAnimator.animateAppearance(itemHolder, preLayoutInfo, postLayoutInfo)) {
postAnimationRunner();
}
}
void animateDisappearance(@NonNull ViewHolder holder,
@NonNull ItemHolderInfo preLayoutInfo, @Nullable ItemHolderInfo postLayoutInfo) {
addAnimatingView(holder);
holder.setIsRecyclable(false);
if (mItemAnimator.animateDisappearance(holder, preLayoutInfo, postLayoutInfo)) {
postAnimationRunner();
}
}
private void animateChange(@NonNull ViewHolder oldHolder, @NonNull ViewHolder newHolder,
@NonNull ItemHolderInfo preInfo, @NonNull ItemHolderInfo postInfo,
boolean oldHolderDisappearing, boolean newHolderDisappearing) {
oldHolder.setIsRecyclable(false);
if (oldHolderDisappearing) {
addAnimatingView(oldHolder);
}
if (oldHolder != newHolder) {
if (newHolderDisappearing) {
addAnimatingView(newHolder);
}
oldHolder.mShadowedHolder = newHolder;
// old holder should disappear after animation ends
addAnimatingView(oldHolder);
mRecycler.unscrapView(oldHolder);
newHolder.setIsRecyclable(false);
newHolder.mShadowingHolder = oldHolder;
}
if (mItemAnimator.animateChange(oldHolder, newHolder, preInfo, postInfo)) {
postAnimationRunner();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
TraceCompat.beginSection(TRACE_ON_LAYOUT_TAG);
dispatchLayout();
TraceCompat.endSection();
mFirstLayoutComplete = true;
}
@Override
public void requestLayout() {
if (mEatRequestLayout == 0 && !mLayoutFrozen) {
super.requestLayout();
} else {
mLayoutRequestEaten = true;
}
}
void markItemDecorInsetsDirty() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final View child = mChildHelper.getUnfilteredChildAt(i);
((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
}
mRecycler.markItemDecorInsetsDirty();
}
@Override
public void draw(Canvas c) {
super.draw(c);
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDrawOver(c, this, mState);
}
// TODO If padding is not 0 and clipChildrenToPadding is false, to draw glows properly, we
// need find children closest to edges. Not sure if it is worth the effort.
boolean needsInvalidate = false;
if (mLeftGlow != null && !mLeftGlow.isFinished()) {
final int restore = c.save();
final int padding = mClipToPadding ? getPaddingBottom() : 0;
c.rotate(270);
c.translate(-getHeight() + padding, 0);
needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
c.restoreToCount(restore);
}
if (mTopGlow != null && !mTopGlow.isFinished()) {
final int restore = c.save();
if (mClipToPadding) {
c.translate(getPaddingLeft(), getPaddingTop());
}
needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
c.restoreToCount(restore);
}
if (mRightGlow != null && !mRightGlow.isFinished()) {
final int restore = c.save();
final int width = getWidth();
final int padding = mClipToPadding ? getPaddingTop() : 0;
c.rotate(90);
c.translate(-padding, -width);
needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
c.restoreToCount(restore);
}
if (mBottomGlow != null && !mBottomGlow.isFinished()) {
final int restore = c.save();
c.rotate(180);
if (mClipToPadding) {
c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom());
} else {
c.translate(-getWidth(), -getHeight());
}
needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
c.restoreToCount(restore);
}
// If some views are animating, ItemDecorators are likely to move/change with them.
// Invalidate RecyclerView to re-draw decorators. This is still efficient because children's
// display lists are not invalidated.
if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0
&& mItemAnimator.isRunning()) {
needsInvalidate = true;
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDraw(c, this, mState);
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && mLayout.checkLayoutParams((LayoutParams) p);
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager" + exceptionLabel());
}
return mLayout.generateDefaultLayoutParams();
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager" + exceptionLabel());
}
return mLayout.generateLayoutParams(getContext(), attrs);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager" + exceptionLabel());
}
return mLayout.generateLayoutParams(p);
}
/**
* Returns true if RecyclerView is currently running some animations.
* <p>
* If you want to be notified when animations are finished, use
* {@link ItemAnimator#isRunning(ItemAnimator.ItemAnimatorFinishedListener)}.
*
* @return True if there are some item animations currently running or waiting to be started.
**/
public boolean isAnimating() {
return mItemAnimator != null && mItemAnimator.isRunning();
}
void saveOldPositions() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (DEBUG && holder.mPosition == -1 && !holder.isRemoved()) {
throw new IllegalStateException("view holder cannot have position -1 unless it"
+ " is removed" + exceptionLabel());
}
if (!holder.shouldIgnore()) {
holder.saveOldPosition();
}
}
}
void clearOldPositions() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (!holder.shouldIgnore()) {
holder.clearOldPosition();
}
}
mRecycler.clearOldPositions();
}
void offsetPositionRecordsForMove(int from, int to) {
final int childCount = mChildHelper.getUnfilteredChildCount();
final int start, end, inBetweenOffset;
if (from < to) {
start = from;
end = to;
inBetweenOffset = -1;
} else {
start = to;
end = from;
inBetweenOffset = 1;
}
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder == null || holder.mPosition < start || holder.mPosition > end) {
continue;
}
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForMove attached child " + i + " holder "
+ holder);
}
if (holder.mPosition == from) {
holder.offsetPosition(to - from, false);
} else {
holder.offsetPosition(inBetweenOffset, false);
}
mState.mStructureChanged = true;
}
mRecycler.offsetPositionRecordsForMove(from, to);
requestLayout();
}
void offsetPositionRecordsForInsert(int positionStart, int itemCount) {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore() && holder.mPosition >= positionStart) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForInsert attached child " + i + " holder "
+ holder + " now at position " + (holder.mPosition + itemCount));
}
holder.offsetPosition(itemCount, false);
mState.mStructureChanged = true;
}
}
mRecycler.offsetPositionRecordsForInsert(positionStart, itemCount);
requestLayout();
}
void offsetPositionRecordsForRemove(int positionStart, int itemCount,
boolean applyToPreLayout) {
final int positionEnd = positionStart + itemCount;
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore()) {
//如果View大于影响的范围,则只是更改view的上下位置
if (holder.mPosition >= positionEnd) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i
+ " holder " + holder + " now at position "
+ (holder.mPosition - itemCount));
}
holder.offsetPosition(-itemCount, applyToPreLayout);
mState.mStructureChanged = true;
} else if (holder.mPosition >= positionStart) {
//如果是影响的范围,则设置Flag为Remove
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i
+ " holder " + holder + " now REMOVED");
}
holder.flagRemovedAndOffsetPosition(positionStart - 1, -itemCount,
applyToPreLayout);
mState.mStructureChanged = true;
}
}
}
mRecycler.offsetPositionRecordsForRemove(positionStart, itemCount, applyToPreLayout);
requestLayout();
}
/**
* Rebind existing views for the given range, or create as needed.
*
* @param positionStart Adapter position to start at
* @param itemCount Number of views that must explicitly be rebound
**/
void viewRangeUpdate(int positionStart, int itemCount, Object payload) {
final int childCount = mChildHelper.getUnfilteredChildCount();
final int positionEnd = positionStart + itemCount;
for (int i = 0; i < childCount; i++) {
final View child = mChildHelper.getUnfilteredChildAt(i);
final ViewHolder holder = getChildViewHolderInt(child);
if (holder == null || holder.shouldIgnore()) {
continue;
}
if (holder.mPosition >= positionStart && holder.mPosition < positionEnd) {
// We re-bind these view holders after pre-processing is complete so that
// ViewHolders have their final positions assigned.
holder.addFlags(ViewHolder.FLAG_UPDATE);
holder.addChangePayload(payload);
// lp cannot be null since we get ViewHolder from it.
((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
}
}
mRecycler.viewRangeUpdate(positionStart, itemCount);
}
boolean canReuseUpdatedViewHolder(ViewHolder viewHolder) {
return mItemAnimator == null || mItemAnimator.canReuseUpdatedViewHolder(viewHolder,
viewHolder.getUnmodifiedPayloads());
}
/**
* Call this method to signal that *all* adapter content has changed (generally, because of
* setAdapter, swapAdapter, or notifyDataSetChanged), and that once layout occurs, all
* attached items should be discarded or animated.
*
* Attached items are labeled as invalid, and all cached items are discarded.
*
* It is still possible for items to be prefetched while mDataSetHasChangedAfterLayout == true,
* so this method must always discard all cached views so that the only valid items that remain
* in the cache, once layout occurs, are valid prefetched items.
**/
/**
* 设置adapter中所有的内容都变化了
*/
void setDataSetChangedAfterLayout() {
mDataSetHasChangedAfterLayout = true;
markKnownViewsInvalid();
}
/**
* Mark all known views as invalid. Used in response to a, "the whole world might have changed"
* data change event.
**/
void markKnownViewsInvalid() {
//设置所有的ViewHolder Flag变成ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore()) {
holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
}
}
markItemDecorInsetsDirty();
mRecycler.markKnownViewsInvalid();
}
/**
* Invalidates all ItemDecorations. If RecyclerView has item decorations, calling this method
* will trigger a {@link #requestLayout()} call.
**/
public void invalidateItemDecorations() {
if (mItemDecorations.size() == 0) {
return;
}
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot invalidate item decorations during a scroll"
+ " or layout");
}
markItemDecorInsetsDirty();
requestLayout();
}
/**
* Returns true if the RecyclerView should attempt to preserve currently focused Adapter Item's
* focus even if the View representing the Item is replaced during a layout calculation.
* <p>
* By default, this value is {@code true}.
*
* @return True if the RecyclerView will try to preserve focused Item after a layout if it loses
* focus.
*
* @see #setPreserveFocusAfterLayout(boolean)
**/
public boolean getPreserveFocusAfterLayout() {
return mPreserveFocusAfterLayout;
}
/**
* Set whether the RecyclerView should try to keep the same Item focused after a layout
* calculation or not.
* <p>
* Usually, LayoutManagers keep focused views visible before and after layout but sometimes,
* views may lose focus during a layout calculation as their state changes or they are replaced
* with another view due to type change or animation. In these cases, RecyclerView can request
* focus on the new view automatically.
*
* @param preserveFocusAfterLayout Whether RecyclerView should preserve focused Item during a
* layout calculations. Defaults to true.
*
* @see #getPreserveFocusAfterLayout()
**/
public void setPreserveFocusAfterLayout(boolean preserveFocusAfterLayout) {
mPreserveFocusAfterLayout = preserveFocusAfterLayout;
}
/**
* Retrieve the {@link ViewHolder} for the given child view.
*
* @param child Child of this RecyclerView to query for its ViewHolder
* @return The child view's ViewHolder
**/
public ViewHolder getChildViewHolder(View child) {
final ViewParent parent = child.getParent();
if (parent != null && parent != this) {
throw new IllegalArgumentException("View " + child + " is not a direct child of "
+ this);
}
return getChildViewHolderInt(child);
}
/**
* Traverses the ancestors of the given view and returns the item view that contains it and
* also a direct child of the RecyclerView. This returned view can be used to get the
* ViewHolder by calling {@link #getChildViewHolder(View)}.
*
* @param view The view that is a descendant of the RecyclerView.
*
* @return The direct child of the RecyclerView which contains the given view or null if the
* provided view is not a descendant of this RecyclerView.
*
* @see #getChildViewHolder(View)
* @see #findContainingViewHolder(View)
**/
@Nullable
public View findContainingItemView(View view) {
ViewParent parent = view.getParent();
while (parent != null && parent != this && parent instanceof View) {
view = (View) parent;
parent = view.getParent();
}
return parent == this ? view : null;
}
/**
* Returns the ViewHolder that contains the given view.
*
* @param view The view that is a descendant of the RecyclerView.
*
* @return The ViewHolder that contains the given view or null if the provided view is not a
* descendant of this RecyclerView.
**/
@Nullable
public ViewHolder findContainingViewHolder(View view) {
View itemView = findContainingItemView(view);
return itemView == null ? null : getChildViewHolder(itemView);
}
static ViewHolder getChildViewHolderInt(View child) {
if (child == null) {
return null;
}
return ((LayoutParams) child.getLayoutParams()).mViewHolder;
}
/**
* @deprecated use {@link #getChildAdapterPosition(View)} or
* {@link #getChildLayoutPosition(View)}.
**/
@Deprecated
public int getChildPosition(View child) {
return getChildAdapterPosition(child);
}
/**
* Return the adapter position that the given child view corresponds to.
*
* @param child Child View to query
* @return Adapter position corresponding to the given view or {@link #NO_POSITION}
**/
public int getChildAdapterPosition(View child) {
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getAdapterPosition() : NO_POSITION;
}
/**
* Return the adapter position of the given child view as of the latest completed layout pass.
* <p>
* This position may not be equal to Item's adapter position if there are pending changes
* in the adapter which have not been reflected to the layout yet.
*
* @param child Child View to query
* @return Adapter position of the given View as of last layout pass or {@link #NO_POSITION} if
* the View is representing a removed item.
**/
public int getChildLayoutPosition(View child) {
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getLayoutPosition() : NO_POSITION;
}
/**
* Return the stable item id that the given child view corresponds to.
*
* @param child Child View to query
* @return Item id corresponding to the given view or {@link #NO_ID}
**/
public long getChildItemId(View child) {
if (mAdapter == null || !mAdapter.hasStableIds()) {
return NO_ID;
}
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getItemId() : NO_ID;
}
/**
* @deprecated use {@link #findViewHolderForLayoutPosition(int)} or
* {@link #findViewHolderForAdapterPosition(int)}
**/
@Deprecated
public ViewHolder findViewHolderForPosition(int position) {
return findViewHolderForPosition(position, false);
}
/**
* Return the ViewHolder for the item in the given position of the data set as of the latest
* layout pass.
* <p>
* This method checks only the children of RecyclerView. If the item at the given
* <code>position</code> is not laid out, it <em>will not</em> create a new one.
* <p>
* Note that when Adapter contents change, ViewHolder positions are not updated until the
* next layout calculation. If there are pending adapter updates, the return value of this
* method may not match your adapter contents. You can use
* #{@link ViewHolder#getAdapterPosition()} to get the current adapter position of a ViewHolder.
* <p>
* When the ItemAnimator is running a change animation, there might be 2 ViewHolders
* with the same layout position representing the same Item. In this case, the updated
* ViewHolder will be returned.
*
* @param position The position of the item in the data set of the adapter
* @return The ViewHolder at <code>position</code> or null if there is no such item
**/
public ViewHolder findViewHolderForLayoutPosition(int position) {
return findViewHolderForPosition(position, false);
}
/**
* Return the ViewHolder for the item in the given position of the data set. Unlike
* {@link #findViewHolderForLayoutPosition(int)} this method takes into account any pending
* adapter changes that may not be reflected to the layout yet. On the other hand, if
* {@link Adapter#notifyDataSetChanged()} has been called but the new layout has not been
* calculated yet, this method will return <code>null</code> since the new positions of views
* are unknown until the layout is calculated.
* <p>
* This method checks only the children of RecyclerView. If the item at the given
* <code>position</code> is not laid out, it <em>will not</em> create a new one.
* <p>
* When the ItemAnimator is running a change animation, there might be 2 ViewHolders
* representing the same Item. In this case, the updated ViewHolder will be returned.
*
* @param position The position of the item in the data set of the adapter
* @return The ViewHolder at <code>position</code> or null if there is no such item
**/
public ViewHolder findViewHolderForAdapterPosition(int position) {
if (mDataSetHasChangedAfterLayout) {
return null;
}
final int childCount = mChildHelper.getUnfilteredChildCount();
// hidden VHs are not preferred but if that is the only one we find, we rather return it
ViewHolder hidden = null;
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.isRemoved()
&& getAdapterPositionFor(holder) == position) {
if (mChildHelper.isHidden(holder.itemView)) {
hidden = holder;
} else {
return holder;
}
}
}
return hidden;
}
ViewHolder findViewHolderForPosition(int position, boolean checkNewPosition) {
final int childCount = mChildHelper.getUnfilteredChildCount();
ViewHolder hidden = null;
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.isRemoved()) {
if (checkNewPosition) {
if (holder.mPosition != position) {
continue;
}
} else if (holder.getLayoutPosition() != position) {
continue;
}
if (mChildHelper.isHidden(holder.itemView)) {
hidden = holder;
} else {
return holder;
}
}
}
// This method should not query cached views. It creates a problem during adapter updates
// when we are dealing with already laid out views. Also, for the public method, it is more
// reasonable to return null if position is not laid out.
return hidden;
}
/**
* Return the ViewHolder for the item with the given id. The RecyclerView must
* use an Adapter with {@link Adapter#setHasStableIds(boolean) stableIds} to
* return a non-null value.
* <p>
* This method checks only the children of RecyclerView. If the item with the given
* <code>id</code> is not laid out, it <em>will not</em> create a new one.
*
* When the ItemAnimator is running a change animation, there might be 2 ViewHolders with the
* same id. In this case, the updated ViewHolder will be returned.
*
* @param id The id for the requested item
* @return The ViewHolder with the given <code>id</code> or null if there is no such item
**/
public ViewHolder findViewHolderForItemId(long id) {
if (mAdapter == null || !mAdapter.hasStableIds()) {
return null;
}
final int childCount = mChildHelper.getUnfilteredChildCount();
ViewHolder hidden = null;
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.isRemoved() && holder.getItemId() == id) {
if (mChildHelper.isHidden(holder.itemView)) {
hidden = holder;
} else {
return holder;
}
}
}
return hidden;
}
/**
* Find the topmost view under the given point.
*
* @param x Horizontal position in pixels to search
* @param y Vertical position in pixels to search
* @return The child view under (x, y) or null if no matching child is found
**/
public View findChildViewUnder(float x, float y) {
final int count = mChildHelper.getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = mChildHelper.getChildAt(i);
final float translationX = child.getTranslationX();
final float translationY = child.getTranslationY();
if (x >= child.getLeft() + translationX
&& x <= child.getRight() + translationX
&& y >= child.getTop() + translationY
&& y <= child.getBottom() + translationY) {
return child;
}
}
return null;
}
@Override
public boolean drawChild(Canvas canvas, View child, long drawingTime) {
return super.drawChild(canvas, child, drawingTime);
}
/**
* Offset the bounds of all child views by <code>dy</code> pixels.
* Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}.
*
* @param dy Vertical pixel offset to apply to the bounds of all child views
**/
public void offsetChildrenVertical(int dy) {
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
mChildHelper.getChildAt(i).offsetTopAndBottom(dy);
}
}
/**
* Called when an item view is attached to this RecyclerView.
*
* <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications
* of child views as they become attached. This will be called before a
* {@link LayoutManager} measures or lays out the view and is a good time to perform these
* changes.</p>
*
* @param child Child view that is now attached to this RecyclerView and its associated window
**/
public void onChildAttachedToWindow(View child) {
}
/**
* Called when an item view is detached from this RecyclerView.
*
* <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications
* of child views as they become detached. This will be called as a
* {@link LayoutManager} fully detaches the child view from the parent and its window.</p>
*
* @param child Child view that is now detached from this RecyclerView and its associated window
**/
public void onChildDetachedFromWindow(View child) {
}
/**
* Offset the bounds of all child views by <code>dx</code> pixels.
* Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}.
*
* @param dx Horizontal pixel offset to apply to the bounds of all child views
**/
public void offsetChildrenHorizontal(int dx) {
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
mChildHelper.getChildAt(i).offsetLeftAndRight(dx);
}
}
/**
* Returns the bounds of the view including its decoration and margins.
*
* @param view The view element to check
* @param outBounds A rect that will receive the bounds of the element including its
* decoration and margins.
**/
public void getDecoratedBoundsWithMargins(View view, Rect outBounds) {
getDecoratedBoundsWithMarginsInt(view, outBounds);
}
static void getDecoratedBoundsWithMarginsInt(View view, Rect outBounds) {
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
final Rect insets = lp.mDecorInsets;
outBounds.set(view.getLeft() - insets.left - lp.leftMargin,
view.getTop() - insets.top - lp.topMargin,
view.getRight() + insets.right + lp.rightMargin,
view.getBottom() + insets.bottom + lp.bottomMargin);
}
Rect getItemDecorInsetsForChild(View child) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.mInsetsDirty) {
return lp.mDecorInsets;
}
if (mState.isPreLayout() && (lp.isItemChanged() || lp.isViewInvalid())) {
// changed/invalid items should not be updated until they are rebound.
return lp.mDecorInsets;
}
final Rect insets = lp.mDecorInsets;
insets.set(0, 0, 0, 0);
final int decorCount = mItemDecorations.size();
for (int i = 0; i < decorCount; i++) {
mTempRect.set(0, 0, 0, 0);
//getItemOffsets()实现分割线的回调方法!
mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
insets.left += mTempRect.left;
insets.top += mTempRect.top;
insets.right += mTempRect.right;
insets.bottom += mTempRect.bottom;
}
lp.mInsetsDirty = false;
return insets;
}
/**
* Called when the scroll position of this RecyclerView changes. Subclasses should use
* this method to respond to scrolling within the adapter's data set instead of an explicit
* listener.
*
* <p>This method will always be invoked before listeners. If a subclass needs to perform
* any additional upkeep or bookkeeping after scrolling but before listeners run,
* this is a good place to do so.</p>
*
* <p>This differs from {@link View#onScrollChanged(int, int, int, int)} in that it receives
* the distance scrolled in either direction within the adapter's data set instead of absolute
* scroll coordinates. Since RecyclerView cannot compute the absolute scroll position from
* any arbitrary point in the data set, <code>onScrollChanged</code> will always receive
* the current {@link View#getScrollX()} and {@link View#getScrollY()} values which
* do not correspond to the data set scroll position. However, some subclasses may choose
* to use these fields as special offsets.</p>
*
* @param dx horizontal distance scrolled in pixels
* @param dy vertical distance scrolled in pixels
**/
public void onScrolled(int dx, int dy) {
// Do nothing
}
void dispatchOnScrolled(int hresult, int vresult) {
mDispatchScrollCounter++;
// Pass the current scrollX/scrollY values; no actual change in these properties occurred
// but some general-purpose code may choose to respond to changes this way.
final int scrollX = getScrollX();
final int scrollY = getScrollY();
onScrollChanged(scrollX, scrollY, scrollX, scrollY);
// Pass the real deltas to onScrolled, the RecyclerView-specific method.
onScrolled(hresult, vresult);
// Invoke listeners last. Subclassed view methods always handle the event first.
// All internal state is consistent by the time listeners are invoked.
if (mScrollListener != null) {
mScrollListener.onScrolled(this, hresult, vresult);
}
if (mScrollListeners != null) {
for (int i = mScrollListeners.size() - 1; i >= 0; i--) {
mScrollListeners.get(i).onScrolled(this, hresult, vresult);
}
}
mDispatchScrollCounter--;
}
/**
* Called when the scroll state of this RecyclerView changes. Subclasses should use this
* method to respond to state changes instead of an explicit listener.
*
* <p>This method will always be invoked before listeners, but after the LayoutManager
* responds to the scroll state change.</p>
*
* @param state the new scroll state, one of {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}
**/
public void onScrollStateChanged(int state) {
// Do nothing
}
void dispatchOnScrollStateChanged(int state) {
// Let the LayoutManager go first; this allows it to bring any properties into
// a consistent state before the RecyclerView subclass responds.
if (mLayout != null) {
mLayout.onScrollStateChanged(state);
}
// Let the RecyclerView subclass handle this event next; any LayoutManager property
// changes will be reflected by this time.
onScrollStateChanged(state);
// Listeners go last. All other internal state is consistent by this point.
if (mScrollListener != null) {
mScrollListener.onScrollStateChanged(this, state);
}
if (mScrollListeners != null) {
for (int i = mScrollListeners.size() - 1; i >= 0; i--) {
mScrollListeners.get(i).onScrollStateChanged(this, state);
}
}
}
/**
* Returns whether there are pending adapter updates which are not yet applied to the layout.
* <p>
* If this method returns <code>true</code>, it means that what user is currently seeing may not
* reflect them adapter contents (depending on what has changed).
* You may use this information to defer or cancel some operations.
* <p>
* This method returns true if RecyclerView has not yet calculated the first layout after it is
* attached to the Window or the Adapter has been replaced.
*
* @return True if there are some adapter updates which are not yet reflected to layout or false
* if layout is up to date.
**/
public boolean hasPendingAdapterUpdates() {
return !mFirstLayoutComplete || mDataSetHasChangedAfterLayout
|| mAdapterHelper.hasPendingUpdates();
}
class ViewFlinger implements Runnable {
private int mLastFlingX;
private int mLastFlingY;
private OverScroller mScroller;
Interpolator mInterpolator = sQuinticInterpolator;
// When set to true, postOnAnimation callbacks are delayed until the run method completes
private boolean mEatRunOnAnimationRequest = false;
// Tracks if postAnimationCallback should be re-attached when it is done
private boolean mReSchedulePostAnimationCallback = false;
ViewFlinger() {
mScroller = new OverScroller(getContext(), sQuinticInterpolator);
}
@Override
public void run() {
if (mLayout == null) {
stop();
return; // no layout, cannot scroll.
}
disableRunOnAnimationRequests();
consumePendingUpdateOperations();
// keep a local reference so that if it is changed during onAnimation method, it won't
// cause unexpected behaviors
final OverScroller scroller = mScroller;
final SmoothScroller smoothScroller = mLayout.mSmoothScroller;
if (scroller.computeScrollOffset()) {
final int[] scrollConsumed = mScrollConsumed;
final int x = scroller.getCurrX();
final int y = scroller.getCurrY();
int dx = x - mLastFlingX;
int dy = y - mLastFlingY;
int hresult = 0;
int vresult = 0;
mLastFlingX = x;
mLastFlingY = y;
int overscrollX = 0, overscrollY = 0;
if (dispatchNestedPreScroll(dx, dy, scrollConsumed, null, TYPE_NON_TOUCH)) {
dx -= scrollConsumed[0];
dy -= scrollConsumed[1];
}
if (mAdapter != null) {
eatRequestLayout();
onEnterLayoutOrScroll();
TraceCompat.beginSection(TRACE_SCROLL_TAG);
fillRemainingScrollValues(mState);
if (dx != 0) {
hresult = mLayout.scrollHorizontallyBy(dx, mRecycler, mState);
overscrollX = dx - hresult;
}
if (dy != 0) {
vresult = mLayout.scrollVerticallyBy(dy, mRecycler, mState);
overscrollY = dy - vresult;
}
TraceCompat.endSection();
repositionShadowingViews();
onExitLayoutOrScroll();
resumeRequestLayout(false);
if (smoothScroller != null && !smoothScroller.isPendingInitialRun()
&& smoothScroller.isRunning()) {
final int adapterSize = mState.getItemCount();
if (adapterSize == 0) {
smoothScroller.stop();
} else if (smoothScroller.getTargetPosition() >= adapterSize) {
smoothScroller.setTargetPosition(adapterSize - 1);
smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY);
} else {
smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY);
}
}
}
if (!mItemDecorations.isEmpty()) {
invalidate();
}
if (getOverScrollMode() != View.OVER_SCROLL_NEVER) {
considerReleasingGlowsOnScroll(dx, dy);
}
if (!dispatchNestedScroll(hresult, vresult, overscrollX, overscrollY, null,
TYPE_NON_TOUCH)
&& (overscrollX != 0 || overscrollY != 0)) {
final int vel = (int) scroller.getCurrVelocity();
int velX = 0;
if (overscrollX != x) {
velX = overscrollX < 0 ? -vel : overscrollX > 0 ? vel : 0;
}
int velY = 0;
if (overscrollY != y) {
velY = overscrollY < 0 ? -vel : overscrollY > 0 ? vel : 0;
}
if (getOverScrollMode() != View.OVER_SCROLL_NEVER) {
absorbGlows(velX, velY);
}
if ((velX != 0 || overscrollX == x || scroller.getFinalX() == 0)
&& (velY != 0 || overscrollY == y || scroller.getFinalY() == 0)) {
scroller.abortAnimation();
}
}
if (hresult != 0 || vresult != 0) {
dispatchOnScrolled(hresult, vresult);
}
if (!awakenScrollBars()) {
invalidate();
}
final boolean fullyConsumedVertical = dy != 0 && mLayout.canScrollVertically()
&& vresult == dy;
final boolean fullyConsumedHorizontal = dx != 0 && mLayout.canScrollHorizontally()
&& hresult == dx;
final boolean fullyConsumedAny = (dx == 0 && dy == 0) || fullyConsumedHorizontal
|| fullyConsumedVertical;
if (scroller.isFinished() || (!fullyConsumedAny
&& !hasNestedScrollingParent(TYPE_NON_TOUCH))) {
// setting state to idle will stop this.
setScrollState(SCROLL_STATE_IDLE);
if (ALLOW_THREAD_GAP_WORK) {
mPrefetchRegistry.clearPrefetchPositions();
}
stopNestedScroll(TYPE_NON_TOUCH);
} else {
postOnAnimation();
if (mGapWorker != null) {
mGapWorker.postFromTraversal(RecyclerView.this, dx, dy);
}
}
}
// call this after the onAnimation is complete not to have inconsistent callbacks etc.
if (smoothScroller != null) {
if (smoothScroller.isPendingInitialRun()) {
smoothScroller.onAnimation(0, 0);
}
if (!mReSchedulePostAnimationCallback) {
smoothScroller.stop(); //stop if it does not trigger any scroll
}
}
enableRunOnAnimationRequests();
}
private void disableRunOnAnimationRequests() {
mReSchedulePostAnimationCallback = false;
mEatRunOnAnimationRequest = true;
}
private void enableRunOnAnimationRequests() {
mEatRunOnAnimationRequest = false;
if (mReSchedulePostAnimationCallback) {
postOnAnimation();
}
}
void postOnAnimation() {
if (mEatRunOnAnimationRequest) {
mReSchedulePostAnimationCallback = true;
} else {
removeCallbacks(this);
ViewCompat.postOnAnimation(RecyclerView.this, this);
}
}
public void fling(int velocityX, int velocityY) {
setScrollState(SCROLL_STATE_SETTLING);
mLastFlingX = mLastFlingY = 0;
mScroller.fling(0, 0, velocityX, velocityY,
Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
postOnAnimation();
}
public void smoothScrollBy(int dx, int dy) {
smoothScrollBy(dx, dy, 0, 0);
}
public void smoothScrollBy(int dx, int dy, int vx, int vy) {
smoothScrollBy(dx, dy, computeScrollDuration(dx, dy, vx, vy));
}
private float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * (float) Math.PI / 2.0f;
return (float) Math.sin(f);
}
private int computeScrollDuration(int dx, int dy, int vx, int vy) {
final int absDx = Math.abs(dx);
final int absDy = Math.abs(dy);
final boolean horizontal = absDx > absDy;
final int velocity = (int) Math.sqrt(vx * vx + vy * vy);
final int delta = (int) Math.sqrt(dx * dx + dy * dy);
final int containerSize = horizontal ? getWidth() : getHeight();
final int halfContainerSize = containerSize / 2;
final float distanceRatio = Math.min(1.f, 1.f * delta / containerSize);
final float distance = halfContainerSize + halfContainerSize
* distanceInfluenceForSnapDuration(distanceRatio);
final int duration;
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
float absDelta = (float) (horizontal ? absDx : absDy);
duration = (int) (((absDelta / containerSize) + 1) * 300);
}
return Math.min(duration, MAX_SCROLL_DURATION);
}
public void smoothScrollBy(int dx, int dy, int duration) {
smoothScrollBy(dx, dy, duration, sQuinticInterpolator);
}
public void smoothScrollBy(int dx, int dy, Interpolator interpolator) {
smoothScrollBy(dx, dy, computeScrollDuration(dx, dy, 0, 0),
interpolator == null ? sQuinticInterpolator : interpolator);
}
public void smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) {
if (mInterpolator != interpolator) {
mInterpolator = interpolator;
mScroller = new OverScroller(getContext(), interpolator);
}
setScrollState(SCROLL_STATE_SETTLING);
mLastFlingX = mLastFlingY = 0;
mScroller.startScroll(0, 0, dx, dy, duration);
if (Build.VERSION.SDK_INT < 23) {
// b/64931938 before API 23, startScroll() does not reset getCurX()/getCurY()
// to start values, which causes fillRemainingScrollValues() put in obsolete values
// for LayoutManager.onLayoutChildren().
mScroller.computeScrollOffset();
}
postOnAnimation();
}
public void stop() {
removeCallbacks(this);
mScroller.abortAnimation();
}
}
void repositionShadowingViews() {
// Fix up shadow views used by change animations
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; i++) {
View view = mChildHelper.getChildAt(i);
ViewHolder holder = getChildViewHolder(view);
if (holder != null && holder.mShadowingHolder != null) {
View shadowingView = holder.mShadowingHolder.itemView;
int left = view.getLeft();
int top = view.getTop();
if (left != shadowingView.getLeft() || top != shadowingView.getTop()) {
shadowingView.layout(left, top,
left + shadowingView.getWidth(),
top + shadowingView.getHeight());
}
}
}
}
private class RecyclerViewDataObserver extends AdapterDataObserver {
RecyclerViewDataObserver() {
}
/**
* notifydatasetchange调用的方法
*/
@Override
public void onChanged() {
assertNotInLayoutOrScroll(null);
mState.mStructureChanged = true;
//设置所有的View的Flag
setDataSetChangedAfterLayout();
if (!mAdapterHelper.hasPendingUpdates()) {
requestLayout();
}
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeChanged(positionStart, itemCount, payload)) {
triggerUpdateProcessor();
}
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeInserted(positionStart, itemCount)) {
triggerUpdateProcessor();
}
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeRemoved(positionStart, itemCount)) {
triggerUpdateProcessor();
}
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeMoved(fromPosition, toPosition, itemCount)) {
triggerUpdateProcessor();
}
}
void triggerUpdateProcessor() {
if (POST_UPDATES_ON_ANIMATION && mHasFixedSize && mIsAttached) {
ViewCompat.postOnAnimation(RecyclerView.this, mUpdateChildViewsRunnable);
} else {
//注意这里将mAdapterUpdateDuringMeasure设为true
mAdapterUpdateDuringMeasure = true;
requestLayout();
}
}
}
/**
* RecycledViewPool lets you share Views between multiple RecyclerViews.
* <p>
* If you want to recycle views across RecyclerViews, create an instance of RecycledViewPool
* and use {@link RecyclerView#setRecycledViewPool(RecycledViewPool)}.
* <p>
* RecyclerView automatically creates a pool for itself if you don't provide one.
*
**/
public static class RecycledViewPool {
private static final int DEFAULT_MAX_SCRAP = 5;
/**
* Tracks both pooled holders, as well as create/bind timing metadata for the given type.
*
* Note that this tracks running averages of create/bind time across all RecyclerViews
* (and, indirectly, Adapters) that use this pool.
*
* 1) This enables us to track average create and bind times across multiple adapters. Even
* though create (and especially bind) may behave differently for different Adapter
* subclasses, sharing the pool is a strong signal that they'll perform similarly, per type.
*
* 2) If {@link #willBindInTime(int, long, long)} returns false for one view, it will return
* false for all other views of its type for the same deadline. This prevents items
* constructed by {@link GapWorker} prefetch from being bound to a lower priority prefetch.
**/
static class ScrapData {
ArrayList<ViewHolder> mScrapHeap = new ArrayList<>();
int mMaxScrap = DEFAULT_MAX_SCRAP;
long mCreateRunningAverageNs = 0;
long mBindRunningAverageNs = 0;
}
SparseArray<ScrapData> mScrap = new SparseArray<>();
private int mAttachCount = 0;
public void clear() {
for (int i = 0; i < mScrap.size(); i++) {
ScrapData data = mScrap.valueAt(i);
data.mScrapHeap.clear();
}
}
public void setMaxRecycledViews(int viewType, int max) {
ScrapData scrapData = getScrapDataForType(viewType);
scrapData.mMaxScrap = max;
final ArrayList<ViewHolder> scrapHeap = scrapData.mScrapHeap;
if (scrapHeap != null) {
while (scrapHeap.size() > max) {
scrapHeap.remove(scrapHeap.size() - 1);
}
}
}
/**
* Returns the current number of Views held by the RecycledViewPool of the given view type.
**/
public int getRecycledViewCount(int viewType) {
return getScrapDataForType(viewType).mScrapHeap.size();
}
public ViewHolder getRecycledView(int viewType) {
final ScrapData scrapData = mScrap.get(viewType);
if (scrapData != null && !scrapData.mScrapHeap.isEmpty()) {
final ArrayList<ViewHolder> scrapHeap = scrapData.mScrapHeap;
return scrapHeap.remove(scrapHeap.size() - 1);
}
return null;
}
int size() {
int count = 0;
for (int i = 0; i < mScrap.size(); i++) {
ArrayList<ViewHolder> viewHolders = mScrap.valueAt(i).mScrapHeap;
if (viewHolders != null) {
count += viewHolders.size();
}
}
return count;
}
public void putRecycledView(ViewHolder scrap) {
final int viewType = scrap.getItemViewType();
final ArrayList<ViewHolder> scrapHeap = getScrapDataForType(viewType).mScrapHeap;
if (mScrap.get(viewType).mMaxScrap <= scrapHeap.size()) {
return;
}
if (DEBUG && scrapHeap.contains(scrap)) {
throw new IllegalArgumentException("this scrap item already exists");
}
scrap.resetInternal();
scrapHeap.add(scrap);
}
long runningAverage(long oldAverage, long newValue) {
if (oldAverage == 0) {
return newValue;
}
return (oldAverage / 4 * 3) + (newValue / 4);
}
void factorInCreateTime(int viewType, long createTimeNs) {
ScrapData scrapData = getScrapDataForType(viewType);
scrapData.mCreateRunningAverageNs = runningAverage(
scrapData.mCreateRunningAverageNs, createTimeNs);
}
void factorInBindTime(int viewType, long bindTimeNs) {
ScrapData scrapData = getScrapDataForType(viewType);
scrapData.mBindRunningAverageNs = runningAverage(
scrapData.mBindRunningAverageNs, bindTimeNs);
}
boolean willCreateInTime(int viewType, long approxCurrentNs, long deadlineNs) {
long expectedDurationNs = getScrapDataForType(viewType).mCreateRunningAverageNs;
return expectedDurationNs == 0 || (approxCurrentNs + expectedDurationNs < deadlineNs);
}
boolean willBindInTime(int viewType, long approxCurrentNs, long deadlineNs) {
long expectedDurationNs = getScrapDataForType(viewType).mBindRunningAverageNs;
return expectedDurationNs == 0 || (approxCurrentNs + expectedDurationNs < deadlineNs);
}
void attach(Adapter adapter) {
mAttachCount++;
}
void detach() {
mAttachCount--;
}
/**
* Detaches the old adapter and attaches the new one.
* <p>
* RecycledViewPool will clear its cache if it has only one adapter attached and the new
* adapter uses a different ViewHolder than the oldAdapter.
*
* @param oldAdapter The previous adapter instance. Will be detached.
* @param newAdapter The new adapter instance. Will be attached.
* @param compatibleWithPrevious True if both oldAdapter and newAdapter are using the same
* ViewHolder and view types.
**/
void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter,
boolean compatibleWithPrevious) {
if (oldAdapter != null) {
detach();
}
if (!compatibleWithPrevious && mAttachCount == 0) {
clear();
}
if (newAdapter != null) {
attach(newAdapter);
}
}
private ScrapData getScrapDataForType(int viewType) {
ScrapData scrapData = mScrap.get(viewType);
if (scrapData == null) {
scrapData = new ScrapData();
mScrap.put(viewType, scrapData);
}
return scrapData;
}
}
/**
* Utility method for finding an internal RecyclerView, if present
**/
@Nullable
static RecyclerView findNestedRecyclerView(@NonNull View view) {
if (!(view instanceof ViewGroup)) {
return null;
}
if (view instanceof RecyclerView) {
return (RecyclerView) view;
}
final ViewGroup parent = (ViewGroup) view;
final int count = parent.getChildCount();
for (int i = 0; i < count; i++) {
final View child = parent.getChildAt(i);
final RecyclerView descendant = findNestedRecyclerView(child);
if (descendant != null) {
return descendant;
}
}
return null;
}
/**
* Utility method for clearing holder's internal RecyclerView, if present
**/
static void clearNestedRecyclerViewIfNotNested(@NonNull ViewHolder holder) {
if (holder.mNestedRecyclerView != null) {
View item = holder.mNestedRecyclerView.get();
while (item != null) {
if (item == holder.itemView) {
return; // match found, don't need to clear
}
ViewParent parent = item.getParent();
if (parent instanceof View) {
item = (View) parent;
} else {
item = null;
}
}
holder.mNestedRecyclerView = null; // not nested
}
}
/**
* Time base for deadline-aware work scheduling. Overridable for testing.
*
* Will return 0 to avoid cost of System.nanoTime where deadline-aware work scheduling
* isn't relevant.
**/
long getNanoTime() {
if (ALLOW_THREAD_GAP_WORK) {
return System.nanoTime();
} else {
return 0;
}
}
/**
* A Recycler is responsible for managing scrapped or detached item views for reuse.
*
* <p>A "scrapped" view is a view that is still attached to its parent RecyclerView but
* that has been marked for removal or reuse.</p>
*
* <p>Typical use of a Recycler by a {@link LayoutManager} will be to obtain views for
* an adapter's data set representing the data at a given position or item ID.
* If the view to be reused is considered "dirty" the adapter will be asked to rebind it.
* If not, the view can be quickly reused by the LayoutManager with no further work.
* Clean views that have not {@link android.view.View#isLayoutRequested() requested layout}
* may be repositioned by a LayoutManager without remeasurement.</p>
**/
public final class Recycler {
final ArrayList<ViewHolder> mAttachedScrap = new ArrayList<>();
ArrayList<ViewHolder> mChangedScrap = null;
final ArrayList<ViewHolder> mCachedViews = new ArrayList<ViewHolder>();
private final List<ViewHolder>
mUnmodifiableAttachedScrap = Collections.unmodifiableList(mAttachedScrap);
private int mRequestedCacheMax = DEFAULT_CACHE_SIZE;
int mViewCacheMax = DEFAULT_CACHE_SIZE;
RecycledViewPool mRecyclerPool;
private ViewCacheExtension mViewCacheExtension;
static final int DEFAULT_CACHE_SIZE = 2;
/**
* Clear scrap views out of this recycler. Detached views contained within a
* recycled view pool will remain.
**/
public void clear() {
mAttachedScrap.clear();
recycleAndClearCachedViews();
}
/**
* Set the maximum number of detached, valid views we should retain for later use.
*
* @param viewCount Number of views to keep before sending views to the shared pool
**/
public void setViewCacheSize(int viewCount) {
mRequestedCacheMax = viewCount;
updateViewCacheSize();
}
void updateViewCacheSize() {
int extraCache = mLayout != null ? mLayout.mPrefetchMaxCountObserved : 0;
mViewCacheMax = mRequestedCacheMax + extraCache;
// first, try the views that can be recycled
for (int i = mCachedViews.size() - 1;
i >= 0 && mCachedViews.size() > mViewCacheMax; i--) {
recycleCachedViewAt(i);
}
}
/**
* Returns an unmodifiable list of ViewHolders that are currently in the scrap list.
*
* @return List of ViewHolders in the scrap list.
**/
public List<ViewHolder> getScrapList() {
return mUnmodifiableAttachedScrap;
}
/**
* Helper method for getViewForPosition.
* <p>
* Checks whether a given view holder can be used for the provided position.
*
* @param holder ViewHolder
* @return true if ViewHolder matches the provided position, false otherwise
**/
boolean validateViewHolderForOffsetPosition(ViewHolder holder) {
// if it is a removed holder, nothing to verify since we cannot ask adapter anymore
// if it is not removed, verify the type and id.
if (holder.isRemoved()) {
if (DEBUG && !mState.isPreLayout()) {
throw new IllegalStateException("should not receive a removed view unless it"
+ " is pre layout" + exceptionLabel());
}
return mState.isPreLayout();
}
if (holder.mPosition < 0 || holder.mPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid view holder "
+ "adapter position" + holder + exceptionLabel());
}
if (!mState.isPreLayout()) {
// don't check type if it is pre-layout.
final int type = mAdapter.getItemViewType(holder.mPosition);
if (type != holder.getItemViewType()) {
return false;
}
}
if (mAdapter.hasStableIds()) {
return holder.getItemId() == mAdapter.getItemId(holder.mPosition);
}
return true;
}
/**
* Attempts to bind view, and account for relevant timing information. If
* deadlineNs != FOREVER_NS, this method may fail to bind, and return false.
*
* @param holder Holder to be bound.
* @param offsetPosition Position of item to be bound.
* @param position Pre-layout position of item to be bound.
* @param deadlineNs Time, relative to getNanoTime(), by which bind/create work should
* complete. If FOREVER_NS is passed, this method will not fail to
* bind the holder.
* @return
**/
private boolean tryBindViewHolderByDeadline(ViewHolder holder, int offsetPosition,
int position, long deadlineNs) {
holder.mOwnerRecyclerView = RecyclerView.this;
final int viewType = holder.getItemViewType();
long startBindNs = getNanoTime();
if (deadlineNs != FOREVER_NS
&& !mRecyclerPool.willBindInTime(viewType, startBindNs, deadlineNs)) {
// abort - we have a deadline we can't meet
return false;
}
mAdapter.bindViewHolder(holder, offsetPosition);
long endBindNs = getNanoTime();
mRecyclerPool.factorInBindTime(holder.getItemViewType(), endBindNs - startBindNs);
attachAccessibilityDelegateOnBind(holder);
if (mState.isPreLayout()) {
holder.mPreLayoutPosition = position;
}
return true;
}
/**
* Binds the given View to the position. The View can be a View previously retrieved via
* {@link #getViewForPosition(int)} or created by
* {@link Adapter#onCreateViewHolder(ViewGroup, int)}.
* <p>
* Generally, a LayoutManager should acquire its views via {@link #getViewForPosition(int)}
* and let the RecyclerView handle caching. This is a helper method for LayoutManager who
* wants to handle its own recycling logic.
* <p>
* Note that, {@link #getViewForPosition(int)} already binds the View to the position so
* you don't need to call this method unless you want to bind this View to another position.
*
* @param view The view to update.
* @param position The position of the item to bind to this View.
**/
public void bindViewToPosition(View view, int position) {
ViewHolder holder = getChildViewHolderInt(view);
if (holder == null) {
throw new IllegalArgumentException("The view does not have a ViewHolder. You cannot"
+ " pass arbitrary views to this method, they should be created by the "
+ "Adapter" + exceptionLabel());
}
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount() + exceptionLabel());
}
tryBindViewHolderByDeadline(holder, offsetPosition, position, FOREVER_NS);
final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
final LayoutParams rvLayoutParams;
if (lp == null) {
rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
holder.itemView.setLayoutParams(rvLayoutParams);
} else if (!checkLayoutParams(lp)) {
rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
holder.itemView.setLayoutParams(rvLayoutParams);
} else {
rvLayoutParams = (LayoutParams) lp;
}
rvLayoutParams.mInsetsDirty = true;
rvLayoutParams.mViewHolder = holder;
rvLayoutParams.mPendingInvalidate = holder.itemView.getParent() == null;
}
/**
* RecyclerView provides artificial position range (item count) in pre-layout state and
* automatically maps these positions to {@link Adapter} positions when
* {@link #getViewForPosition(int)} or {@link #bindViewToPosition(View, int)} is called.
* <p>
* Usually, LayoutManager does not need to worry about this. However, in some cases, your
* LayoutManager may need to call some custom component with item positions in which
* case you need the actual adapter position instead of the pre layout position. You
* can use this method to convert a pre-layout position to adapter (post layout) position.
* <p>
* Note that if the provided position belongs to a deleted ViewHolder, this method will
* return -1.
* <p>
* Calling this method in post-layout state returns the same value back.
*
* @param position The pre-layout position to convert. Must be greater or equal to 0 and
* less than {@link State#getItemCount()}.
**/
public int convertPreLayoutPositionToPostLayout(int position) {
if (position < 0 || position >= mState.getItemCount()) {
throw new IndexOutOfBoundsException("invalid position " + position + ". State "
+ "item count is " + mState.getItemCount() + exceptionLabel());
}
if (!mState.isPreLayout()) {
return position;
}
return mAdapterHelper.findPositionOffset(position);
}
/**
* Obtain a view initialized for the given position.
*
* This method should be used by {@link LayoutManager} implementations to obtain
* views to represent data from an {@link Adapter}.
* <p>
* The Recycler may reuse a scrap or detached view from a shared pool if one is
* available for the correct view type. If the adapter has not indicated that the
* data at the given position has changed, the Recycler will attempt to hand back
* a scrap view that was previously initialized for that data without rebinding.
*
* @param position Position to obtain a view for
* @return A view representing the data at <code>position</code> from <code>adapter</code>
**/
public View getViewForPosition(int position) {
return getViewForPosition(position, false);
}
View getViewForPosition(int position, boolean dryRun) {
//dryRun为false
return tryGetViewHolderForPositionByDeadline(position, dryRun, FOREVER_NS).itemView;
}
/**
* Attempts to get the ViewHolder for the given position, either from the Recycler scrap,
* cache, the RecycledViewPool, or creating it directly.
* <p>
* If a deadlineNs other than {@link #FOREVER_NS} is passed, this method early return
* rather than constructing or binding a ViewHolder if it doesn't think it has time.
* If a ViewHolder must be constructed and not enough time remains, null is returned. If a
* ViewHolder is aquired and must be bound but not enough time remains, an unbound holder is
* returned. Use {@link ViewHolder#isBound()} on the returned object to check for this.
*
* @param position Position of ViewHolder to be returned.
* @param dryRun True if the ViewHolder should not be removed from scrap/cache/
* @param deadlineNs Time, relative to getNanoTime(), by which bind/create work should
* complete. If FOREVER_NS is passed, this method will not fail to
* create/bind the holder if needed.
*
* @return ViewHolder for requested position
**/
/**
* 注释写的很清楚,从Recycler的scrap,cache,RecyclerViewPool,或者直接create创建
**/
@Nullable
ViewHolder tryGetViewHolderForPositionByDeadline(int position,
boolean dryRun, long deadlineNs) {
if (position < 0 || position >= mState.getItemCount()) {
throw new IndexOutOfBoundsException("Invalid item position " + position
+ "(" + position + "). Item count:" + mState.getItemCount()
+ exceptionLabel());
}
boolean fromScrapOrHiddenOrCache = false;
ViewHolder holder = null;
// 0) If there is a changed scrap, try to find from there
if (mState.isPreLayout()) {
//preLayout默认是false,只有有动画的时候才为true
holder = getChangedScrapViewForPosition(position);
fromScrapOrHiddenOrCache = holder != null;
}
// 1) Find by position from scrap/hidden list/cache
if (holder == null) {
holder = getScrapOrHiddenOrCachedHolderForPosition(position, dryRun);
if (holder != null) {
if (!validateViewHolderForOffsetPosition(holder)) {
//如果检查发现这个holder不是当前position的
// recycle holder (and unscrap if relevant) since it can't be used
if (!dryRun) {
// we would like to recycle this but need to make sure it is not used by
// animation logic etc.
holder.addFlags(ViewHolder.FLAG_INVALID);
//从scrap中移除
if (holder.isScrap()) {
removeDetachedView(holder.itemView, false);
holder.unScrap();
} else if (holder.wasReturnedFromScrap()) {
holder.clearReturnedFromScrapFlag();
}
//放到ViewCache或者Pool中
recycleViewHolderInternal(holder);
}
//至空继续寻找
holder = null;
} else {
fromScrapOrHiddenOrCache = true;
}
}
}
if (holder == null) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount() + exceptionLabel());
}
final int type = mAdapter.getItemViewType(offsetPosition);
// 2) Find from scrap/cache via stable ids, if exists
if (mAdapter.hasStableIds()) {
holder = getScrapOrCachedViewForId(mAdapter.getItemId(offsetPosition),
type, dryRun);
if (holder != null) {
// update position
holder.mPosition = offsetPosition;
fromScrapOrHiddenOrCache = true;
}
}
//自定义缓存
if (holder == null && mViewCacheExtension != null) {
// We are NOT sending the offsetPosition because LayoutManager does not
// know it.
final View view = mViewCacheExtension
.getViewForPositionAndType(this, position, type);
if (view != null) {
holder = getChildViewHolder(view);
if (holder == null) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view which does not have a ViewHolder"
+ exceptionLabel());
} else if (holder.shouldIgnore()) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view that is ignored. You must call stopIgnoring before"
+ " returning this view." + exceptionLabel());
}
}
}
//pool
if (holder == null) { // fallback to pool
if (DEBUG) {
Log.d(TAG, "tryGetViewHolderForPositionByDeadline("
+ position + ") fetching from shared pool");
}
holder = getRecycledViewPool().getRecycledView(type);
if (holder != null) {
holder.resetInternal();
if (FORCE_INVALIDATE_DISPLAY_LIST) {
invalidateDisplayListInt(holder);
}
}
}
//create
if (holder == null) {
long start = getNanoTime();
if (deadlineNs != FOREVER_NS
&& !mRecyclerPool.willCreateInTime(type, start, deadlineNs)) {
// abort - we have a deadline we can't meet
return null;
}
holder = mAdapter.createViewHolder(RecyclerView.this, type);
if (ALLOW_THREAD_GAP_WORK) {
// only bother finding nested RV if prefetching
RecyclerView innerView = findNestedRecyclerView(holder.itemView);
if (innerView != null) {
holder.mNestedRecyclerView = new WeakReference<>(innerView);
}
}
long end = getNanoTime();
mRecyclerPool.factorInCreateTime(type, end - start);
if (DEBUG) {
Log.d(TAG, "tryGetViewHolderForPositionByDeadline created new ViewHolder");
}
}
}
// This is very ugly but the only place we can grab this information
// before the View is rebound and returned to the LayoutManager for post layout ops.
// We don't need this in pre-layout since the VH is not updated by the LM.
if (fromScrapOrHiddenOrCache && !mState.isPreLayout() && holder
.hasAnyOfTheFlags(ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST)) {
holder.setFlags(0, ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);
if (mState.mRunSimpleAnimations) {
int changeFlags = ItemAnimator
.buildAdapterChangeFlagsForAnimations(holder);
changeFlags |= ItemAnimator.FLAG_APPEARED_IN_PRE_LAYOUT;
final ItemHolderInfo info = mItemAnimator.recordPreLayoutInformation(mState,
holder, changeFlags, holder.getUnmodifiedPayloads());
recordAnimationInfoIfBouncedHiddenView(holder, info);
}
}
boolean bound = false;
if (mState.isPreLayout() && holder.isBound()) {
// do not update unless we absolutely have to.
holder.mPreLayoutPosition = position;
} else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) {
//如果FLAG是ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID,则需要调bind
if (DEBUG && holder.isRemoved()) {
throw new IllegalStateException("Removed holder should be bound and it should"
+ " come here only in pre-layout. Holder: " + holder
+ exceptionLabel());
}
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
bound = tryBindViewHolderByDeadline(holder, offsetPosition, position, deadlineNs);
}
final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
final LayoutParams rvLayoutParams;
if (lp == null) {
rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
holder.itemView.setLayoutParams(rvLayoutParams);
} else if (!checkLayoutParams(lp)) {
rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
holder.itemView.setLayoutParams(rvLayoutParams);
} else {
rvLayoutParams = (LayoutParams) lp;
}
rvLayoutParams.mViewHolder = holder;
rvLayoutParams.mPendingInvalidate = fromScrapOrHiddenOrCache && bound;
return holder;
}
private void attachAccessibilityDelegateOnBind(ViewHolder holder) {
if (isAccessibilityEnabled()) {
final View itemView = holder.itemView;
if (ViewCompat.getImportantForAccessibility(itemView)
== ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(itemView,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
if (!ViewCompat.hasAccessibilityDelegate(itemView)) {
holder.addFlags(ViewHolder.FLAG_SET_A11Y_ITEM_DELEGATE);
ViewCompat.setAccessibilityDelegate(itemView,
mAccessibilityDelegate.getItemDelegate());
}
}
}
private void invalidateDisplayListInt(ViewHolder holder) {
if (holder.itemView instanceof ViewGroup) {
invalidateDisplayListInt((ViewGroup) holder.itemView, false);
}
}
private void invalidateDisplayListInt(ViewGroup viewGroup, boolean invalidateThis) {
for (int i = viewGroup.getChildCount() - 1; i >= 0; i--) {
final View view = viewGroup.getChildAt(i);
if (view instanceof ViewGroup) {
invalidateDisplayListInt((ViewGroup) view, true);
}
}
if (!invalidateThis) {
return;
}
// we need to force it to become invisible
if (viewGroup.getVisibility() == View.INVISIBLE) {
viewGroup.setVisibility(View.VISIBLE);
viewGroup.setVisibility(View.INVISIBLE);
} else {
final int visibility = viewGroup.getVisibility();
viewGroup.setVisibility(View.INVISIBLE);
viewGroup.setVisibility(visibility);
}
}
/**
* Recycle a detached view. The specified view will be added to a pool of views
* for later rebinding and reuse.
*
* <p>A view must be fully detached (removed from parent) before it may be recycled. If the
* View is scrapped, it will be removed from scrap list.</p>
*
* @param view Removed view for recycling
* @see LayoutManager#removeAndRecycleView(View, Recycler)
**/
public void recycleView(View view) {
// This public recycle method tries to make view recycle-able since layout manager
// intended to recycle this view (e.g. even if it is in scrap or change cache)
ViewHolder holder = getChildViewHolderInt(view);
if (holder.isTmpDetached()) {
removeDetachedView(view, false);
}
//从scrap移除
if (holder.isScrap()) {
holder.unScrap();
} else if (holder.wasReturnedFromScrap()) {
holder.clearReturnedFromScrapFlag();
}
//缓存到cache和pool中
recycleViewHolderInternal(holder);
}
/**
* Internally, use this method instead of {@link #recycleView(android.view.View)} to
* catch potential bugs.
* @param view
**/
void recycleViewInternal(View view) {
recycleViewHolderInternal(getChildViewHolderInt(view));
}
void recycleAndClearCachedViews() {
final int count = mCachedViews.size();
for (int i = count - 1; i >= 0; i--) {
recycleCachedViewAt(i);
}
mCachedViews.clear();
if (ALLOW_THREAD_GAP_WORK) {
mPrefetchRegistry.clearPrefetchPositions();
}
}
/**
* Recycles a cached view and removes the view from the list. Views are added to cache
* if and only if they are recyclable, so this method does not check it again.
* <p>
* A small exception to this rule is when the view does not have an animator reference
* but transient state is true (due to animations created outside ItemAnimator). In that
* case, adapter may choose to recycle it. From RecyclerView's perspective, the view is
* still recyclable since Adapter wants to do so.
*
* @param cachedViewIndex The index of the view in cached views list
**/
void recycleCachedViewAt(int cachedViewIndex) {
if (DEBUG) {
Log.d(TAG, "Recycling cached view at index " + cachedViewIndex);
}
ViewHolder viewHolder = mCachedViews.get(cachedViewIndex);
if (DEBUG) {
Log.d(TAG, "CachedViewHolder to be recycled: " + viewHolder);
}
//将View放到Pool中,但是从CacheView中移除
addViewHolderToRecycledViewPool(viewHolder, true);
mCachedViews.remove(cachedViewIndex);
}
/**
* internal implementation checks if view is scrapped or attached and throws an exception
* if so.
* Public version un-scraps before calling recycle.
**/
void recycleViewHolderInternal(ViewHolder holder) {
if (holder.isScrap() || holder.itemView.getParent() != null) {
throw new IllegalArgumentException(
"Scrapped or attached views may not be recycled. isScrap:"
+ holder.isScrap() + " isAttached:"
+ (holder.itemView.getParent() != null) + exceptionLabel());
}
if (holder.isTmpDetached()) {
throw new IllegalArgumentException("Tmp detached view should be removed "
+ "from RecyclerView before it can be recycled: " + holder
+ exceptionLabel());
}
if (holder.shouldIgnore()) {
throw new IllegalArgumentException("Trying to recycle an ignored view holder. You"
+ " should first call stopIgnoringView(view) before calling recycle."
+ exceptionLabel());
}
//noinspection unchecked
final boolean transientStatePreventsRecycling = holder
.doesTransientStatePreventRecycling();
final boolean forceRecycle = mAdapter != null
&& transientStatePreventsRecycling
&& mAdapter.onFailedToRecycleView(holder);
boolean cached = false;
boolean recycled = false;
if (DEBUG && mCachedViews.contains(holder)) {
throw new IllegalArgumentException("cached view received recycle internal? "
+ holder + exceptionLabel());
}
if (forceRecycle || holder.isRecyclable()) {
if (mViewCacheMax > 0
&& !holder.hasAnyOfTheFlags(ViewHolder.FLAG_INVALID
| ViewHolder.FLAG_REMOVED
| ViewHolder.FLAG_UPDATE
| ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN)) {
// Retire oldest cached view
int cachedViewSize = mCachedViews.size();
//如果超过默认大小,则删除第一个
if (cachedViewSize >= mViewCacheMax && cachedViewSize > 0) {
recycleCachedViewAt(0);
cachedViewSize--;
}
int targetCacheIndex = cachedViewSize;
if (ALLOW_THREAD_GAP_WORK
&& cachedViewSize > 0
&& !mPrefetchRegistry.lastPrefetchIncludedPosition(holder.mPosition)) {
// when adding the view, skip past most recently prefetched views
int cacheIndex = cachedViewSize - 1;
while (cacheIndex >= 0) {
int cachedPos = mCachedViews.get(cacheIndex).mPosition;
if (!mPrefetchRegistry.lastPrefetchIncludedPosition(cachedPos)) {
break;
}
cacheIndex--;
}
targetCacheIndex = cacheIndex + 1;
}
//加入缓存
mCachedViews.add(targetCacheIndex, holder);
cached = true;
}
if (!cached) {
//不然直接加入Pool中
addViewHolderToRecycledViewPool(holder, true);
recycled = true;
}
} else {
// NOTE: A view can fail to be recycled when it is scrolled off while an animation
// runs. In this case, the item is eventually recycled by
// ItemAnimatorRestoreListener#onAnimationFinished.
// TODO: consider cancelling an animation when an item is removed scrollBy,
// to return it to the pool faster
if (DEBUG) {
Log.d(TAG, "trying to recycle a non-recycleable holder. Hopefully, it will "
+ "re-visit here. We are still removing it from animation lists"
+ exceptionLabel());
}
}
// even if the holder is not removed, we still call this method so that it is removed
// from view holder lists.
mViewInfoStore.removeViewHolder(holder);
if (!cached && !recycled && transientStatePreventsRecycling) {
holder.mOwnerRecyclerView = null;
}
}
/**
* Prepares the ViewHolder to be removed/recycled, and inserts it into the RecycledViewPool.
*
* Pass false to dispatchRecycled for views that have not been bound.
*
* @param holder Holder to be added to the pool.
* @param dispatchRecycled True to dispatch View recycled callbacks.
**/
void addViewHolderToRecycledViewPool(ViewHolder holder, boolean dispatchRecycled) {
clearNestedRecyclerViewIfNotNested(holder);
if (holder.hasAnyOfTheFlags(ViewHolder.FLAG_SET_A11Y_ITEM_DELEGATE)) {
holder.setFlags(0, ViewHolder.FLAG_SET_A11Y_ITEM_DELEGATE);
ViewCompat.setAccessibilityDelegate(holder.itemView, null);
}
if (dispatchRecycled) {
dispatchViewRecycled(holder);
}
holder.mOwnerRecyclerView = null;
getRecycledViewPool().putRecycledView(holder);
}
/**
* Used as a fast path for unscrapping and recycling a view during a bulk operation.
* The caller must call {@link #clearScrap()} when it's done to update the recycler's
* internal bookkeeping.
**/
void quickRecycleScrapView(View view) {
final ViewHolder holder = getChildViewHolderInt(view);
holder.mScrapContainer = null;
holder.mInChangeScrap = false;
holder.clearReturnedFromScrapFlag();
recycleViewHolderInternal(holder);
}
/**
* Mark an attached view as scrap.
*
* <p>"Scrap" views are still attached to their parent RecyclerView but are eligible
* for rebinding and reuse. Requests for a view for a given position may return a
* reused or rebound scrap view instance.</p>
*
* @param view View to scrap
**/
void scrapView(View view) {
final ViewHolder holder = getChildViewHolderInt(view);
//如果是REMOVE或者INVALID,加入到attachScrap不然放到changeScrap中
if (holder.hasAnyOfTheFlags(ViewHolder.FLAG_REMOVED | ViewHolder.FLAG_INVALID)
|| !holder.isUpdated() || canReuseUpdatedViewHolder(holder)) {
if (holder.isInvalid() && !holder.isRemoved() && !mAdapter.hasStableIds()) {
throw new IllegalArgumentException("Called scrap view with an invalid view."
+ " Invalid views cannot be reused from scrap, they should rebound from"
+ " recycler pool." + exceptionLabel());
}
holder.setScrapContainer(this, false);
mAttachedScrap.add(holder);
} else {
if (mChangedScrap == null) {
mChangedScrap = new ArrayList<ViewHolder>();
}
holder.setScrapContainer(this, true);
mChangedScrap.add(holder);
}
}
/**
* Remove a previously scrapped view from the pool of eligible scrap.
*
* <p>This view will no longer be eligible for reuse until re-scrapped or
* until it is explicitly removed and recycled.</p>
**/
void unscrapView(ViewHolder holder) {
if (holder.mInChangeScrap) {
mChangedScrap.remove(holder);
} else {
mAttachedScrap.remove(holder);
}
holder.mScrapContainer = null;
holder.mInChangeScrap = false;
holder.clearReturnedFromScrapFlag();
}
int getScrapCount() {
return mAttachedScrap.size();
}
View getScrapViewAt(int index) {
return mAttachedScrap.get(index).itemView;
}
void clearScrap() {
mAttachedScrap.clear();
if (mChangedScrap != null) {
mChangedScrap.clear();
}
}
ViewHolder getChangedScrapViewForPosition(int position) {
// If pre-layout, check the changed scrap for an exact match.
final int changedScrapSize;
if (mChangedScrap == null || (changedScrapSize = mChangedScrap.size()) == 0) {
return null;
}
// find by position
for (int i = 0; i < changedScrapSize; i++) {
final ViewHolder holder = mChangedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
// find by id
if (mAdapter.hasStableIds()) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition > 0 && offsetPosition < mAdapter.getItemCount()) {
final long id = mAdapter.getItemId(offsetPosition);
for (int i = 0; i < changedScrapSize; i++) {
final ViewHolder holder = mChangedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getItemId() == id) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
}
}
return null;
}
/**
* Returns a view for the position either from attach scrap, hidden children, or cache.
*
* @param position Item position
* @param dryRun Does a dry run, finds the ViewHolder but does not remove
* @return a ViewHolder that can be re-used for this position.
**/
ViewHolder getScrapOrHiddenOrCachedHolderForPosition(int position, boolean dryRun) {
final int scrapCount = mAttachedScrap.size();
// Try first for an exact, non-invalid match from scrap.
//先从scrap中寻找
for (int i = 0; i < scrapCount; i++) {
final ViewHolder holder = mAttachedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position
&& !holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved())) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
//dryRun为false
if (!dryRun) {
//这里获得是View
View view = mChildHelper.findHiddenNonRemovedView(position);
if (view != null) {
// This View is good to be used. We just need to unhide, detach and move to the
// scrap list.
//通过View的LayoutParam获得ViewHolder
final ViewHolder vh = getChildViewHolderInt(view);
//从HiddenView中移除
mChildHelper.unhide(view);
int layoutIndex = mChildHelper.indexOfChild(view);
if (layoutIndex == RecyclerView.NO_POSITION) {
throw new IllegalStateException("layout index should not be -1 after "
+ "unhiding a view:" + vh + exceptionLabel());
}
mChildHelper.detachViewFromParent(layoutIndex);
//添加到Scrap中,其实这里既然已经拿到了ViewHolder,可以直接传vh进去
scrapView(view);
vh.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP
| ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);
return vh;
}
}
// Search in our first-level recycled view cache.
//从CacheView中拿
final int cacheSize = mCachedViews.size();
for (int i = 0; i < cacheSize; i++) {
final ViewHolder holder = mCachedViews.get(i);
// invalid view holders may be in cache if adapter has stable ids as they can be
// retrieved via getScrapOrCachedViewForId
//holder是有效的,并且position相同
if (!holder.isInvalid() && holder.getLayoutPosition() == position) {
if (!dryRun) {
mCachedViews.remove(i);
}
if (DEBUG) {
Log.d(TAG, "getScrapOrHiddenOrCachedHolderForPosition(" + position
+ ") found match in cache: " + holder);
}
return holder;
}
}
return null;
}
ViewHolder getScrapOrCachedViewForId(long id, int type, boolean dryRun) {
// Look in our attached views first
//
final int count = mAttachedScrap.size();
for (int i = count - 1; i >= 0; i--) {
//在attachedScrap中寻找
final ViewHolder holder = mAttachedScrap.get(i);
if (holder.getItemId() == id && !holder.wasReturnedFromScrap()) {
//id相同并且不是从scrap中返回的
if (type == holder.getItemViewType()) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
if (holder.isRemoved()) {
// this might be valid in two cases:
// > item is removed but we are in pre-layout pass
// >> do nothing. return as is. make sure we don't rebind
// > item is removed then added to another position and we are in
// post layout.
// >> remove removed and invalid flags, add update flag to rebind
// because item was invisible to us and we don't know what happened in
// between.
if (!mState.isPreLayout()) {
holder.setFlags(ViewHolder.FLAG_UPDATE, ViewHolder.FLAG_UPDATE
| ViewHolder.FLAG_INVALID | ViewHolder.FLAG_REMOVED);
}
}
return holder;
} else if (!dryRun) {
// if we are running animations, it is actually better to keep it in scrap
// but this would force layout manager to lay it out which would be bad.
// Recycle this scrap. Type mismatch.
//从scrap中移除
mAttachedScrap.remove(i);
removeDetachedView(holder.itemView, false);
//加入cacheView或者pool
quickRecycleScrapView(holder.itemView);
}
}
}
//从cacheView中找
// Search the first-level cache
final int cacheSize = mCachedViews.size();
for (int i = cacheSize - 1; i >= 0; i--) {
final ViewHolder holder = mCachedViews.get(i);
if (holder.getItemId() == id) {
if (type == holder.getItemViewType()) {
if (!dryRun) {
//从cache中移除
mCachedViews.remove(i);
}
return holder;
} else if (!dryRun) {
//从cacheView中移除,但是放到pool中
recycleCachedViewAt(i);
return null;
}
}
}
return null;
}
void dispatchViewRecycled(ViewHolder holder) {
if (mRecyclerListener != null) {
mRecyclerListener.onViewRecycled(holder);
}
if (mAdapter != null) {
mAdapter.onViewRecycled(holder);
}
if (mState != null) {
mViewInfoStore.removeViewHolder(holder);
}
if (DEBUG) Log.d(TAG, "dispatchViewRecycled: " + holder);
}
void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter,
boolean compatibleWithPrevious) {
clear();
getRecycledViewPool().onAdapterChanged(oldAdapter, newAdapter, compatibleWithPrevious);
}
void offsetPositionRecordsForMove(int from, int to) {
final int start, end, inBetweenOffset;
if (from < to) {
start = from;
end = to;
inBetweenOffset = -1;
} else {
start = to;
end = from;
inBetweenOffset = 1;
}
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder == null || holder.mPosition < start || holder.mPosition > end) {
continue;
}
if (holder.mPosition == from) {
holder.offsetPosition(to - from, false);
} else {
holder.offsetPosition(inBetweenOffset, false);
}
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForMove cached child " + i + " holder "
+ holder);
}
}
}
void offsetPositionRecordsForInsert(int insertedAt, int count) {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null && holder.mPosition >= insertedAt) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForInsert cached " + i + " holder "
+ holder + " now at position " + (holder.mPosition + count));
}
holder.offsetPosition(count, true);
}
}
}
/**
* @param removedFrom Remove start index
* @param count Remove count
* @param applyToPreLayout If true, changes will affect ViewHolder's pre-layout position, if
* false, they'll be applied before the second layout pass
**/
void offsetPositionRecordsForRemove(int removedFrom, int count, boolean applyToPreLayout) {
final int removedEnd = removedFrom + count;
final int cachedCount = mCachedViews.size();
for (int i = cachedCount - 1; i >= 0; i--) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
if (holder.mPosition >= removedEnd) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove cached " + i
+ " holder " + holder + " now at position "
+ (holder.mPosition - count));
}
holder.offsetPosition(-count, applyToPreLayout);
} else if (holder.mPosition >= removedFrom) {
// Item for this view was removed. Dump it from the cache.
holder.addFlags(ViewHolder.FLAG_REMOVED);
recycleCachedViewAt(i);
}
}
}
}
void setViewCacheExtension(ViewCacheExtension extension) {
mViewCacheExtension = extension;
}
void setRecycledViewPool(RecycledViewPool pool) {
if (mRecyclerPool != null) {
mRecyclerPool.detach();
}
mRecyclerPool = pool;
if (pool != null) {
mRecyclerPool.attach(getAdapter());
}
}
RecycledViewPool getRecycledViewPool() {
if (mRecyclerPool == null) {
mRecyclerPool = new RecycledViewPool();
}
return mRecyclerPool;
}
void viewRangeUpdate(int positionStart, int itemCount) {
final int positionEnd = positionStart + itemCount;
final int cachedCount = mCachedViews.size();
for (int i = cachedCount - 1; i >= 0; i--) {
final ViewHolder holder = mCachedViews.get(i);
if (holder == null) {
continue;
}
final int pos = holder.mPosition;
if (pos >= positionStart && pos < positionEnd) {
holder.addFlags(ViewHolder.FLAG_UPDATE);
recycleCachedViewAt(i);
// cached views should not be flagged as changed because this will cause them
// to animate when they are returned from cache.
}
}
}
void markKnownViewsInvalid() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
holder.addChangePayload(null);
}
}
if (mAdapter == null || !mAdapter.hasStableIds()) {
// we cannot re-use cached views in this case. Recycle them all
recycleAndClearCachedViews();
}
}
void clearOldPositions() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
holder.clearOldPosition();
}
final int scrapCount = mAttachedScrap.size();
for (int i = 0; i < scrapCount; i++) {
mAttachedScrap.get(i).clearOldPosition();
}
if (mChangedScrap != null) {
final int changedScrapCount = mChangedScrap.size();
for (int i = 0; i < changedScrapCount; i++) {
mChangedScrap.get(i).clearOldPosition();
}
}
}
void markItemDecorInsetsDirty() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
LayoutParams layoutParams = (LayoutParams) holder.itemView.getLayoutParams();
if (layoutParams != null) {
layoutParams.mInsetsDirty = true;
}
}
}
}
/**
* ViewCacheExtension is a helper class to provide an additional layer of view caching that can
* be controlled by the developer.
* <p>
* When {@link Recycler#getViewForPosition(int)} is called, Recycler checks attached scrap and
* first level cache to find a matching View. If it cannot find a suitable View, Recycler will
* call the {@link #getViewForPositionAndType(Recycler, int, int)} before checking
* {@link RecycledViewPool}.
* <p>
* Note that, Recycler never sends Views to this method to be cached. It is developers
* responsibility to decide whether they want to keep their Views in this custom cache or let
* the default recycling policy handle it.
**/
public abstract static class ViewCacheExtension {
/**
* Returns a View that can be binded to the given Adapter position.
* <p>
* This method should <b>not</b> create a new View. Instead, it is expected to return
* an already created View that can be re-used for the given type and position.
* If the View is marked as ignored, it should first call
* {@link LayoutManager#stopIgnoringView(View)} before returning the View.
* <p>
* RecyclerView will re-bind the returned View to the position if necessary.
*
* @param recycler The Recycler that can be used to bind the View
* @param position The adapter position
* @param type The type of the View, defined by adapter
* @return A View that is bound to the given position or NULL if there is no View to re-use
* @see LayoutManager#ignoreView(View)
**/
public abstract View getViewForPositionAndType(Recycler recycler, int position, int type);
}
/**
* Base class for an Adapter
*
* <p>Adapters provide a binding from an app-specific data set to views that are displayed
* within a {@link RecyclerView}.</p>
*
* @param <VH> A class that extends ViewHolder that will be used by the adapter.
**/
public abstract static class Adapter<VH extends ViewHolder> {
private final AdapterDataObservable mObservable = new AdapterDataObservable();
private boolean mHasStableIds = false;
/**
* Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent
* an item.
* <p>
* This new ViewHolder should be constructed with a new View that can represent the items
* of the given type. You can either create a new View manually or inflate it from an XML
* layout file.
* <p>
* The new ViewHolder will be used to display items of the adapter using
* {@link #onBindViewHolder(ViewHolder, int, List)}. Since it will be re-used to display
* different items in the data set, it is a good idea to cache references to sub views of
* the View to avoid unnecessary {@link View#findViewById(int)} calls.
*
* @param parent The ViewGroup into which the new View will be added after it is bound to
* an adapter position.
* @param viewType The view type of the new View.
*
* @return A new ViewHolder that holds a View of the given view type.
* @see #getItemViewType(int)
* @see #onBindViewHolder(ViewHolder, int)
**/
public abstract VH onCreateViewHolder(ViewGroup parent, int viewType);
/**
* Called by RecyclerView to display the data at the specified position. This method should
* update the contents of the {@link ViewHolder#itemView} to reflect the item at the given
* position.
* <p>
* Note that unlike {@link android.widget.ListView}, RecyclerView will not call this method
* again if the position of the item changes in the data set unless the item itself is
* invalidated or the new position cannot be determined. For this reason, you should only
* use the <code>position</code> parameter while acquiring the related data item inside
* this method and should not keep a copy of it. If you need the position of an item later
* on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
* have the updated adapter position.
*
* Override {@link #onBindViewHolder(ViewHolder, int, List)} instead if Adapter can
* handle efficient partial bind.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
**/
public abstract void onBindViewHolder(VH holder, int position);
/**
* Called by RecyclerView to display the data at the specified position. This method
* should update the contents of the {@link ViewHolder#itemView} to reflect the item at
* the given position.
* <p>
* Note that unlike {@link android.widget.ListView}, RecyclerView will not call this method
* again if the position of the item changes in the data set unless the item itself is
* invalidated or the new position cannot be determined. For this reason, you should only
* use the <code>position</code> parameter while acquiring the related data item inside
* this method and should not keep a copy of it. If you need the position of an item later
* on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
* have the updated adapter position.
* <p>
* Partial bind vs full bind:
* <p>
* The payloads parameter is a merge list from {@link #notifyItemChanged(int, Object)} or
* {@link #notifyItemRangeChanged(int, int, Object)}. If the payloads list is not empty,
* the ViewHolder is currently bound to old data and Adapter may run an efficient partial
* update using the payload info. If the payload is empty, Adapter must run a full bind.
* Adapter should not assume that the payload passed in notify methods will be received by
* onBindViewHolder(). For example when the view is not attached to the screen, the
* payload in notifyItemChange() will be simply dropped.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
* @param payloads A non-null list of merged payloads. Can be empty list if requires full
* update.
**/
public void onBindViewHolder(VH holder, int position, List<Object> payloads) {
onBindViewHolder(holder, position);
}
/**
* This method calls {@link #onCreateViewHolder(ViewGroup, int)} to create a new
* {@link ViewHolder} and initializes some private fields to be used by RecyclerView.
*
* @see #onCreateViewHolder(ViewGroup, int)
**/
public final VH createViewHolder(ViewGroup parent, int viewType) {
TraceCompat.beginSection(TRACE_CREATE_VIEW_TAG);
final VH holder = onCreateViewHolder(parent, viewType);
holder.mItemViewType = viewType;
TraceCompat.endSection();
return holder;
}
/**
* This method internally calls {@link #onBindViewHolder(ViewHolder, int)} to update the
* {@link ViewHolder} contents with the item at the given position and also sets up some
* private fields to be used by RecyclerView.
*
* @see #onBindViewHolder(ViewHolder, int)
**/
public final void bindViewHolder(VH holder, int position) {
holder.mPosition = position;
if (hasStableIds()) {
holder.mItemId = getItemId(position);
}
holder.setFlags(ViewHolder.FLAG_BOUND,
ViewHolder.FLAG_BOUND | ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID
| ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
TraceCompat.beginSection(TRACE_BIND_VIEW_TAG);
onBindViewHolder(holder, position, holder.getUnmodifiedPayloads());
holder.clearPayload();
final ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
if (layoutParams instanceof RecyclerView.LayoutParams) {
((LayoutParams) layoutParams).mInsetsDirty = true;
}
TraceCompat.endSection();
}
/**
* Return the view type of the item at <code>position</code> for the purposes
* of view recycling.
*
* <p>The default implementation of this method returns 0, making the assumption of
* a single view type for the adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
*
* @param position position to query
* @return integer value identifying the type of the view needed to represent the item at
* <code>position</code>. Type codes need not be contiguous.
**/
public int getItemViewType(int position) {
return 0;
}
/**
* Indicates whether each item in the data set can be represented with a unique identifier
* of type {@link java.lang.Long}.
*
* @param hasStableIds Whether items in data set have unique identifiers or not.
* @see #hasStableIds()
* @see #getItemId(int)
**/
public void setHasStableIds(boolean hasStableIds) {
if (hasObservers()) {
throw new IllegalStateException("Cannot change whether this adapter has "
+ "stable IDs while the adapter has registered observers.");
}
mHasStableIds = hasStableIds;
}
/**
* Return the stable ID for the item at <code>position</code>. If {@link #hasStableIds()}
* would return false this method should return {@link #NO_ID}. The default implementation
* of this method returns {@link #NO_ID}.
*
* @param position Adapter position to query
* @return the stable ID of the item at position
**/
public long getItemId(int position) {
return NO_ID;
}
/**
* Returns the total number of items in the data set held by the adapter.
*
* @return The total number of items in this adapter.
**/
public abstract int getItemCount();
/**
* Returns true if this adapter publishes a unique <code>long</code> value that can
* act as a key for the item at a given position in the data set. If that item is relocated
* in the data set, the ID returned for that item should be the same.
*
* @return true if this adapter's items have stable IDs
**/
public final boolean hasStableIds() {
return mHasStableIds;
}
/**
* Called when a view created by this adapter has been recycled.
*
* <p>A view is recycled when a {@link LayoutManager} decides that it no longer
* needs to be attached to its parent {@link RecyclerView}. This can be because it has
* fallen out of visibility or a set of cached views represented by views still
* attached to the parent RecyclerView. If an item view has large or expensive data
* bound to it such as large bitmaps, this may be a good place to release those
* resources.</p>
* <p>
* RecyclerView calls this method right before clearing ViewHolder's internal data and
* sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
* before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get
* its adapter position.
*
* @param holder The ViewHolder for the view being recycled
**/
public void onViewRecycled(VH holder) {
}
/**
* Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled
* due to its transient state. Upon receiving this callback, Adapter can clear the
* animation(s) that effect the View's transient state and return <code>true</code> so that
* the View can be recycled. Keep in mind that the View in question is already removed from
* the RecyclerView.
* <p>
* In some cases, it is acceptable to recycle a View although it has transient state. Most
* of the time, this is a case where the transient state will be cleared in
* {@link #onBindViewHolder(ViewHolder, int)} call when View is rebound to a new position.
* For this reason, RecyclerView leaves the decision to the Adapter and uses the return
* value of this method to decide whether the View should be recycled or not.
* <p>
* Note that when all animations are created by {@link RecyclerView.ItemAnimator}, you
* should never receive this callback because RecyclerView keeps those Views as children
* until their animations are complete. This callback is useful when children of the item
* views create animations which may not be easy to implement using an {@link ItemAnimator}.
* <p>
* You should <em>never</em> fix this issue by calling
* <code>holder.itemView.setHasTransientState(false);</code> unless you've previously called
* <code>holder.itemView.setHasTransientState(true);</code>. Each
* <code>View.setHasTransientState(true)</code> call must be matched by a
* <code>View.setHasTransientState(false)</code> call, otherwise, the state of the View
* may become inconsistent. You should always prefer to end or cancel animations that are
* triggering the transient state instead of handling it manually.
*
* @param holder The ViewHolder containing the View that could not be recycled due to its
* transient state.
* @return True if the View should be recycled, false otherwise. Note that if this method
* returns <code>true</code>, RecyclerView <em>will ignore</em> the transient state of
* the View and recycle it regardless. If this method returns <code>false</code>,
* RecyclerView will check the View's transient state again before giving a final decision.
* Default implementation returns false.
**/
public boolean onFailedToRecycleView(VH holder) {
return false;
}
/**
* Called when a view created by this adapter has been attached to a window.
*
* <p>This can be used as a reasonable signal that the view is about to be seen
* by the user. If the adapter previously freed any resources in
* {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow}
* those resources should be restored here.</p>
*
* @param holder Holder of the view being attached
**/
public void onViewAttachedToWindow(VH holder) {
}
/**
* Called when a view created by this adapter has been detached from its window.
*
* <p>Becoming detached from the window is not necessarily a permanent condition;
* the consumer of an Adapter's views may choose to cache views offscreen while they
* are not visible, attaching and detaching them as appropriate.</p>
*
* @param holder Holder of the view being detached
**/
public void onViewDetachedFromWindow(VH holder) {
}
/**
* Returns true if one or more observers are attached to this adapter.
*
* @return true if this adapter has observers
**/
public final boolean hasObservers() {
return mObservable.hasObservers();
}
/**
* Register a new observer to listen for data changes.
*
* <p>The adapter may publish a variety of events describing specific changes.
* Not all adapters may support all change types and some may fall back to a generic
* {@link android.support.v7.widget.RecyclerView.AdapterDataObserver#onChanged()
* "something changed"} event if more specific data is not available.</p>
*
* <p>Components registering observers with an adapter are responsible for
* {@link #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver)
* unregistering} those observers when finished.</p>
*
* @param observer Observer to register
*
* @see #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver)
**/
public void registerAdapterDataObserver(AdapterDataObserver observer) {
mObservable.registerObserver(observer);
}
/**
* Unregister an observer currently listening for data changes.
*
* <p>The unregistered observer will no longer receive events about changes
* to the adapter.</p>
*
* @param observer Observer to unregister
*
* @see #registerAdapterDataObserver(RecyclerView.AdapterDataObserver)
**/
public void unregisterAdapterDataObserver(AdapterDataObserver observer) {
mObservable.unregisterObserver(observer);
}
/**
* Called by RecyclerView when it starts observing this Adapter.
* <p>
* Keep in mind that same adapter may be observed by multiple RecyclerViews.
*
* @param recyclerView The RecyclerView instance which started observing this adapter.
* @see #onDetachedFromRecyclerView(RecyclerView)
**/
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
}
/**
* Called by RecyclerView when it stops observing this Adapter.
*
* @param recyclerView The RecyclerView instance which stopped observing this adapter.
* @see #onAttachedToRecyclerView(RecyclerView)
**/
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
}
/**
* Notify any registered observers that the data set has changed.
*
* <p>There are two different classes of data change events, item changes and structural
* changes. Item changes are when a single item has its data updated but no positional
* changes have occurred. Structural changes are when items are inserted, removed or moved
* within the data set.</p>
*
* <p>This event does not specify what about the data set has changed, forcing
* any observers to assume that all existing items and structure may no longer be valid.
* LayoutManagers will be forced to fully rebind and relayout all visible views.</p>
*
* <p><code>RecyclerView</code> will attempt to synthesize visible structural change events
* for adapters that report that they have {@link #hasStableIds() stable IDs} when
* this method is used. This can help for the purposes of animation and visual
* object persistence but individual item views will still need to be rebound
* and relaid out.</p>
*
* <p>If you are writing an adapter it will always be more efficient to use the more
* specific change events if you can. Rely on <code>notifyDataSetChanged()</code>
* as a last resort.</p>
*
* @see #notifyItemChanged(int)
* @see #notifyItemInserted(int)
* @see #notifyItemRemoved(int)
* @see #notifyItemRangeChanged(int, int)
* @see #notifyItemRangeInserted(int, int)
* @see #notifyItemRangeRemoved(int, int)
**/
public final void notifyDataSetChanged() {
mObservable.notifyChanged();
}
/**
* Notify any registered observers that the item at <code>position</code> has changed.
* Equivalent to calling <code>notifyItemChanged(position, null);</code>.
*
* <p>This is an item change event, not a structural change event. It indicates that any
* reflection of the data at <code>position</code> is out of date and should be updated.
* The item at <code>position</code> retains the same identity.</p>
*
* @param position Position of the item that has changed
*
* @see #notifyItemRangeChanged(int, int)
**/
public final void notifyItemChanged(int position) {
mObservable.notifyItemRangeChanged(position, 1);
}
/**
* Notify any registered observers that the item at <code>position</code> has changed with
* an optional payload object.
*
* <p>This is an item change event, not a structural change event. It indicates that any
* reflection of the data at <code>position</code> is out of date and should be updated.
* The item at <code>position</code> retains the same identity.
* </p>
*
* <p>
* Client can optionally pass a payload for partial change. These payloads will be merged
* and may be passed to adapter's {@link #onBindViewHolder(ViewHolder, int, List)} if the
* item is already represented by a ViewHolder and it will be rebound to the same
* ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing
* payloads on that item and prevent future payload until
* {@link #onBindViewHolder(ViewHolder, int, List)} is called. Adapter should not assume
* that the payload will always be passed to onBindViewHolder(), e.g. when the view is not
* attached, the payload will be simply dropped.
*
* @param position Position of the item that has changed
* @param payload Optional parameter, use null to identify a "full" update
*
* @see #notifyItemRangeChanged(int, int)
**/
public final void notifyItemChanged(int position, Object payload) {
mObservable.notifyItemRangeChanged(position, 1, payload);
}
/**
* Notify any registered observers that the <code>itemCount</code> items starting at
* position <code>positionStart</code> have changed.
* Equivalent to calling <code>notifyItemRangeChanged(position, itemCount, null);</code>.
*
* <p>This is an item change event, not a structural change event. It indicates that
* any reflection of the data in the given position range is out of date and should
* be updated. The items in the given range retain the same identity.</p>
*
* @param positionStart Position of the first item that has changed
* @param itemCount Number of items that have changed
*
* @see #notifyItemChanged(int)
**/
public final void notifyItemRangeChanged(int positionStart, int itemCount) {
mObservable.notifyItemRangeChanged(positionStart, itemCount);
}
/**
* Notify any registered observers that the <code>itemCount</code> items starting at
* position <code>positionStart</code> have changed. An optional payload can be
* passed to each changed item.
*
* <p>This is an item change event, not a structural change event. It indicates that any
* reflection of the data in the given position range is out of date and should be updated.
* The items in the given range retain the same identity.
* </p>
*
* <p>
* Client can optionally pass a payload for partial change. These payloads will be merged
* and may be passed to adapter's {@link #onBindViewHolder(ViewHolder, int, List)} if the
* item is already represented by a ViewHolder and it will be rebound to the same
* ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing
* payloads on that item and prevent future payload until
* {@link #onBindViewHolder(ViewHolder, int, List)} is called. Adapter should not assume
* that the payload will always be passed to onBindViewHolder(), e.g. when the view is not
* attached, the payload will be simply dropped.
*
* @param positionStart Position of the first item that has changed
* @param itemCount Number of items that have changed
* @param payload Optional parameter, use null to identify a "full" update
*
* @see #notifyItemChanged(int)
**/
public final void notifyItemRangeChanged(int positionStart, int itemCount, Object payload) {
mObservable.notifyItemRangeChanged(positionStart, itemCount, payload);
}
/**
* Notify any registered observers that the item reflected at <code>position</code>
* has been newly inserted. The item previously at <code>position</code> is now at
* position <code>position + 1</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param position Position of the newly inserted item in the data set
*
* @see #notifyItemRangeInserted(int, int)
**/
public final void notifyItemInserted(int position) {
mObservable.notifyItemRangeInserted(position, 1);
}
/**
* Notify any registered observers that the item reflected at <code>fromPosition</code>
* has been moved to <code>toPosition</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param fromPosition Previous position of the item.
* @param toPosition New position of the item.
**/
public final void notifyItemMoved(int fromPosition, int toPosition) {
mObservable.notifyItemMoved(fromPosition, toPosition);
}
/**
* Notify any registered observers that the currently reflected <code>itemCount</code>
* items starting at <code>positionStart</code> have been newly inserted. The items
* previously located at <code>positionStart</code> and beyond can now be found starting
* at position <code>positionStart + itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Position of the first item that was inserted
* @param itemCount Number of items inserted
*
* @see #notifyItemInserted(int)
**/
public final void notifyItemRangeInserted(int positionStart, int itemCount) {
mObservable.notifyItemRangeInserted(positionStart, itemCount);
}
/**
* Notify any registered observers that the item previously located at <code>position</code>
* has been removed from the data set. The items previously located at and after
* <code>position</code> may now be found at <code>oldPosition - 1</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param position Position of the item that has now been removed
*
* @see #notifyItemRangeRemoved(int, int)
**/
public final void notifyItemRemoved(int position) {
mObservable.notifyItemRangeRemoved(position, 1);
}
/**
* Notify any registered observers that the <code>itemCount</code> items previously
* located at <code>positionStart</code> have been removed from the data set. The items
* previously located at and after <code>positionStart + itemCount</code> may now be found
* at <code>oldPosition - itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the data
* set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Previous position of the first item that was removed
* @param itemCount Number of items removed from the data set
**/
public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
mObservable.notifyItemRangeRemoved(positionStart, itemCount);
}
}
void dispatchChildDetached(View child) {
final ViewHolder viewHolder = getChildViewHolderInt(child);
onChildDetachedFromWindow(child);
if (mAdapter != null && viewHolder != null) {
mAdapter.onViewDetachedFromWindow(viewHolder);
}
if (mOnChildAttachStateListeners != null) {
final int cnt = mOnChildAttachStateListeners.size();
for (int i = cnt - 1; i >= 0; i--) {
mOnChildAttachStateListeners.get(i).onChildViewDetachedFromWindow(child);
}
}
}
void dispatchChildAttached(View child) {
final ViewHolder viewHolder = getChildViewHolderInt(child);
onChildAttachedToWindow(child);
if (mAdapter != null && viewHolder != null) {
mAdapter.onViewAttachedToWindow(viewHolder);
}
if (mOnChildAttachStateListeners != null) {
final int cnt = mOnChildAttachStateListeners.size();
for (int i = cnt - 1; i >= 0; i--) {
mOnChildAttachStateListeners.get(i).onChildViewAttachedToWindow(child);
}
}
}
/**
* A <code>LayoutManager</code> is responsible for measuring and positioning item views
* within a <code>RecyclerView</code> as well as determining the policy for when to recycle
* item views that are no longer visible to the user. By changing the <code>LayoutManager</code>
* a <code>RecyclerView</code> can be used to implement a standard vertically scrolling list,
* a uniform grid, staggered grids, horizontally scrolling collections and more. Several stock
* layout managers are provided for general use.
* <p/>
* If the LayoutManager specifies a default constructor or one with the signature
* ({@link Context}, {@link AttributeSet}, {@code int}, {@code int}), RecyclerView will
* instantiate and set the LayoutManager when being inflated. Most used properties can
* be then obtained from {@link #getProperties(Context, AttributeSet, int, int)}. In case
* a LayoutManager specifies both constructors, the non-default constructor will take
* precedence.
*
**/
public abstract static class LayoutManager {
ChildHelper mChildHelper;
RecyclerView mRecyclerView;
/**
* The callback used for retrieving information about a RecyclerView and its children in the
* horizontal direction.
**/
private final ViewBoundsCheck.Callback mHorizontalBoundCheckCallback =
new ViewBoundsCheck.Callback() {
@Override
public int getChildCount() {
return LayoutManager.this.getChildCount();
}
@Override
public View getParent() {
return mRecyclerView;
}
@Override
public View getChildAt(int index) {
return LayoutManager.this.getChildAt(index);
}
@Override
public int getParentStart() {
return LayoutManager.this.getPaddingLeft();
}
@Override
public int getParentEnd() {
return LayoutManager.this.getWidth() - LayoutManager.this.getPaddingRight();
}
@Override
public int getChildStart(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return LayoutManager.this.getDecoratedLeft(view) - params.leftMargin;
}
@Override
public int getChildEnd(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return LayoutManager.this.getDecoratedRight(view) + params.rightMargin;
}
};
/**
* The callback used for retrieving information about a RecyclerView and its children in the
* vertical direction.
**/
private final ViewBoundsCheck.Callback mVerticalBoundCheckCallback =
new ViewBoundsCheck.Callback() {
@Override
public int getChildCount() {
return LayoutManager.this.getChildCount();
}
@Override
public View getParent() {
return mRecyclerView;
}
@Override
public View getChildAt(int index) {
return LayoutManager.this.getChildAt(index);
}
@Override
public int getParentStart() {
return LayoutManager.this.getPaddingTop();
}
@Override
public int getParentEnd() {
return LayoutManager.this.getHeight()
- LayoutManager.this.getPaddingBottom();
}
@Override
public int getChildStart(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return LayoutManager.this.getDecoratedTop(view) - params.topMargin;
}
@Override
public int getChildEnd(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return LayoutManager.this.getDecoratedBottom(view) + params.bottomMargin;
}
};
/**
* Utility objects used to check the boundaries of children against their parent
* RecyclerView.
* @see #isViewPartiallyVisible(View, boolean, boolean),
* {@link LinearLayoutManager#findOneVisibleChild(int, int, boolean, boolean)},
* and {@link LinearLayoutManager#findOnePartiallyOrCompletelyInvisibleChild(int, int)}.
**/
ViewBoundsCheck mHorizontalBoundCheck = new ViewBoundsCheck(mHorizontalBoundCheckCallback);
ViewBoundsCheck mVerticalBoundCheck = new ViewBoundsCheck(mVerticalBoundCheckCallback);
@Nullable
SmoothScroller mSmoothScroller;
boolean mRequestedSimpleAnimations = false;
boolean mIsAttachedToWindow = false;
boolean mAutoMeasure = false;
/**
* LayoutManager has its own more strict measurement cache to avoid re-measuring a child
* if the space that will be given to it is already larger than what it has measured before.
**/
private boolean mMeasurementCacheEnabled = true;
private boolean mItemPrefetchEnabled = true;
/**
* Written by {@link GapWorker} when prefetches occur to track largest number of view ever
* requested by a {@link #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)} or
* {@link #collectAdjacentPrefetchPositions(int, int, State, LayoutPrefetchRegistry)} call.
*
* If expanded by a {@link #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)},
* will be reset upon layout to prevent initial prefetches (often large, since they're
* proportional to expected child count) from expanding cache permanently.
**/
int mPrefetchMaxCountObserved;
/**
* If true, mPrefetchMaxCountObserved is only valid until next layout, and should be reset.
**/
boolean mPrefetchMaxObservedInInitialPrefetch;
/**
* These measure specs might be the measure specs that were passed into RecyclerView's
* onMeasure method OR fake measure specs created by the RecyclerView.
* For example, when a layout is run, RecyclerView always sets these specs to be
* EXACTLY because a LayoutManager cannot resize RecyclerView during a layout pass.
* <p>
* Also, to be able to use the hint in unspecified measure specs, RecyclerView checks the
* API level and sets the size to 0 pre-M to avoid any issue that might be caused by
* corrupt values. Older platforms have no responsibility to provide a size if they set
* mode to unspecified.
**/
private int mWidthMode, mHeightMode;
private int mWidth, mHeight;
/**
* Interface for LayoutManagers to request items to be prefetched, based on position, with
* specified distance from viewport, which indicates priority.
*
* @see LayoutManager#collectAdjacentPrefetchPositions(int, int, State, LayoutPrefetchRegistry)
* @see LayoutManager#collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)
**/
public interface LayoutPrefetchRegistry {
/**
* Requests an an item to be prefetched, based on position, with a specified distance,
* indicating priority.
*
* @param layoutPosition Position of the item to prefetch.
* @param pixelDistance Distance from the current viewport to the bounds of the item,
* must be non-negative.
**/
void addPosition(int layoutPosition, int pixelDistance);
}
void setRecyclerView(RecyclerView recyclerView) {
if (recyclerView == null) {
mRecyclerView = null;
mChildHelper = null;
mWidth = 0;
mHeight = 0;
} else {
mRecyclerView = recyclerView;
mChildHelper = recyclerView.mChildHelper;
mWidth = recyclerView.getWidth();
mHeight = recyclerView.getHeight();
}
mWidthMode = MeasureSpec.EXACTLY;
mHeightMode = MeasureSpec.EXACTLY;
}
void setMeasureSpecs(int wSpec, int hSpec) {
mWidth = MeasureSpec.getSize(wSpec);
mWidthMode = MeasureSpec.getMode(wSpec);
if (mWidthMode == MeasureSpec.UNSPECIFIED && !ALLOW_SIZE_IN_UNSPECIFIED_SPEC) {
mWidth = 0;
}
mHeight = MeasureSpec.getSize(hSpec);
mHeightMode = MeasureSpec.getMode(hSpec);
if (mHeightMode == MeasureSpec.UNSPECIFIED && !ALLOW_SIZE_IN_UNSPECIFIED_SPEC) {
mHeight = 0;
}
}
/**
* Called after a layout is calculated during a measure pass when using auto-measure.
* <p>
* It simply traverses all children to calculate a bounding box then calls
* {@link #setMeasuredDimension(Rect, int, int)}. LayoutManagers can override that method
* if they need to handle the bounding box differently.
* <p>
* For example, GridLayoutManager override that method to ensure that even if a column is
* empty, the GridLayoutManager still measures wide enough to include it.
*
* @param widthSpec The widthSpec that was passing into RecyclerView's onMeasure
* @param heightSpec The heightSpec that was passing into RecyclerView's onMeasure
**/
void setMeasuredDimensionFromChildren(int widthSpec, int heightSpec) {
final int count = getChildCount();
if (count == 0) {
mRecyclerView.defaultOnMeasure(widthSpec, heightSpec);
return;
}
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
final Rect bounds = mRecyclerView.mTempRect;
getDecoratedBoundsWithMargins(child, bounds);
if (bounds.left < minX) {
minX = bounds.left;
}
if (bounds.right > maxX) {
maxX = bounds.right;
}
if (bounds.top < minY) {
minY = bounds.top;
}
if (bounds.bottom > maxY) {
maxY = bounds.bottom;
}
}
mRecyclerView.mTempRect.set(minX, minY, maxX, maxY);
setMeasuredDimension(mRecyclerView.mTempRect, widthSpec, heightSpec);
}
/**
* Sets the measured dimensions from the given bounding box of the children and the
* measurement specs that were passed into {@link RecyclerView#onMeasure(int, int)}. It is
* called after the RecyclerView calls
* {@link LayoutManager#onLayoutChildren(Recycler, State)} during a measurement pass.
* <p>
* This method should call {@link #setMeasuredDimension(int, int)}.
* <p>
* The default implementation adds the RecyclerView's padding to the given bounding box
* then caps the value to be within the given measurement specs.
* <p>
* This method is only called if the LayoutManager opted into the auto measurement API.
*
* @param childrenBounds The bounding box of all children
* @param wSpec The widthMeasureSpec that was passed into the RecyclerView.
* @param hSpec The heightMeasureSpec that was passed into the RecyclerView.
*
* @see #setAutoMeasureEnabled(boolean)
**/
public void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec) {
int usedWidth = childrenBounds.width() + getPaddingLeft() + getPaddingRight();
int usedHeight = childrenBounds.height() + getPaddingTop() + getPaddingBottom();
int width = chooseSize(wSpec, usedWidth, getMinimumWidth());
int height = chooseSize(hSpec, usedHeight, getMinimumHeight());
setMeasuredDimension(width, height);
}
/**
* Calls {@code RecyclerView#requestLayout} on the underlying RecyclerView
**/
public void requestLayout() {
if (mRecyclerView != null) {
mRecyclerView.requestLayout();
}
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is not</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertNotInLayoutOrScroll(String)
**/
public void assertInLayoutOrScroll(String message) {
if (mRecyclerView != null) {
mRecyclerView.assertInLayoutOrScroll(message);
}
}
/**
* Chooses a size from the given specs and parameters that is closest to the desired size
* and also complies with the spec.
*
* @param spec The measureSpec
* @param desired The preferred measurement
* @param min The minimum value
*
* @return A size that fits to the given specs
**/
public static int chooseSize(int spec, int desired, int min) {
//desired是padding的和
final int mode = View.MeasureSpec.getMode(spec);
final int size = View.MeasureSpec.getSize(spec);
switch (mode) {
case View.MeasureSpec.EXACTLY:
//exactly就直接放回size
return size;
case View.MeasureSpec.AT_MOST:
//match_parent返回的是最小值
return Math.min(size, Math.max(desired, min));
case View.MeasureSpec.UNSPECIFIED:
default:
//wrap
return Math.max(desired, min);
}
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertInLayoutOrScroll(String)
**/
public void assertNotInLayoutOrScroll(String message) {
if (mRecyclerView != null) {
mRecyclerView.assertNotInLayoutOrScroll(message);
}
}
/**
* Defines whether the layout should be measured by the RecyclerView or the LayoutManager
* wants to handle the layout measurements itself.
* <p>
* This method is usually called by the LayoutManager with value {@code true} if it wants
* to support WRAP_CONTENT. If you are using a public LayoutManager but want to customize
* the measurement logic, you can call this method with {@code false} and override
* {@link LayoutManager#onMeasure(int, int)} to implement your custom measurement logic.
* <p>
* AutoMeasure is a convenience mechanism for LayoutManagers to easily wrap their content or
* handle various specs provided by the RecyclerView's parent.
* It works by calling {@link LayoutManager#onLayoutChildren(Recycler, State)} during an
* {@link RecyclerView#onMeasure(int, int)} call, then calculating desired dimensions based
* on children's positions. It does this while supporting all existing animation
* capabilities of the RecyclerView.
* <p>
* AutoMeasure works as follows:
* <ol>
* <li>LayoutManager should call {@code setAutoMeasureEnabled(true)} to enable it. All of
* the framework LayoutManagers use {@code auto-measure}.</li>
* <li>When {@link RecyclerView#onMeasure(int, int)} is called, if the provided specs are
* exact, RecyclerView will only call LayoutManager's {@code onMeasure} and return without
* doing any layout calculation.</li>
* <li>If one of the layout specs is not {@code EXACT}, the RecyclerView will start the
* layout process in {@code onMeasure} call. It will process all pending Adapter updates and
* decide whether to run a predictive layout or not. If it decides to do so, it will first
* call {@link #onLayoutChildren(Recycler, State)} with {@link State#isPreLayout()} set to
* {@code true}. At this stage, {@link #getWidth()} and {@link #getHeight()} will still
* return the width and height of the RecyclerView as of the last layout calculation.
* <p>
* After handling the predictive case, RecyclerView will call
* {@link #onLayoutChildren(Recycler, State)} with {@link State#isMeasuring()} set to
* {@code true} and {@link State#isPreLayout()} set to {@code false}. The LayoutManager can
* access the measurement specs via {@link #getHeight()}, {@link #getHeightMode()},
* {@link #getWidth()} and {@link #getWidthMode()}.</li>
* <li>After the layout calculation, RecyclerView sets the measured width & height by
* calculating the bounding box for the children (+ RecyclerView's padding). The
* LayoutManagers can override {@link #setMeasuredDimension(Rect, int, int)} to choose
* different values. For instance, GridLayoutManager overrides this value to handle the case
* where if it is vertical and has 3 columns but only 2 items, it should still measure its
* width to fit 3 items, not 2.</li>
* <li>Any following on measure call to the RecyclerView will run
* {@link #onLayoutChildren(Recycler, State)} with {@link State#isMeasuring()} set to
* {@code true} and {@link State#isPreLayout()} set to {@code false}. RecyclerView will
* take care of which views are actually added / removed / moved / changed for animations so
* that the LayoutManager should not worry about them and handle each
* {@link #onLayoutChildren(Recycler, State)} call as if it is the last one.
* </li>
* <li>When measure is complete and RecyclerView's
* {@link #onLayout(boolean, int, int, int, int)} method is called, RecyclerView checks
* whether it already did layout calculations during the measure pass and if so, it re-uses
* that information. It may still decide to call {@link #onLayoutChildren(Recycler, State)}
* if the last measure spec was different from the final dimensions or adapter contents
* have changed between the measure call and the layout call.</li>
* <li>Finally, animations are calculated and run as usual.</li>
* </ol>
*
* @param enabled <code>True</code> if the Layout should be measured by the
* RecyclerView, <code>false</code> if the LayoutManager wants
* to measure itself.
*
* @see #setMeasuredDimension(Rect, int, int)
* @see #isAutoMeasureEnabled()
**/
public void setAutoMeasureEnabled(boolean enabled) {
mAutoMeasure = enabled;
}
/**
* Returns whether the LayoutManager uses the automatic measurement API or not.
*
* @return <code>True</code> if the LayoutManager is measured by the RecyclerView or
* <code>false</code> if it measures itself.
*
* @see #setAutoMeasureEnabled(boolean)
**/
public boolean isAutoMeasureEnabled() {
return mAutoMeasure;
}
/**
* Returns whether this LayoutManager supports automatic item animations.
* A LayoutManager wishing to support item animations should obey certain
* rules as outlined in {@link #onLayoutChildren(Recycler, State)}.
* The default return value is <code>false</code>, so subclasses of LayoutManager
* will not get predictive item animations by default.
*
* <p>Whether item animations are enabled in a RecyclerView is determined both
* by the return value from this method and the
* {@link RecyclerView#setItemAnimator(ItemAnimator) ItemAnimator} set on the
* RecyclerView itself. If the RecyclerView has a non-null ItemAnimator but this
* method returns false, then simple item animations will be enabled, in which
* views that are moving onto or off of the screen are simply faded in/out. If
* the RecyclerView has a non-null ItemAnimator and this method returns true,
* then there will be two calls to {@link #onLayoutChildren(Recycler, State)} to
* setup up the information needed to more intelligently predict where appearing
* and disappearing views should be animated from/to.</p>
*
* @return true if predictive item animations should be enabled, false otherwise
**/
public boolean supportsPredictiveItemAnimations() {
return false;
}
/**
* Sets whether the LayoutManager should be queried for views outside of
* its viewport while the UI thread is idle between frames.
*
* <p>If enabled, the LayoutManager will be queried for items to inflate/bind in between
* view system traversals on devices running API 21 or greater. Default value is true.</p>
*
* <p>On platforms API level 21 and higher, the UI thread is idle between passing a frame
* to RenderThread and the starting up its next frame at the next VSync pulse. By
* prefetching out of window views in this time period, delays from inflation and view
* binding are much less likely to cause jank and stuttering during scrolls and flings.</p>
*
* <p>While prefetch is enabled, it will have the side effect of expanding the effective
* size of the View cache to hold prefetched views.</p>
*
* @param enabled <code>True</code> if items should be prefetched in between traversals.
*
* @see #isItemPrefetchEnabled()
**/
public final void setItemPrefetchEnabled(boolean enabled) {
if (enabled != mItemPrefetchEnabled) {
mItemPrefetchEnabled = enabled;
mPrefetchMaxCountObserved = 0;
if (mRecyclerView != null) {
mRecyclerView.mRecycler.updateViewCacheSize();
}
}
}
/**
* Sets whether the LayoutManager should be queried for views outside of
* its viewport while the UI thread is idle between frames.
*
* @see #setItemPrefetchEnabled(boolean)
*
* @return true if item prefetch is enabled, false otherwise
**/
public final boolean isItemPrefetchEnabled() {
return mItemPrefetchEnabled;
}
/**
* Gather all positions from the LayoutManager to be prefetched, given specified momentum.
*
* <p>If item prefetch is enabled, this method is called in between traversals to gather
* which positions the LayoutManager will soon need, given upcoming movement in subsequent
* traversals.</p>
*
* <p>The LayoutManager should call {@link LayoutPrefetchRegistry#addPosition(int, int)} for
* each item to be prepared, and these positions will have their ViewHolders created and
* bound, if there is sufficient time available, in advance of being needed by a
* scroll or layout.</p>
*
* @param dx X movement component.
* @param dy Y movement component.
* @param state State of RecyclerView
* @param layoutPrefetchRegistry PrefetchRegistry to add prefetch entries into.
*
* @see #isItemPrefetchEnabled()
* @see #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)
**/
public void collectAdjacentPrefetchPositions(int dx, int dy, State state,
LayoutPrefetchRegistry layoutPrefetchRegistry) {
}
/**
* Gather all positions from the LayoutManager to be prefetched in preperation for its
* RecyclerView to come on screen, due to the movement of another, containing RecyclerView.
*
* <p>This method is only called when a RecyclerView is nested in another RecyclerView.</p>
*
* <p>If item prefetch is enabled for this LayoutManager, as well in another containing
* LayoutManager, this method is called in between draw traversals to gather
* which positions this LayoutManager will first need, once it appears on the screen.</p>
*
* <p>For example, if this LayoutManager represents a horizontally scrolling list within a
* vertically scrolling LayoutManager, this method would be called when the horizontal list
* is about to come onscreen.</p>
*
* <p>The LayoutManager should call {@link LayoutPrefetchRegistry#addPosition(int, int)} for
* each item to be prepared, and these positions will have their ViewHolders created and
* bound, if there is sufficient time available, in advance of being needed by a
* scroll or layout.</p>
*
* @param adapterItemCount number of items in the associated adapter.
* @param layoutPrefetchRegistry PrefetchRegistry to add prefetch entries into.
*
* @see #isItemPrefetchEnabled()
* @see #collectAdjacentPrefetchPositions(int, int, State, LayoutPrefetchRegistry)
**/
public void collectInitialPrefetchPositions(int adapterItemCount,
LayoutPrefetchRegistry layoutPrefetchRegistry) {
}
void dispatchAttachedToWindow(RecyclerView view) {
mIsAttachedToWindow = true;
onAttachedToWindow(view);
}
void dispatchDetachedFromWindow(RecyclerView view, Recycler recycler) {
mIsAttachedToWindow = false;
onDetachedFromWindow(view, recycler);
}
/**
* Returns whether LayoutManager is currently attached to a RecyclerView which is attached
* to a window.
*
* @return True if this LayoutManager is controlling a RecyclerView and the RecyclerView
* is attached to window.
**/
public boolean isAttachedToWindow() {
return mIsAttachedToWindow;
}
/**
* Causes the Runnable to execute on the next animation time step.
* The runnable will be run on the user interface thread.
* <p>
* Calling this method when LayoutManager is not attached to a RecyclerView has no effect.
*
* @param action The Runnable that will be executed.
*
* @see #removeCallbacks
**/
public void postOnAnimation(Runnable action) {
if (mRecyclerView != null) {
ViewCompat.postOnAnimation(mRecyclerView, action);
}
}
/**
* Removes the specified Runnable from the message queue.
* <p>
* Calling this method when LayoutManager is not attached to a RecyclerView has no effect.
*
* @param action The Runnable to remove from the message handling queue
*
* @return true if RecyclerView could ask the Handler to remove the Runnable,
* false otherwise. When the returned value is true, the Runnable
* may or may not have been actually removed from the message queue
* (for instance, if the Runnable was not in the queue already.)
*
* @see #postOnAnimation
**/
public boolean removeCallbacks(Runnable action) {
if (mRecyclerView != null) {
return mRecyclerView.removeCallbacks(action);
}
return false;
}
/**
* Called when this LayoutManager is both attached to a RecyclerView and that RecyclerView
* is attached to a window.
* <p>
* If the RecyclerView is re-attached with the same LayoutManager and Adapter, it may not
* call {@link #onLayoutChildren(Recycler, State)} if nothing has changed and a layout was
* not requested on the RecyclerView while it was detached.
* <p>
* Subclass implementations should always call through to the superclass implementation.
*
* @param view The RecyclerView this LayoutManager is bound to
*
* @see #onDetachedFromWindow(RecyclerView, Recycler)
**/
@CallSuper
public void onAttachedToWindow(RecyclerView view) {
}
/**
* @deprecated
* override {@link #onDetachedFromWindow(RecyclerView, Recycler)}
**/
@Deprecated
public void onDetachedFromWindow(RecyclerView view) {
}
/**
* Called when this LayoutManager is detached from its parent RecyclerView or when
* its parent RecyclerView is detached from its window.
* <p>
* LayoutManager should clear all of its View references as another LayoutManager might be
* assigned to the RecyclerView.
* <p>
* If the RecyclerView is re-attached with the same LayoutManager and Adapter, it may not
* call {@link #onLayoutChildren(Recycler, State)} if nothing has changed and a layout was
* not requested on the RecyclerView while it was detached.
* <p>
* If your LayoutManager has View references that it cleans in on-detach, it should also
* call {@link RecyclerView#requestLayout()} to ensure that it is re-laid out when
* RecyclerView is re-attached.
* <p>
* Subclass implementations should always call through to the superclass implementation.
*
* @param view The RecyclerView this LayoutManager is bound to
* @param recycler The recycler to use if you prefer to recycle your children instead of
* keeping them around.
*
* @see #onAttachedToWindow(RecyclerView)
**/
@CallSuper
public void onDetachedFromWindow(RecyclerView view, Recycler recycler) {
onDetachedFromWindow(view);
}
/**
* Check if the RecyclerView is configured to clip child views to its padding.
*
* @return true if this RecyclerView clips children to its padding, false otherwise
**/
public boolean getClipToPadding() {
return mRecyclerView != null && mRecyclerView.mClipToPadding;
}
/**
* Lay out all relevant child views from the given adapter.
*
* The LayoutManager is in charge of the behavior of item animations. By default,
* RecyclerView has a non-null {@link #getItemAnimator() ItemAnimator}, and simple
* item animations are enabled. This means that add/remove operations on the
* adapter will result in animations to add new or appearing items, removed or
* disappearing items, and moved items. If a LayoutManager returns false from
* {@link #supportsPredictiveItemAnimations()}, which is the default, and runs a
* normal layout operation during {@link #onLayoutChildren(Recycler, State)}, the
* RecyclerView will have enough information to run those animations in a simple
* way. For example, the default ItemAnimator, {@link DefaultItemAnimator}, will
* simply fade views in and out, whether they are actually added/removed or whether
* they are moved on or off the screen due to other add/remove operations.
*
* <p>A LayoutManager wanting a better item animation experience, where items can be
* animated onto and off of the screen according to where the items exist when they
* are not on screen, then the LayoutManager should return true from
* {@link #supportsPredictiveItemAnimations()} and add additional logic to
* {@link #onLayoutChildren(Recycler, State)}. Supporting predictive animations
* means that {@link #onLayoutChildren(Recycler, State)} will be called twice;
* once as a "pre" layout step to determine where items would have been prior to
* a real layout, and again to do the "real" layout. In the pre-layout phase,
* items will remember their pre-layout positions to allow them to be laid out
* appropriately. Also, {@link LayoutParams#isItemRemoved() removed} items will
* be returned from the scrap to help determine correct placement of other items.
* These removed items should not be added to the child list, but should be used
* to help calculate correct positioning of other views, including views that
* were not previously onscreen (referred to as APPEARING views), but whose
* pre-layout offscreen position can be determined given the extra
* information about the pre-layout removed views.</p>
*
* <p>The second layout pass is the real layout in which only non-removed views
* will be used. The only additional requirement during this pass is, if
* {@link #supportsPredictiveItemAnimations()} returns true, to note which
* views exist in the child list prior to layout and which are not there after
* layout (referred to as DISAPPEARING views), and to position/layout those views
* appropriately, without regard to the actual bounds of the RecyclerView. This allows
* the animation system to know the location to which to animate these disappearing
* views.</p>
*
* <p>The default LayoutManager implementations for RecyclerView handle all of these
* requirements for animations already. Clients of RecyclerView can either use one
* of these layout managers directly or look at their implementations of
* onLayoutChildren() to see how they account for the APPEARING and
* DISAPPEARING views.</p>
*
* @param recycler Recycler to use for fetching potentially cached views for a
* position
* @param state Transient state of RecyclerView
**/
public void onLayoutChildren(Recycler recycler, State state) {
Log.e(TAG, "You must override onLayoutChildren(Recycler recycler, State state) ");
}
/**
* Called after a full layout calculation is finished. The layout calculation may include
* multiple {@link #onLayoutChildren(Recycler, State)} calls due to animations or
* layout measurement but it will include only one {@link #onLayoutCompleted(State)} call.
* This method will be called at the end of {@link View#layout(int, int, int, int)} call.
* <p>
* This is a good place for the LayoutManager to do some cleanup like pending scroll
* position, saved state etc.
*
* @param state Transient state of RecyclerView
**/
public void onLayoutCompleted(State state) {
}
/**
* Create a default <code>LayoutParams</code> object for a child of the RecyclerView.
*
* <p>LayoutManagers will often want to use a custom <code>LayoutParams</code> type
* to store extra information specific to the layout. Client code should subclass
* {@link RecyclerView.LayoutParams} for this purpose.</p>
*
* <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
* you must also override
* {@link #checkLayoutParams(LayoutParams)},
* {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
* {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
*
* @return A new LayoutParams for a child view
**/
public abstract LayoutParams generateDefaultLayoutParams();
/**
* Determines the validity of the supplied LayoutParams object.
*
* <p>This should check to make sure that the object is of the correct type
* and all values are within acceptable ranges. The default implementation
* returns <code>true</code> for non-null params.</p>
*
* @param lp LayoutParams object to check
* @return true if this LayoutParams object is valid, false otherwise
**/
public boolean checkLayoutParams(LayoutParams lp) {
return lp != null;
}
/**
* Create a LayoutParams object suitable for this LayoutManager, copying relevant
* values from the supplied LayoutParams object if possible.
*
* <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
* you must also override
* {@link #checkLayoutParams(LayoutParams)},
* {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
* {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
*
* @param lp Source LayoutParams object to copy values from
* @return a new LayoutParams object
**/
public LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
if (lp instanceof LayoutParams) {
return new LayoutParams((LayoutParams) lp);
} else if (lp instanceof MarginLayoutParams) {
return new LayoutParams((MarginLayoutParams) lp);
} else {
return new LayoutParams(lp);
}
}
/**
* Create a LayoutParams object suitable for this LayoutManager from
* an inflated layout resource.
*
* <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
* you must also override
* {@link #checkLayoutParams(LayoutParams)},
* {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
* {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
*
* @param c Context for obtaining styled attributes
* @param attrs AttributeSet describing the supplied arguments
* @return a new LayoutParams object
**/
public LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
return new LayoutParams(c, attrs);
}
/**
* Scroll horizontally by dx pixels in screen coordinates and return the distance traveled.
* The default implementation does nothing and returns 0.
*
* @param dx distance to scroll by in pixels. X increases as scroll position
* approaches the right.
* @param recycler Recycler to use for fetching potentially cached views for a
* position
* @param state Transient state of RecyclerView
* @return The actual distance scrolled. The return value will be negative if dx was
* negative and scrolling proceeeded in that direction.
* <code>Math.abs(result)</code> may be less than dx if a boundary was reached.
**/
public int scrollHorizontallyBy(int dx, Recycler recycler, State state) {
return 0;
}
/**
* Scroll vertically by dy pixels in screen coordinates and return the distance traveled.
* The default implementation does nothing and returns 0.
*
* @param dy distance to scroll in pixels. Y increases as scroll position
* approaches the bottom.
* @param recycler Recycler to use for fetching potentially cached views for a
* position
* @param state Transient state of RecyclerView
* @return The actual distance scrolled. The return value will be negative if dy was
* negative and scrolling proceeeded in that direction.
* <code>Math.abs(result)</code> may be less than dy if a boundary was reached.
**/
public int scrollVerticallyBy(int dy, Recycler recycler, State state) {
return 0;
}
/**
* Query if horizontal scrolling is currently supported. The default implementation
* returns false.
*
* @return True if this LayoutManager can scroll the current contents horizontally
**/
public boolean canScrollHorizontally() {
return false;
}
/**
* Query if vertical scrolling is currently supported. The default implementation
* returns false.
*
* @return True if this LayoutManager can scroll the current contents vertically
**/
public boolean canScrollVertically() {
return false;
}
/**
* Scroll to the specified adapter position.
*
* Actual position of the item on the screen depends on the LayoutManager implementation.
* @param position Scroll to this adapter position.
**/
public void scrollToPosition(int position) {
if (DEBUG) {
Log.e(TAG, "You MUST implement scrollToPosition. It will soon become abstract");
}
}
/**
* <p>Smooth scroll to the specified adapter position.</p>
* <p>To support smooth scrolling, override this method, create your {@link SmoothScroller}
* instance and call {@link #startSmoothScroll(SmoothScroller)}.
* </p>
* @param recyclerView The RecyclerView to which this layout manager is attached
* @param state Current State of RecyclerView
* @param position Scroll to this adapter position.
**/
public void smoothScrollToPosition(RecyclerView recyclerView, State state,
int position) {
Log.e(TAG, "You must override smoothScrollToPosition to support smooth scrolling");
}
/**
* <p>Starts a smooth scroll using the provided SmoothScroller.</p>
* <p>Calling this method will cancel any previous smooth scroll request.</p>
* @param smoothScroller Instance which defines how smooth scroll should be animated
**/
public void startSmoothScroll(SmoothScroller smoothScroller) {
if (mSmoothScroller != null && smoothScroller != mSmoothScroller
&& mSmoothScroller.isRunning()) {
mSmoothScroller.stop();
}
mSmoothScroller = smoothScroller;
mSmoothScroller.start(mRecyclerView, this);
}
/**
* @return true if RecycylerView is currently in the state of smooth scrolling.
**/
public boolean isSmoothScrolling() {
return mSmoothScroller != null && mSmoothScroller.isRunning();
}
/**
* Returns the resolved layout direction for this RecyclerView.
*
* @return {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_RTL} if the layout
* direction is RTL or returns
* {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_LTR} if the layout direction
* is not RTL.
**/
public int getLayoutDirection() {
return ViewCompat.getLayoutDirection(mRecyclerView);
}
/**
* Ends all animations on the view created by the {@link ItemAnimator}.
*
* @param view The View for which the animations should be ended.
* @see RecyclerView.ItemAnimator#endAnimations()
**/
public void endAnimation(View view) {
if (mRecyclerView.mItemAnimator != null) {
mRecyclerView.mItemAnimator.endAnimation(getChildViewHolderInt(view));
}
}
/**
* To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view
* to the layout that is known to be going away, either because it has been
* {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the
* visible portion of the container but is being laid out in order to inform RecyclerView
* in how to animate the item out of view.
* <p>
* Views added via this method are going to be invisible to LayoutManager after the
* dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)}
* or won't be included in {@link #getChildCount()} method.
*
* @param child View to add and then remove with animation.
**/
public void addDisappearingView(View child) {
addDisappearingView(child, -1);
}
/**
* To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view
* to the layout that is known to be going away, either because it has been
* {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the
* visible portion of the container but is being laid out in order to inform RecyclerView
* in how to animate the item out of view.
* <p>
* Views added via this method are going to be invisible to LayoutManager after the
* dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)}
* or won't be included in {@link #getChildCount()} method.
*
* @param child View to add and then remove with animation.
* @param index Index of the view.
**/
public void addDisappearingView(View child, int index) {
addViewInt(child, index, true);
}
/**
* Add a view to the currently attached RecyclerView if needed. LayoutManagers should
* use this method to add views obtained from a {@link Recycler} using
* {@link Recycler#getViewForPosition(int)}.
*
* @param child View to add
**/
public void addView(View child) {
addView(child, -1);
}
/**
* Add a view to the currently attached RecyclerView if needed. LayoutManagers should
* use this method to add views obtained from a {@link Recycler} using
* {@link Recycler#getViewForPosition(int)}.
*
* @param child View to add
* @param index Index to add child at
**/
public void addView(View child, int index) {
addViewInt(child, index, false);
}
private void addViewInt(View child, int index, boolean disappearing) {
final ViewHolder holder = getChildViewHolderInt(child);
if (disappearing || holder.isRemoved()) {
// these views will be hidden at the end of the layout pass.
mRecyclerView.mViewInfoStore.addToDisappearedInLayout(holder);
} else {
// This may look like unnecessary but may happen if layout manager supports
// predictive layouts and adapter removed then re-added the same item.
// In this case, added version will be visible in the post layout (because add is
// deferred) but RV will still bind it to the same View.
// So if a View re-appears in post layout pass, remove it from disappearing list.
mRecyclerView.mViewInfoStore.removeFromDisappearedInLayout(holder);
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
//第一次没有进入scrap,后面从scrap拿到的会再remove
if (holder.wasReturnedFromScrap() || holder.isScrap()) {
if (holder.isScrap()) {
holder.unScrap();
} else {
holder.clearReturnedFromScrapFlag();
}
mChildHelper.attachViewToParent(child, index, child.getLayoutParams(), false);
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchFinishTemporaryDetach(child);
}
} else if (child.getParent() == mRecyclerView) { // it was not a scrap but a valid child
// ensure in correct position
int currentIndex = mChildHelper.indexOfChild(child);
if (index == -1) {
index = mChildHelper.getChildCount();
}
if (currentIndex == -1) {
throw new IllegalStateException("Added View has RecyclerView as parent but"
+ " view is not a real child. Unfiltered index:"
+ mRecyclerView.indexOfChild(child) + mRecyclerView.exceptionLabel());
}
if (currentIndex != index) {
mRecyclerView.mLayout.moveView(currentIndex, index);
}
} else {
//hidden=false,所以不会放入hiddenViews中
mChildHelper.addView(child, index, false);
lp.mInsetsDirty = true;
if (mSmoothScroller != null && mSmoothScroller.isRunning()) {
mSmoothScroller.onChildAttachedToWindow(child);
}
}
if (lp.mPendingInvalidate) {
if (DEBUG) {
Log.d(TAG, "consuming pending invalidate on child " + lp.mViewHolder);
}
holder.itemView.invalidate();
lp.mPendingInvalidate = false;
}
}
/**
* Remove a view from the currently attached RecyclerView if needed. LayoutManagers should
* use this method to completely remove a child view that is no longer needed.
* LayoutManagers should strongly consider recycling removed views using
* {@link Recycler#recycleView(android.view.View)}.
*
* @param child View to remove
**/
public void removeView(View child) {
mChildHelper.removeView(child);
}
/**
* Remove a view from the currently attached RecyclerView if needed. LayoutManagers should
* use this method to completely remove a child view that is no longer needed.
* LayoutManagers should strongly consider recycling removed views using
* {@link Recycler#recycleView(android.view.View)}.
*
* @param index Index of the child view to remove
**/
public void removeViewAt(int index) {
final View child = getChildAt(index);
if (child != null) {
mChildHelper.removeViewAt(index);
}
}
/**
* Remove all views from the currently attached RecyclerView. This will not recycle
* any of the affected views; the LayoutManager is responsible for doing so if desired.
**/
public void removeAllViews() {
// Only remove non-animating views
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
mChildHelper.removeViewAt(i);
}
}
/**
* Returns offset of the RecyclerView's text baseline from the its top boundary.
*
* @return The offset of the RecyclerView's text baseline from the its top boundary; -1 if
* there is no baseline.
**/
public int getBaseline() {
return -1;
}
/**
* Returns the adapter position of the item represented by the given View. This does not
* contain any adapter changes that might have happened after the last layout.
*
* @param view The view to query
* @return The adapter position of the item which is rendered by this View.
**/
public int getPosition(View view) {
return ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
}
/**
* Returns the View type defined by the adapter.
*
* @param view The view to query
* @return The type of the view assigned by the adapter.
**/
public int getItemViewType(View view) {
return getChildViewHolderInt(view).getItemViewType();
}
/**
* Traverses the ancestors of the given view and returns the item view that contains it
* and also a direct child of the LayoutManager.
* <p>
* Note that this method may return null if the view is a child of the RecyclerView but
* not a child of the LayoutManager (e.g. running a disappear animation).
*
* @param view The view that is a descendant of the LayoutManager.
*
* @return The direct child of the LayoutManager which contains the given view or null if
* the provided view is not a descendant of this LayoutManager.
*
* @see RecyclerView#getChildViewHolder(View)
* @see RecyclerView#findContainingViewHolder(View)
**/
@Nullable
public View findContainingItemView(View view) {
if (mRecyclerView == null) {
return null;
}
View found = mRecyclerView.findContainingItemView(view);
if (found == null) {
return null;
}
if (mChildHelper.isHidden(found)) {
return null;
}
return found;
}
/**
* Finds the view which represents the given adapter position.
* <p>
* This method traverses each child since it has no information about child order.
* Override this method to improve performance if your LayoutManager keeps data about
* child views.
* <p>
* If a view is ignored via {@link #ignoreView(View)}, it is also ignored by this method.
*
* @param position Position of the item in adapter
* @return The child view that represents the given position or null if the position is not
* laid out
**/
public View findViewByPosition(int position) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
ViewHolder vh = getChildViewHolderInt(child);
if (vh == null) {
continue;
}
if (vh.getLayoutPosition() == position && !vh.shouldIgnore()
&& (mRecyclerView.mState.isPreLayout() || !vh.isRemoved())) {
return child;
}
}
return null;
}
/**
* Temporarily detach a child view.
*
* <p>LayoutManagers may want to perform a lightweight detach operation to rearrange
* views currently attached to the RecyclerView. Generally LayoutManager implementations
* will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}
* so that the detached view may be rebound and reused.</p>
*
* <p>If a LayoutManager uses this method to detach a view, it <em>must</em>
* {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach}
* or {@link #removeDetachedView(android.view.View) fully remove} the detached view
* before the LayoutManager entry point method called by RecyclerView returns.</p>
*
* @param child Child to detach
**/
public void detachView(View child) {
final int ind = mChildHelper.indexOfChild(child);
if (ind >= 0) {
detachViewInternal(ind, child);
}
}
/**
* Temporarily detach a child view.
*
* <p>LayoutManagers may want to perform a lightweight detach operation to rearrange
* views currently attached to the RecyclerView. Generally LayoutManager implementations
* will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}
* so that the detached view may be rebound and reused.</p>
*
* <p>If a LayoutManager uses this method to detach a view, it <em>must</em>
* {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach}
* or {@link #removeDetachedView(android.view.View) fully remove} the detached view
* before the LayoutManager entry point method called by RecyclerView returns.</p>
*
* @param index Index of the child to detach
**/
public void detachViewAt(int index) {
detachViewInternal(index, getChildAt(index));
}
private void detachViewInternal(int index, View view) {
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchStartTemporaryDetach(view);
}
mChildHelper.detachViewFromParent(index);
}
/**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
* @param index Intended child index for child
* @param lp LayoutParams for child
**/
public void attachView(View child, int index, LayoutParams lp) {
ViewHolder vh = getChildViewHolderInt(child);
if (vh.isRemoved()) {
mRecyclerView.mViewInfoStore.addToDisappearedInLayout(vh);
} else {
mRecyclerView.mViewInfoStore.removeFromDisappearedInLayout(vh);
}
mChildHelper.attachViewToParent(child, index, lp, vh.isRemoved());
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchFinishTemporaryDetach(child);
}
}
/**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
* @param index Intended child index for child
**/
public void attachView(View child, int index) {
attachView(child, index, (LayoutParams) child.getLayoutParams());
}
/**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
**/
public void attachView(View child) {
attachView(child, -1);
}
/**
* Finish removing a view that was previously temporarily
* {@link #detachView(android.view.View) detached}.
*
* @param child Detached child to remove
**/
public void removeDetachedView(View child) {
mRecyclerView.removeDetachedView(child, false);
}
/**
* Moves a View from one position to another.
*
* @param fromIndex The View's initial index
* @param toIndex The View's target index
**/
public void moveView(int fromIndex, int toIndex) {
View view = getChildAt(fromIndex);
if (view == null) {
throw new IllegalArgumentException("Cannot move a child from non-existing index:"
+ fromIndex + mRecyclerView.toString());
}
detachViewAt(fromIndex);
attachView(view, toIndex);
}
/**
* Detach a child view and add it to a {@link Recycler Recycler's} scrap heap.
*
* <p>Scrapping a view allows it to be rebound and reused to show updated or
* different data.</p>
*
* @param child Child to detach and scrap
* @param recycler Recycler to deposit the new scrap view into
**/
public void detachAndScrapView(View child, Recycler recycler) {
int index = mChildHelper.indexOfChild(child);
scrapOrRecycleView(recycler, index, child);
}
/**
* Detach a child view and add it to a {@link Recycler Recycler's} scrap heap.
*
* <p>Scrapping a view allows it to be rebound and reused to show updated or
* different data.</p>
*
* @param index Index of child to detach and scrap
* @param recycler Recycler to deposit the new scrap view into
**/
public void detachAndScrapViewAt(int index, Recycler recycler) {
final View child = getChildAt(index);
scrapOrRecycleView(recycler, index, child);
}
/**
* Remove a child view and recycle it using the given Recycler.
*
* @param child Child to remove and recycle
* @param recycler Recycler to use to recycle child
**/
public void removeAndRecycleView(View child, Recycler recycler) {
removeView(child);
recycler.recycleView(child);
}
/**
* Remove a child view and recycle it using the given Recycler.
*
* @param index Index of child to remove and recycle
* @param recycler Recycler to use to recycle child
**/
public void removeAndRecycleViewAt(int index, Recycler recycler) {
final View view = getChildAt(index);
//移除回调
removeViewAt(index);
//缓存
recycler.recycleView(view);
}
/**
* Return the current number of child views attached to the parent RecyclerView.
* This does not include child views that were temporarily detached and/or scrapped.
*
* @return Number of attached children
**/
public int getChildCount() {
return mChildHelper != null ? mChildHelper.getChildCount() : 0;
}
/**
* Return the child view at the given index
* @param index Index of child to return
* @return Child view at index
**/
public View getChildAt(int index) {
return mChildHelper != null ? mChildHelper.getChildAt(index) : null;
}
/**
* Return the width measurement spec mode of the RecyclerView.
* <p>
* This value is set only if the LayoutManager opts into the auto measure api via
* {@link #setAutoMeasureEnabled(boolean)}.
* <p>
* When RecyclerView is running a layout, this value is always set to
* {@link View.MeasureSpec#EXACTLY} even if it was measured with a different spec mode.
*
* @return Width measure spec mode.
*
* @see View.MeasureSpec#getMode(int)
* @see View#onMeasure(int, int)
**/
public int getWidthMode() {
return mWidthMode;
}
/**
* Return the height measurement spec mode of the RecyclerView.
* <p>
* This value is set only if the LayoutManager opts into the auto measure api via
* {@link #setAutoMeasureEnabled(boolean)}.
* <p>
* When RecyclerView is running a layout, this value is always set to
* {@link View.MeasureSpec#EXACTLY} even if it was measured with a different spec mode.
*
* @return Height measure spec mode.
*
* @see View.MeasureSpec#getMode(int)
* @see View#onMeasure(int, int)
**/
public int getHeightMode() {
return mHeightMode;
}
/**
* Return the width of the parent RecyclerView
*
* @return Width in pixels
**/
public int getWidth() {
return mWidth;
}
/**
* Return the height of the parent RecyclerView
*
* @return Height in pixels
**/
public int getHeight() {
return mHeight;
}
/**
* Return the left padding of the parent RecyclerView
*
* @return Padding in pixels
**/
public int getPaddingLeft() {
return mRecyclerView != null ? mRecyclerView.getPaddingLeft() : 0;
}
/**
* Return the top padding of the parent RecyclerView
*
* @return Padding in pixels
**/
public int getPaddingTop() {
return mRecyclerView != null ? mRecyclerView.getPaddingTop() : 0;
}
/**
* Return the right padding of the parent RecyclerView
*
* @return Padding in pixels
**/
public int getPaddingRight() {
return mRecyclerView != null ? mRecyclerView.getPaddingRight() : 0;
}
/**
* Return the bottom padding of the parent RecyclerView
*
* @return Padding in pixels
**/
public int getPaddingBottom() {
return mRecyclerView != null ? mRecyclerView.getPaddingBottom() : 0;
}
/**
* Return the start padding of the parent RecyclerView
*
* @return Padding in pixels
**/
public int getPaddingStart() {
return mRecyclerView != null ? ViewCompat.getPaddingStart(mRecyclerView) : 0;
}
/**
* Return the end padding of the parent RecyclerView
*
* @return Padding in pixels
**/
public int getPaddingEnd() {
return mRecyclerView != null ? ViewCompat.getPaddingEnd(mRecyclerView) : 0;
}
/**
* Returns true if the RecyclerView this LayoutManager is bound to has focus.
*
* @return True if the RecyclerView has focus, false otherwise.
* @see View#isFocused()
**/
public boolean isFocused() {
return mRecyclerView != null && mRecyclerView.isFocused();
}
/**
* Returns true if the RecyclerView this LayoutManager is bound to has or contains focus.
*
* @return true if the RecyclerView has or contains focus
* @see View#hasFocus()
**/
public boolean hasFocus() {
return mRecyclerView != null && mRecyclerView.hasFocus();
}
/**
* Returns the item View which has or contains focus.
*
* @return A direct child of RecyclerView which has focus or contains the focused child.
**/
public View getFocusedChild() {
if (mRecyclerView == null) {
return null;
}
final View focused = mRecyclerView.getFocusedChild();
if (focused == null || mChildHelper.isHidden(focused)) {
return null;
}
return focused;
}
/**
* Returns the number of items in the adapter bound to the parent RecyclerView.
* <p>
* Note that this number is not necessarily equal to
* {@link State#getItemCount() State#getItemCount()}. In methods where {@link State} is
* available, you should use {@link State#getItemCount() State#getItemCount()} instead.
* For more details, check the documentation for
* {@link State#getItemCount() State#getItemCount()}.
*
* @return The number of items in the bound adapter
* @see State#getItemCount()
**/
public int getItemCount() {
final Adapter a = mRecyclerView != null ? mRecyclerView.getAdapter() : null;
return a != null ? a.getItemCount() : 0;
}
/**
* Offset all child views attached to the parent RecyclerView by dx pixels along
* the horizontal axis.
*
* @param dx Pixels to offset by
**/
public void offsetChildrenHorizontal(int dx) {
if (mRecyclerView != null) {
mRecyclerView.offsetChildrenHorizontal(dx);
}
}
/**
* Offset all child views attached to the parent RecyclerView by dy pixels along
* the vertical axis.
*
* @param dy Pixels to offset by
**/
public void offsetChildrenVertical(int dy) {
if (mRecyclerView != null) {
mRecyclerView.offsetChildrenVertical(dy);
}
}
/**
* Flags a view so that it will not be scrapped or recycled.
* <p>
* Scope of ignoring a child is strictly restricted to position tracking, scrapping and
* recyling. Methods like {@link #removeAndRecycleAllViews(Recycler)} will ignore the child
* whereas {@link #removeAllViews()} or {@link #offsetChildrenHorizontal(int)} will not
* ignore the child.
* <p>
* Before this child can be recycled again, you have to call
* {@link #stopIgnoringView(View)}.
* <p>
* You can call this method only if your LayoutManger is in onLayout or onScroll callback.
*
* @param view View to ignore.
* @see #stopIgnoringView(View)
**/
public void ignoreView(View view) {
if (view.getParent() != mRecyclerView || mRecyclerView.indexOfChild(view) == -1) {
// checking this because calling this method on a recycled or detached view may
// cause loss of state.
throw new IllegalArgumentException("View should be fully attached to be ignored"
+ mRecyclerView.exceptionLabel());
}
final ViewHolder vh = getChildViewHolderInt(view);
vh.addFlags(ViewHolder.FLAG_IGNORE);
mRecyclerView.mViewInfoStore.removeViewHolder(vh);
}
/**
* View can be scrapped and recycled again.
* <p>
* Note that calling this method removes all information in the view holder.
* <p>
* You can call this method only if your LayoutManger is in onLayout or onScroll callback.
*
* @param view View to ignore.
**/
public void stopIgnoringView(View view) {
final ViewHolder vh = getChildViewHolderInt(view);
vh.stopIgnoring();
vh.resetInternal();
vh.addFlags(ViewHolder.FLAG_INVALID);
}
/**
* Temporarily detach and scrap all currently attached child views. Views will be scrapped
* into the given Recycler. The Recycler may prefer to reuse scrap views before
* other views that were previously recycled.
*
* @param recycler Recycler to scrap views into
**/
public void detachAndScrapAttachedViews(Recycler recycler) {
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
final View v = getChildAt(i);
scrapOrRecycleView(recycler, i, v);
}
}
/**
* 1.Recycle操作对应的是removeView, View被remove后调用Recycler的recycleViewHolderInternal回收其ViewHolder
2.Scrap操作对应的是detachView,View被detach后调用Reccyler的scrapView暂存其ViewHolder
* @param recycler
* @param index
* @param view
*/
private void scrapOrRecycleView(Recycler recycler, int index, View view) {
final ViewHolder viewHolder = getChildViewHolderInt(view);
if (viewHolder.shouldIgnore()) {
if (DEBUG) {
Log.d(TAG, "ignoring view " + viewHolder);
}
return;
}
if (viewHolder.isInvalid() && !viewHolder.isRemoved()
&& !mRecyclerView.mAdapter.hasStableIds()) {
//注意这里是remove
removeViewAt(index);
//往cacheview和pool中
recycler.recycleViewHolderInternal(viewHolder);
} else {
//注意这里是detach
detachViewAt(index);
//存到scrap中
recycler.scrapView(view);
mRecyclerView.mViewInfoStore.onViewDetached(viewHolder);
}
}
/**
* Recycles the scrapped views.
* <p>
* When a view is detached and removed, it does not trigger a ViewGroup invalidate. This is
* the expected behavior if scrapped views are used for animations. Otherwise, we need to
* call remove and invalidate RecyclerView to ensure UI update.
*
* @param recycler Recycler
**/
void removeAndRecycleScrapInt(Recycler recycler) {
final int scrapCount = recycler.getScrapCount();
// Loop backward, recycler might be changed by removeDetachedView()
for (int i = scrapCount - 1; i >= 0; i--) {
final View scrap = recycler.getScrapViewAt(i);
final ViewHolder vh = getChildViewHolderInt(scrap);
if (vh.shouldIgnore()) {
continue;
}
// If the scrap view is animating, we need to cancel them first. If we cancel it
// here, ItemAnimator callback may recycle it which will cause double recycling.
// To avoid this, we mark it as not recycleable before calling the item animator.
// Since removeDetachedView calls a user API, a common mistake (ending animations on
// the view) may recycle it too, so we guard it before we call user APIs.
vh.setIsRecyclable(false);
if (vh.isTmpDetached()) {
mRecyclerView.removeDetachedView(scrap, false);
}
if (mRecyclerView.mItemAnimator != null) {
mRecyclerView.mItemAnimator.endAnimation(vh);
}
vh.setIsRecyclable(true);
recycler.quickRecycleScrapView(scrap);
}
recycler.clearScrap();
if (scrapCount > 0) {
mRecyclerView.invalidate();
}
}
/**
* Measure a child view using standard measurement policy, taking the padding
* of the parent RecyclerView and any added item decorations into account.
*
* <p>If the RecyclerView can be scrolled in either dimension the caller may
* pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
*
* @param child Child view to measure
* @param widthUsed Width in pixels currently consumed by other views, if relevant
* @param heightUsed Height in pixels currently consumed by other views, if relevant
**/
public void measureChild(View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,
canScrollVertically());
if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
child.measure(widthSpec, heightSpec);
}
}
/**
* RecyclerView internally does its own View measurement caching which should help with
* WRAP_CONTENT.
* <p>
* Use this method if the View is already measured once in this layout pass.
**/
boolean shouldReMeasureChild(View child, int widthSpec, int heightSpec, LayoutParams lp) {
return !mMeasurementCacheEnabled
|| !isMeasurementUpToDate(child.getMeasuredWidth(), widthSpec, lp.width)
|| !isMeasurementUpToDate(child.getMeasuredHeight(), heightSpec, lp.height);
}
// we may consider making this public
/**
* RecyclerView internally does its own View measurement caching which should help with
* WRAP_CONTENT.
* <p>
* Use this method if the View is not yet measured and you need to decide whether to
* measure this View or not.
**/
boolean shouldMeasureChild(View child, int widthSpec, int heightSpec, LayoutParams lp) {
return child.isLayoutRequested()
|| !mMeasurementCacheEnabled
|| !isMeasurementUpToDate(child.getWidth(), widthSpec, lp.width)
|| !isMeasurementUpToDate(child.getHeight(), heightSpec, lp.height);
}
/**
* In addition to the View Framework's measurement cache, RecyclerView uses its own
* additional measurement cache for its children to avoid re-measuring them when not
* necessary. It is on by default but it can be turned off via
* {@link #setMeasurementCacheEnabled(boolean)}.
*
* @return True if measurement cache is enabled, false otherwise.
*
* @see #setMeasurementCacheEnabled(boolean)
**/
public boolean isMeasurementCacheEnabled() {
return mMeasurementCacheEnabled;
}
/**
* Sets whether RecyclerView should use its own measurement cache for the children. This is
* a more aggressive cache than the framework uses.
*
* @param measurementCacheEnabled True to enable the measurement cache, false otherwise.
*
* @see #isMeasurementCacheEnabled()
**/
public void setMeasurementCacheEnabled(boolean measurementCacheEnabled) {
mMeasurementCacheEnabled = measurementCacheEnabled;
}
private static boolean isMeasurementUpToDate(int childSize, int spec, int dimension) {
final int specMode = MeasureSpec.getMode(spec);
final int specSize = MeasureSpec.getSize(spec);
if (dimension > 0 && childSize != dimension) {
return false;
}
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
return true;
case MeasureSpec.AT_MOST:
return specSize >= childSize;
case MeasureSpec.EXACTLY:
return specSize == childSize;
}
return false;
}
/**
* Measure a child view using standard measurement policy, taking the padding
* of the parent RecyclerView, any added item decorations and the child margins
* into account.
*
* <p>If the RecyclerView can be scrolled in either dimension the caller may
* pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
*
* @param child Child view to measure
* @param widthUsed Width in pixels currently consumed by other views, if relevant
* @param heightUsed Height in pixels currently consumed by other views, if relevant
**/
public void measureChildWithMargins(View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
//设置分割线中的回调方法
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
getPaddingLeft() + getPaddingRight()
+ lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
getPaddingTop() + getPaddingBottom()
+ lp.topMargin + lp.bottomMargin + heightUsed, lp.height,
canScrollVertically());
if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
child.measure(widthSpec, heightSpec);
}
}
/**
* Calculate a MeasureSpec value for measuring a child view in one dimension.
*
* @param parentSize Size of the parent view where the child will be placed
* @param padding Total space currently consumed by other elements of the parent
* @param childDimension Desired size of the child view, or MATCH_PARENT/WRAP_CONTENT.
* Generally obtained from the child view's LayoutParams
* @param canScroll true if the parent RecyclerView can scroll in this dimension
*
* @return a MeasureSpec value for the child view
* @deprecated use {@link #getChildMeasureSpec(int, int, int, int, boolean)}
**/
@Deprecated
public static int getChildMeasureSpec(int parentSize, int padding, int childDimension,
boolean canScroll) {
int size = Math.max(0, parentSize - padding);
int resultSize = 0;
int resultMode = 0;
if (canScroll) {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else {
// MATCH_PARENT can't be applied since we can scroll in this dimension, wrap
// instead using UNSPECIFIED.
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
}
} else {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = size;
// TODO this should be my spec.
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
/**
* Calculate a MeasureSpec value for measuring a child view in one dimension.
*
* @param parentSize Size of the parent view where the child will be placed
* @param parentMode The measurement spec mode of the parent
* @param padding Total space currently consumed by other elements of parent
* @param childDimension Desired size of the child view, or MATCH_PARENT/WRAP_CONTENT.
* Generally obtained from the child view's LayoutParams
* @param canScroll true if the parent RecyclerView can scroll in this dimension
*
* @return a MeasureSpec value for the child view
**/
public static int getChildMeasureSpec(int parentSize, int parentMode, int padding,
int childDimension, boolean canScroll) {
int size = Math.max(0, parentSize - padding);
int resultSize = 0;
int resultMode = 0;
if (canScroll) {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
switch (parentMode) {
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
resultSize = size;
resultMode = parentMode;
break;
case MeasureSpec.UNSPECIFIED:
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
break;
}
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
}
} else {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
resultSize = size;
resultMode = parentMode;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
if (parentMode == MeasureSpec.AT_MOST || parentMode == MeasureSpec.EXACTLY) {
resultMode = MeasureSpec.AT_MOST;
} else {
resultMode = MeasureSpec.UNSPECIFIED;
}
}
}
//noinspection WrongConstant
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
/**
* Returns the measured width of the given child, plus the additional size of
* any insets applied by {@link ItemDecoration ItemDecorations}.
*
* @param child Child view to query
* @return child's measured width plus <code>ItemDecoration</code> insets
*
* @see View#getMeasuredWidth()
**/
public int getDecoratedMeasuredWidth(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredWidth() + insets.left + insets.right;
}
/**
* Returns the measured height of the given child, plus the additional size of
* any insets applied by {@link ItemDecoration ItemDecorations}.
*
* @param child Child view to query
* @return child's measured height plus <code>ItemDecoration</code> insets
*
* @see View#getMeasuredHeight()
**/
public int getDecoratedMeasuredHeight(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredHeight() + insets.top + insets.bottom;
}
/**
* Lay out the given child view within the RecyclerView using coordinates that
* include any current {@link ItemDecoration ItemDecorations}.
*
* <p>LayoutManagers should prefer working in sizes and coordinates that include
* item decoration insets whenever possible. This allows the LayoutManager to effectively
* ignore decoration insets within measurement and layout code. See the following
* methods:</p>
* <ul>
* <li>{@link #layoutDecoratedWithMargins(View, int, int, int, int)}</li>
* <li>{@link #getDecoratedBoundsWithMargins(View, Rect)}</li>
* <li>{@link #measureChild(View, int, int)}</li>
* <li>{@link #measureChildWithMargins(View, int, int)}</li>
* <li>{@link #getDecoratedLeft(View)}</li>
* <li>{@link #getDecoratedTop(View)}</li>
* <li>{@link #getDecoratedRight(View)}</li>
* <li>{@link #getDecoratedBottom(View)}</li>
* <li>{@link #getDecoratedMeasuredWidth(View)}</li>
* <li>{@link #getDecoratedMeasuredHeight(View)}</li>
* </ul>
*
* @param child Child to lay out
* @param left Left edge, with item decoration insets included
* @param top Top edge, with item decoration insets included
* @param right Right edge, with item decoration insets included
* @param bottom Bottom edge, with item decoration insets included
*
* @see View#layout(int, int, int, int)
* @see #layoutDecoratedWithMargins(View, int, int, int, int)
**/
public void layoutDecorated(View child, int left, int top, int right, int bottom) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
child.layout(left + insets.left, top + insets.top, right - insets.right,
bottom - insets.bottom);
}
/**
* Lay out the given child view within the RecyclerView using coordinates that
* include any current {@link ItemDecoration ItemDecorations} and margins.
*
* <p>LayoutManagers should prefer working in sizes and coordinates that include
* item decoration insets whenever possible. This allows the LayoutManager to effectively
* ignore decoration insets within measurement and layout code. See the following
* methods:</p>
* <ul>
* <li>{@link #layoutDecorated(View, int, int, int, int)}</li>
* <li>{@link #measureChild(View, int, int)}</li>
* <li>{@link #measureChildWithMargins(View, int, int)}</li>
* <li>{@link #getDecoratedLeft(View)}</li>
* <li>{@link #getDecoratedTop(View)}</li>
* <li>{@link #getDecoratedRight(View)}</li>
* <li>{@link #getDecoratedBottom(View)}</li>
* <li>{@link #getDecoratedMeasuredWidth(View)}</li>
* <li>{@link #getDecoratedMeasuredHeight(View)}</li>
* </ul>
*
* @param child Child to lay out
* @param left Left edge, with item decoration insets and left margin included
* @param top Top edge, with item decoration insets and top margin included
* @param right Right edge, with item decoration insets and right margin included
* @param bottom Bottom edge, with item decoration insets and bottom margin included
*
* @see View#layout(int, int, int, int)
* @see #layoutDecorated(View, int, int, int, int)
**/
public void layoutDecoratedWithMargins(View child, int left, int top, int right,
int bottom) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = lp.mDecorInsets;
//layout
child.layout(left + insets.left + lp.leftMargin, top + insets.top + lp.topMargin,
right - insets.right - lp.rightMargin,
bottom - insets.bottom - lp.bottomMargin);
}
/**
* Calculates the bounding box of the View while taking into account its matrix changes
* (translation, scale etc) with respect to the RecyclerView.
* <p>
* If {@code includeDecorInsets} is {@code true}, they are applied first before applying
* the View's matrix so that the decor offsets also go through the same transformation.
*
* @param child The ItemView whose bounding box should be calculated.
* @param includeDecorInsets True if the decor insets should be included in the bounding box
* @param out The rectangle into which the output will be written.
**/
public void getTransformedBoundingBox(View child, boolean includeDecorInsets, Rect out) {
if (includeDecorInsets) {
Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
out.set(-insets.left, -insets.top,
child.getWidth() + insets.right, child.getHeight() + insets.bottom);
} else {
out.set(0, 0, child.getWidth(), child.getHeight());
}
if (mRecyclerView != null) {
final Matrix childMatrix = child.getMatrix();
if (childMatrix != null && !childMatrix.isIdentity()) {
final RectF tempRectF = mRecyclerView.mTempRectF;
tempRectF.set(out);
childMatrix.mapRect(tempRectF);
out.set(
(int) Math.floor(tempRectF.left),
(int) Math.floor(tempRectF.top),
(int) Math.ceil(tempRectF.right),
(int) Math.ceil(tempRectF.bottom)
);
}
}
out.offset(child.getLeft(), child.getTop());
}
/**
* Returns the bounds of the view including its decoration and margins.
*
* @param view The view element to check
* @param outBounds A rect that will receive the bounds of the element including its
* decoration and margins.
**/
public void getDecoratedBoundsWithMargins(View view, Rect outBounds) {
RecyclerView.getDecoratedBoundsWithMarginsInt(view, outBounds);
}
/**
* Returns the left edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child left edge with offsets applied
* @see #getLeftDecorationWidth(View)
**/
public int getDecoratedLeft(View child) {
return child.getLeft() - getLeftDecorationWidth(child);
}
/**
* Returns the top edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child top edge with offsets applied
* @see #getTopDecorationHeight(View)
**/
public int getDecoratedTop(View child) {
return child.getTop() - getTopDecorationHeight(child);
}
/**
* Returns the right edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child right edge with offsets applied
* @see #getRightDecorationWidth(View)
**/
public int getDecoratedRight(View child) {
return child.getRight() + getRightDecorationWidth(child);
}
/**
* Returns the bottom edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child bottom edge with offsets applied
* @see #getBottomDecorationHeight(View)
**/
public int getDecoratedBottom(View child) {
return child.getBottom() + getBottomDecorationHeight(child);
}
/**
* Calculates the item decor insets applied to the given child and updates the provided
* Rect instance with the inset values.
* <ul>
* <li>The Rect's left is set to the total width of left decorations.</li>
* <li>The Rect's top is set to the total height of top decorations.</li>
* <li>The Rect's right is set to the total width of right decorations.</li>
* <li>The Rect's bottom is set to total height of bottom decorations.</li>
* </ul>
* <p>
* Note that item decorations are automatically calculated when one of the LayoutManager's
* measure child methods is called. If you need to measure the child with custom specs via
* {@link View#measure(int, int)}, you can use this method to get decorations.
*
* @param child The child view whose decorations should be calculated
* @param outRect The Rect to hold result values
**/
public void calculateItemDecorationsForChild(View child, Rect outRect) {
if (mRecyclerView == null) {
outRect.set(0, 0, 0, 0);
return;
}
Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
outRect.set(insets);
}
/**
* Returns the total height of item decorations applied to child's top.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total height of item decorations applied to the child's top.
* @see #getDecoratedTop(View)
* @see #calculateItemDecorationsForChild(View, Rect)
**/
public int getTopDecorationHeight(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.top;
}
/**
* Returns the total height of item decorations applied to child's bottom.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total height of item decorations applied to the child's bottom.
* @see #getDecoratedBottom(View)
* @see #calculateItemDecorationsForChild(View, Rect)
**/
public int getBottomDecorationHeight(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.bottom;
}
/**
* Returns the total width of item decorations applied to child's left.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total width of item decorations applied to the child's left.
* @see #getDecoratedLeft(View)
* @see #calculateItemDecorationsForChild(View, Rect)
**/
public int getLeftDecorationWidth(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.left;
}
/**
* Returns the total width of item decorations applied to child's right.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total width of item decorations applied to the child's right.
* @see #getDecoratedRight(View)
* @see #calculateItemDecorationsForChild(View, Rect)
**/
public int getRightDecorationWidth(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.right;
}
/**
* Called when searching for a focusable view in the given direction has failed
* for the current content of the RecyclerView.
*
* <p>This is the LayoutManager's opportunity to populate views in the given direction
* to fulfill the request if it can. The LayoutManager should attach and return
* the view to be focused, if a focusable view in the given direction is found.
* Otherwise, if all the existing (or the newly populated views) are unfocusable, it returns
* the next unfocusable view to become visible on the screen. This unfocusable view is
* typically the first view that's either partially or fully out of RV's padded bounded
* area in the given direction. The default implementation returns null.</p>
*
* @param focused The currently focused view
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* or 0 for not applicable
* @param recycler The recycler to use for obtaining views for currently offscreen items
* @param state Transient state of RecyclerView
* @return The chosen view to be focused if a focusable view is found, otherwise an
* unfocusable view to become visible onto the screen, else null.
**/
@Nullable
public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
State state) {
return null;
}
/**
* This method gives a LayoutManager an opportunity to intercept the initial focus search
* before the default behavior of {@link FocusFinder} is used. If this method returns
* null FocusFinder will attempt to find a focusable child view. If it fails
* then {@link #onFocusSearchFailed(View, int, RecyclerView.Recycler, RecyclerView.State)}
* will be called to give the LayoutManager an opportunity to add new views for items
* that did not have attached views representing them. The LayoutManager should not add
* or remove views from this method.
*
* @param focused The currently focused view
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* @return A descendant view to focus or null to fall back to default behavior.
* The default implementation returns null.
**/
public View onInterceptFocusSearch(View focused, int direction) {
return null;
}
/**
* Returns the scroll amount that brings the given rect in child's coordinate system within
* the padded area of RecyclerView.
* @param parent The parent RecyclerView.
* @param child The direct child making the request.
* @param rect The rectangle in the child's coordinates the child
* wishes to be on the screen.
* @param immediate True to forbid animated or delayed scrolling,
* false otherwise
* @return The array containing the scroll amount in x and y directions that brings the
* given rect into RV's padded area.
**/
private int[] getChildRectangleOnScreenScrollAmount(RecyclerView parent, View child,
Rect rect, boolean immediate) {
int[] out = new int[2];
final int parentLeft = getPaddingLeft();
final int parentTop = getPaddingTop();
final int parentRight = getWidth() - getPaddingRight();
final int parentBottom = getHeight() - getPaddingBottom();
final int childLeft = child.getLeft() + rect.left - child.getScrollX();
final int childTop = child.getTop() + rect.top - child.getScrollY();
final int childRight = childLeft + rect.width();
final int childBottom = childTop + rect.height();
final int offScreenLeft = Math.min(0, childLeft - parentLeft);
final int offScreenTop = Math.min(0, childTop - parentTop);
final int offScreenRight = Math.max(0, childRight - parentRight);
final int offScreenBottom = Math.max(0, childBottom - parentBottom);
// Favor the "start" layout direction over the end when bringing one side or the other
// of a large rect into view. If we decide to bring in end because start is already
// visible, limit the scroll such that start won't go out of bounds.
final int dx;
if (getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL) {
dx = offScreenRight != 0 ? offScreenRight
: Math.max(offScreenLeft, childRight - parentRight);
} else {
dx = offScreenLeft != 0 ? offScreenLeft
: Math.min(childLeft - parentLeft, offScreenRight);
}
// Favor bringing the top into view over the bottom. If top is already visible and
// we should scroll to make bottom visible, make sure top does not go out of bounds.
final int dy = offScreenTop != 0 ? offScreenTop
: Math.min(childTop - parentTop, offScreenBottom);
out[0] = dx;
out[1] = dy;
return out;
}
/**
* Called when a child of the RecyclerView wants a particular rectangle to be positioned
* onto the screen. See {@link ViewParent#requestChildRectangleOnScreen(android.view.View,
* android.graphics.Rect, boolean)} for more details.
*
* <p>The base implementation will attempt to perform a standard programmatic scroll
* to bring the given rect into view, within the padded area of the RecyclerView.</p>
*
* @param child The direct child making the request.
* @param rect The rectangle in the child's coordinates the child
* wishes to be on the screen.
* @param immediate True to forbid animated or delayed scrolling,
* false otherwise
* @return Whether the group scrolled to handle the operation
**/
public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect,
boolean immediate) {
return requestChildRectangleOnScreen(parent, child, rect, immediate, false);
}
/**
* Requests that the given child of the RecyclerView be positioned onto the screen. This
* method can be called for both unfocusable and focusable child views. For unfocusable
* child views, focusedChildVisible is typically true in which case, layout manager
* makes the child view visible only if the currently focused child stays in-bounds of RV.
* @param parent The parent RecyclerView.
* @param child The direct child making the request.
* @param rect The rectangle in the child's coordinates the child
* wishes to be on the screen.
* @param immediate True to forbid animated or delayed scrolling,
* false otherwise
* @param focusedChildVisible Whether the currently focused view must stay visible.
* @return Whether the group scrolled to handle the operation
**/
public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect,
boolean immediate,
boolean focusedChildVisible) {
int[] scrollAmount = getChildRectangleOnScreenScrollAmount(parent, child, rect,
immediate);
int dx = scrollAmount[0];
int dy = scrollAmount[1];
if (!focusedChildVisible || isFocusedChildVisibleAfterScrolling(parent, dx, dy)) {
if (dx != 0 || dy != 0) {
if (immediate) {
parent.scrollBy(dx, dy);
} else {
parent.smoothScrollBy(dx, dy);
}
return true;
}
}
return false;
}
/**
* Returns whether the given child view is partially or fully visible within the padded
* bounded area of RecyclerView, depending on the input parameters.
* A view is partially visible if it has non-zero overlap with RV's padded bounded area.
* If acceptEndPointInclusion flag is set to true, it's also considered partially
* visible if it's located outside RV's bounds and it's hitting either RV's start or end
* bounds.
*
* @param child The child view to be examined.
* @param completelyVisible If true, the method returns true if and only if the child is
* completely visible. If false, the method returns true if and
* only if the child is only partially visible (that is it will
* return false if the child is either completely visible or out
* of RV's bounds).
* @param acceptEndPointInclusion If the view's endpoint intersection with RV's start of end
* bounds is enough to consider it partially visible,
* false otherwise.
* @return True if the given child is partially or fully visible, false otherwise.
**/
public boolean isViewPartiallyVisible(@NonNull View child, boolean completelyVisible,
boolean acceptEndPointInclusion) {
int boundsFlag = (ViewBoundsCheck.FLAG_CVS_GT_PVS | ViewBoundsCheck.FLAG_CVS_EQ_PVS
| ViewBoundsCheck.FLAG_CVE_LT_PVE | ViewBoundsCheck.FLAG_CVE_EQ_PVE);
boolean isViewFullyVisible = mHorizontalBoundCheck.isViewWithinBoundFlags(child,
boundsFlag)
&& mVerticalBoundCheck.isViewWithinBoundFlags(child, boundsFlag);
if (completelyVisible) {
return isViewFullyVisible;
} else {
return !isViewFullyVisible;
}
}
/**
* Returns whether the currently focused child stays within RV's bounds with the given
* amount of scrolling.
* @param parent The parent RecyclerView.
* @param dx The scrolling in x-axis direction to be performed.
* @param dy The scrolling in y-axis direction to be performed.
* @return {@code false} if the focused child is not at least partially visible after
* scrolling or no focused child exists, {@code true} otherwise.
**/
private boolean isFocusedChildVisibleAfterScrolling(RecyclerView parent, int dx, int dy) {
final View focusedChild = parent.getFocusedChild();
if (focusedChild == null) {
return false;
}
final int parentLeft = getPaddingLeft();
final int parentTop = getPaddingTop();
final int parentRight = getWidth() - getPaddingRight();
final int parentBottom = getHeight() - getPaddingBottom();
final Rect bounds = mRecyclerView.mTempRect;
getDecoratedBoundsWithMargins(focusedChild, bounds);
if (bounds.left - dx >= parentRight || bounds.right - dx <= parentLeft
|| bounds.top - dy >= parentBottom || bounds.bottom - dy <= parentTop) {
return false;
}
return true;
}
/**
* @deprecated Use {@link #onRequestChildFocus(RecyclerView, State, View, View)}
**/
@Deprecated
public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
// eat the request if we are in the middle of a scroll or layout
return isSmoothScrolling() || parent.isComputingLayout();
}
/**
* Called when a descendant view of the RecyclerView requests focus.
*
* <p>A LayoutManager wishing to keep focused views aligned in a specific
* portion of the view may implement that behavior in an override of this method.</p>
*
* <p>If the LayoutManager executes different behavior that should override the default
* behavior of scrolling the focused child on screen instead of running alongside it,
* this method should return true.</p>
*
* @param parent The RecyclerView hosting this LayoutManager
* @param state Current state of RecyclerView
* @param child Direct child of the RecyclerView containing the newly focused view
* @param focused The newly focused view. This may be the same view as child or it may be
* null
* @return true if the default scroll behavior should be suppressed
**/
public boolean onRequestChildFocus(RecyclerView parent, State state, View child,
View focused) {
return onRequestChildFocus(parent, child, focused);
}
/**
* Called if the RecyclerView this LayoutManager is bound to has a different adapter set.
* The LayoutManager may use this opportunity to clear caches and configure state such
* that it can relayout appropriately with the new data and potentially new view types.
*
* <p>The default implementation removes all currently attached views.</p>
*
* @param oldAdapter The previous adapter instance. Will be null if there was previously no
* adapter.
* @param newAdapter The new adapter instance. Might be null if
* {@link #setAdapter(RecyclerView.Adapter)} is called with {@code null}.
**/
public void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter) {
}
/**
* Called to populate focusable views within the RecyclerView.
*
* <p>The LayoutManager implementation should return <code>true</code> if the default
* behavior of {@link ViewGroup#addFocusables(java.util.ArrayList, int)} should be
* suppressed.</p>
*
* <p>The default implementation returns <code>false</code> to trigger RecyclerView
* to fall back to the default ViewGroup behavior.</p>
*
* @param recyclerView The RecyclerView hosting this LayoutManager
* @param views List of output views. This method should add valid focusable views
* to this list.
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* @param focusableMode The type of focusables to be added.
*
* @return true to suppress the default behavior, false to add default focusables after
* this method returns.
*
* @see #FOCUSABLES_ALL
* @see #FOCUSABLES_TOUCH_MODE
**/
public boolean onAddFocusables(RecyclerView recyclerView, ArrayList<View> views,
int direction, int focusableMode) {
return false;
}
/**
* Called when {@link Adapter#notifyDataSetChanged()} is triggered instead of giving
* detailed information on what has actually changed.
*
* @param recyclerView
**/
public void onItemsChanged(RecyclerView recyclerView) {
}
/**
* Called when items have been added to the adapter. The LayoutManager may choose to
* requestLayout if the inserted items would require refreshing the currently visible set
* of child views. (e.g. currently empty space would be filled by appended items, etc.)
*
* @param recyclerView
* @param positionStart
* @param itemCount
**/
public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
}
/**
* Called when items have been removed from the adapter.
*
* @param recyclerView
* @param positionStart
* @param itemCount
**/
public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
}
/**
* Called when items have been changed in the adapter.
* To receive payload, override {@link #onItemsUpdated(RecyclerView, int, int, Object)}
* instead, then this callback will not be invoked.
*
* @param recyclerView
* @param positionStart
* @param itemCount
**/
public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount) {
}
/**
* Called when items have been changed in the adapter and with optional payload.
* Default implementation calls {@link #onItemsUpdated(RecyclerView, int, int)}.
*
* @param recyclerView
* @param positionStart
* @param itemCount
* @param payload
**/
public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount,
Object payload) {
onItemsUpdated(recyclerView, positionStart, itemCount);
}
/**
* Called when an item is moved withing the adapter.
* <p>
* Note that, an item may also change position in response to another ADD/REMOVE/MOVE
* operation. This callback is only called if and only if {@link Adapter#notifyItemMoved}
* is called.
*
* @param recyclerView
* @param from
* @param to
* @param itemCount
**/
public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) {
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeHorizontalScrollExtent()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current state of RecyclerView
* @return The horizontal extent of the scrollbar's thumb
* @see RecyclerView#computeHorizontalScrollExtent()
**/
public int computeHorizontalScrollExtent(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeHorizontalScrollOffset()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The horizontal offset of the scrollbar's thumb
* @see RecyclerView#computeHorizontalScrollOffset()
**/
public int computeHorizontalScrollOffset(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeHorizontalScrollRange()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The total horizontal range represented by the vertical scrollbar
* @see RecyclerView#computeHorizontalScrollRange()
**/
public int computeHorizontalScrollRange(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeVerticalScrollExtent()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current state of RecyclerView
* @return The vertical extent of the scrollbar's thumb
* @see RecyclerView#computeVerticalScrollExtent()
**/
public int computeVerticalScrollExtent(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeVerticalScrollOffset()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The vertical offset of the scrollbar's thumb
* @see RecyclerView#computeVerticalScrollOffset()
**/
public int computeVerticalScrollOffset(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeVerticalScrollRange()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The total vertical range represented by the vertical scrollbar
* @see RecyclerView#computeVerticalScrollRange()
**/
public int computeVerticalScrollRange(State state) {
return 0;
}
/**
* Measure the attached RecyclerView. Implementations must call
* {@link #setMeasuredDimension(int, int)} before returning.
*
* <p>The default implementation will handle EXACTLY measurements and respect
* the minimum width and height properties of the host RecyclerView if measured
* as UNSPECIFIED. AT_MOST measurements will be treated as EXACTLY and the RecyclerView
* will consume all available space.</p>
*
* @param recycler Recycler
* @param state Transient state of RecyclerView
* @param widthSpec Width {@link android.view.View.MeasureSpec}
* @param heightSpec Height {@link android.view.View.MeasureSpec}
**/
public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
mRecyclerView.defaultOnMeasure(widthSpec, heightSpec);
}
/**
* {@link View#setMeasuredDimension(int, int) Set the measured dimensions} of the
* host RecyclerView.
*
* @param widthSize Measured width
* @param heightSize Measured height
**/
public void setMeasuredDimension(int widthSize, int heightSize) {
mRecyclerView.setMeasuredDimension(widthSize, heightSize);
}
/**
* @return The host RecyclerView's {@link View#getMinimumWidth()}
**/
public int getMinimumWidth() {
return ViewCompat.getMinimumWidth(mRecyclerView);
}
/**
* @return The host RecyclerView's {@link View#getMinimumHeight()}
**/
public int getMinimumHeight() {
return ViewCompat.getMinimumHeight(mRecyclerView);
}
/**
* <p>Called when the LayoutManager should save its state. This is a good time to save your
* scroll position, configuration and anything else that may be required to restore the same
* layout state if the LayoutManager is recreated.</p>
* <p>RecyclerView does NOT verify if the LayoutManager has changed between state save and
* restore. This will let you share information between your LayoutManagers but it is also
* your responsibility to make sure they use the same parcelable class.</p>
*
* @return Necessary information for LayoutManager to be able to restore its state
**/
public Parcelable onSaveInstanceState() {
return null;
}
public void onRestoreInstanceState(Parcelable state) {
}
void stopSmoothScroller() {
if (mSmoothScroller != null) {
mSmoothScroller.stop();
}
}
private void onSmoothScrollerStopped(SmoothScroller smoothScroller) {
if (mSmoothScroller == smoothScroller) {
mSmoothScroller = null;
}
}
/**
* RecyclerView calls this method to notify LayoutManager that scroll state has changed.
*
* @param state The new scroll state for RecyclerView
**/
public void onScrollStateChanged(int state) {
}
/**
* Removes all views and recycles them using the given recycler.
* <p>
* If you want to clean cached views as well, you should call {@link Recycler#clear()} too.
* <p>
* If a View is marked as "ignored", it is not removed nor recycled.
*
* @param recycler Recycler to use to recycle children
* @see #removeAndRecycleView(View, Recycler)
* @see #removeAndRecycleViewAt(int, Recycler)
* @see #ignoreView(View)
**/
public void removeAndRecycleAllViews(Recycler recycler) {
for (int i = getChildCount() - 1; i >= 0; i--) {
final View view = getChildAt(i);
if (!getChildViewHolderInt(view).shouldIgnore()) {
removeAndRecycleViewAt(i, recycler);
}
}
}
// called by accessibility delegate
void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfoCompat info) {
onInitializeAccessibilityNodeInfo(mRecyclerView.mRecycler, mRecyclerView.mState, info);
}
/**
* Called by the AccessibilityDelegate when the information about the current layout should
* be populated.
* <p>
* Default implementation adds a {@link
* android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat}.
* <p>
* You should override
* {@link #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)},
* {@link #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)},
* {@link #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State)} and
* {@link #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State)} for
* more accurate accessibility information.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param info The info that should be filled by the LayoutManager
* @see View#onInitializeAccessibilityNodeInfo(
*android.view.accessibility.AccessibilityNodeInfo)
* @see #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)
* @see #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)
* @see #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State)
* @see #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State)
**/
public void onInitializeAccessibilityNodeInfo(Recycler recycler, State state,
AccessibilityNodeInfoCompat info) {
if (mRecyclerView.canScrollVertically(-1) || mRecyclerView.canScrollHorizontally(-1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
info.setScrollable(true);
}
if (mRecyclerView.canScrollVertically(1) || mRecyclerView.canScrollHorizontally(1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
info.setScrollable(true);
}
final AccessibilityNodeInfoCompat.CollectionInfoCompat collectionInfo =
AccessibilityNodeInfoCompat.CollectionInfoCompat
.obtain(getRowCountForAccessibility(recycler, state),
getColumnCountForAccessibility(recycler, state),
isLayoutHierarchical(recycler, state),
getSelectionModeForAccessibility(recycler, state));
info.setCollectionInfo(collectionInfo);
}
// called by accessibility delegate
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
onInitializeAccessibilityEvent(mRecyclerView.mRecycler, mRecyclerView.mState, event);
}
/**
* Called by the accessibility delegate to initialize an accessibility event.
* <p>
* Default implementation adds item count and scroll information to the event.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param event The event instance to initialize
* @see View#onInitializeAccessibilityEvent(android.view.accessibility.AccessibilityEvent)
**/
public void onInitializeAccessibilityEvent(Recycler recycler, State state,
AccessibilityEvent event) {
if (mRecyclerView == null || event == null) {
return;
}
event.setScrollable(mRecyclerView.canScrollVertically(1)
|| mRecyclerView.canScrollVertically(-1)
|| mRecyclerView.canScrollHorizontally(-1)
|| mRecyclerView.canScrollHorizontally(1));
if (mRecyclerView.mAdapter != null) {
event.setItemCount(mRecyclerView.mAdapter.getItemCount());
}
}
// called by accessibility delegate
void onInitializeAccessibilityNodeInfoForItem(View host, AccessibilityNodeInfoCompat info) {
final ViewHolder vh = getChildViewHolderInt(host);
// avoid trying to create accessibility node info for removed children
if (vh != null && !vh.isRemoved() && !mChildHelper.isHidden(vh.itemView)) {
onInitializeAccessibilityNodeInfoForItem(mRecyclerView.mRecycler,
mRecyclerView.mState, host, info);
}
}
/**
* Called by the AccessibilityDelegate when the accessibility information for a specific
* item should be populated.
* <p>
* Default implementation adds basic positioning information about the item.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param host The child for which accessibility node info should be populated
* @param info The info to fill out about the item
* @see android.widget.AbsListView#onInitializeAccessibilityNodeInfoForItem(View, int,
* android.view.accessibility.AccessibilityNodeInfo)
**/
public void onInitializeAccessibilityNodeInfoForItem(Recycler recycler, State state,
View host, AccessibilityNodeInfoCompat info) {
int rowIndexGuess = canScrollVertically() ? getPosition(host) : 0;
int columnIndexGuess = canScrollHorizontally() ? getPosition(host) : 0;
final AccessibilityNodeInfoCompat.CollectionItemInfoCompat itemInfo =
AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(rowIndexGuess, 1,
columnIndexGuess, 1, false, false);
info.setCollectionItemInfo(itemInfo);
}
/**
* A LayoutManager can call this method to force RecyclerView to run simple animations in
* the next layout pass, even if there is not any trigger to do so. (e.g. adapter data
* change).
* <p>
* Note that, calling this method will not guarantee that RecyclerView will run animations
* at all. For example, if there is not any {@link ItemAnimator} set, RecyclerView will
* not run any animations but will still clear this flag after the layout is complete.
*
**/
public void requestSimpleAnimationsInNextLayout() {
mRequestedSimpleAnimations = true;
}
/**
* Returns the selection mode for accessibility. Should be
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE},
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_SINGLE} or
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_MULTIPLE}.
* <p>
* Default implementation returns
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return Selection mode for accessibility. Default implementation returns
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}.
**/
public int getSelectionModeForAccessibility(Recycler recycler, State state) {
return AccessibilityNodeInfoCompat.CollectionInfoCompat.SELECTION_MODE_NONE;
}
/**
* Returns the number of rows for accessibility.
* <p>
* Default implementation returns the number of items in the adapter if LayoutManager
* supports vertical scrolling or 1 if LayoutManager does not support vertical
* scrolling.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return The number of rows in LayoutManager for accessibility.
**/
public int getRowCountForAccessibility(Recycler recycler, State state) {
if (mRecyclerView == null || mRecyclerView.mAdapter == null) {
return 1;
}
return canScrollVertically() ? mRecyclerView.mAdapter.getItemCount() : 1;
}
/**
* Returns the number of columns for accessibility.
* <p>
* Default implementation returns the number of items in the adapter if LayoutManager
* supports horizontal scrolling or 1 if LayoutManager does not support horizontal
* scrolling.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return The number of rows in LayoutManager for accessibility.
**/
public int getColumnCountForAccessibility(Recycler recycler, State state) {
if (mRecyclerView == null || mRecyclerView.mAdapter == null) {
return 1;
}
return canScrollHorizontally() ? mRecyclerView.mAdapter.getItemCount() : 1;
}
/**
* Returns whether layout is hierarchical or not to be used for accessibility.
* <p>
* Default implementation returns false.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return True if layout is hierarchical.
**/
public boolean isLayoutHierarchical(Recycler recycler, State state) {
return false;
}
// called by accessibility delegate
boolean performAccessibilityAction(int action, Bundle args) {
return performAccessibilityAction(mRecyclerView.mRecycler, mRecyclerView.mState,
action, args);
}
/**
* Called by AccessibilityDelegate when an action is requested from the RecyclerView.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param action The action to perform
* @param args Optional action arguments
* @see View#performAccessibilityAction(int, android.os.Bundle)
**/
public boolean performAccessibilityAction(Recycler recycler, State state, int action,
Bundle args) {
if (mRecyclerView == null) {
return false;
}
int vScroll = 0, hScroll = 0;
switch (action) {
case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD:
if (mRecyclerView.canScrollVertically(-1)) {
vScroll = -(getHeight() - getPaddingTop() - getPaddingBottom());
}
if (mRecyclerView.canScrollHorizontally(-1)) {
hScroll = -(getWidth() - getPaddingLeft() - getPaddingRight());
}
break;
case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD:
if (mRecyclerView.canScrollVertically(1)) {
vScroll = getHeight() - getPaddingTop() - getPaddingBottom();
}
if (mRecyclerView.canScrollHorizontally(1)) {
hScroll = getWidth() - getPaddingLeft() - getPaddingRight();
}
break;
}
if (vScroll == 0 && hScroll == 0) {
return false;
}
mRecyclerView.scrollBy(hScroll, vScroll);
return true;
}
// called by accessibility delegate
boolean performAccessibilityActionForItem(View view, int action, Bundle args) {
return performAccessibilityActionForItem(mRecyclerView.mRecycler, mRecyclerView.mState,
view, action, args);
}
/**
* Called by AccessibilityDelegate when an accessibility action is requested on one of the
* children of LayoutManager.
* <p>
* Default implementation does not do anything.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param view The child view on which the action is performed
* @param action The action to perform
* @param args Optional action arguments
* @return true if action is handled
* @see View#performAccessibilityAction(int, android.os.Bundle)
**/
public boolean performAccessibilityActionForItem(Recycler recycler, State state, View view,
int action, Bundle args) {
return false;
}
/**
* Parse the xml attributes to get the most common properties used by layout managers.
*
* @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_android_orientation
* @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_spanCount
* @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_reverseLayout
* @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_stackFromEnd
*
* @return an object containing the properties as specified in the attrs.
**/
public static Properties getProperties(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
Properties properties = new Properties();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecyclerView,
defStyleAttr, defStyleRes);
properties.orientation = a.getInt(R.styleable.RecyclerView_android_orientation,
VERTICAL);
properties.spanCount = a.getInt(R.styleable.RecyclerView_spanCount, 1);
properties.reverseLayout = a.getBoolean(R.styleable.RecyclerView_reverseLayout, false);
properties.stackFromEnd = a.getBoolean(R.styleable.RecyclerView_stackFromEnd, false);
a.recycle();
return properties;
}
void setExactMeasureSpecsFrom(RecyclerView recyclerView) {
setMeasureSpecs(
MeasureSpec.makeMeasureSpec(recyclerView.getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(recyclerView.getHeight(), MeasureSpec.EXACTLY)
);
}
/**
* Internal API to allow LayoutManagers to be measured twice.
* <p>
* This is not public because LayoutManagers should be able to handle their layouts in one
* pass but it is very convenient to make existing LayoutManagers support wrapping content
* when both orientations are undefined.
* <p>
* This API will be removed after default LayoutManagers properly implement wrap content in
* non-scroll orientation.
**/
boolean shouldMeasureTwice() {
return false;
}
boolean hasFlexibleChildInBothOrientations() {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final ViewGroup.LayoutParams lp = child.getLayoutParams();
if (lp.width < 0 && lp.height < 0) {
return true;
}
}
return false;
}
/**
* Some general properties that a LayoutManager may want to use.
**/
public static class Properties {
/** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_android_orientation **/
public int orientation;
/** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_spanCount **/
public int spanCount;
/** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_reverseLayout **/
public boolean reverseLayout;
/** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_stackFromEnd **/
public boolean stackFromEnd;
}
}
/**
* An ItemDecoration allows the application to add a special drawing and layout offset
* to specific item views from the adapter's data set. This can be useful for drawing dividers
* between items, highlights, visual grouping boundaries and more.
*
* <p>All ItemDecorations are drawn in the order they were added, before the item
* views (in {@link ItemDecoration#onDraw(Canvas, RecyclerView, RecyclerView.State) onDraw()}
* and after the items (in {@link ItemDecoration#onDrawOver(Canvas, RecyclerView,
* RecyclerView.State)}.</p>
**/
public abstract static class ItemDecoration {
/**
* Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
* Any content drawn by this method will be drawn before the item views are drawn,
* and will thus appear underneath the views.
*
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView
**/
public void onDraw(Canvas c, RecyclerView parent, State state) {
onDraw(c, parent);
}
/**
* @deprecated
* Override {@link #onDraw(Canvas, RecyclerView, RecyclerView.State)}
**/
@Deprecated
public void onDraw(Canvas c, RecyclerView parent) {
}
/**
* Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
* Any content drawn by this method will be drawn after the item views are drawn
* and will thus appear over the views.
*
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView.
**/
public void onDrawOver(Canvas c, RecyclerView parent, State state) {
onDrawOver(c, parent);
}
/**
* @deprecated
* Override {@link #onDrawOver(Canvas, RecyclerView, RecyclerView.State)}
**/
@Deprecated
public void onDrawOver(Canvas c, RecyclerView parent) {
}
/**
* @deprecated
* Use {@link #getItemOffsets(Rect, View, RecyclerView, State)}
**/
@Deprecated
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
outRect.set(0, 0, 0, 0);
}
/**
* Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies
* the number of pixels that the item view should be inset by, similar to padding or margin.
* The default implementation sets the bounds of outRect to 0 and returns.
*
* <p>
* If this ItemDecoration does not affect the positioning of item views, it should set
* all four fields of <code>outRect</code> (left, top, right, bottom) to zero
* before returning.
*
* <p>
* If you need to access Adapter for additional data, you can call
* {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the
* View.
*
* @param outRect Rect to receive the output.
* @param view The child view to decorate
* @param parent RecyclerView this ItemDecoration is decorating
* @param state The current state of RecyclerView.
**/
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
parent);
}
}
/**
* An OnItemTouchListener allows the application to intercept touch events in progress at the
* view hierarchy level of the RecyclerView before those touch events are considered for
* RecyclerView's own scrolling behavior.
*
* <p>This can be useful for applications that wish to implement various forms of gestural
* manipulation of item views within the RecyclerView. OnItemTouchListeners may intercept
* a touch interaction already in progress even if the RecyclerView is already handling that
* gesture stream itself for the purposes of scrolling.</p>
*
* @see SimpleOnItemTouchListener
**/
public interface OnItemTouchListener {
/**
* Silently observe and/or take over touch events sent to the RecyclerView
* before they are handled by either the RecyclerView itself or its child views.
*
* <p>The onInterceptTouchEvent methods of each attached OnItemTouchListener will be run
* in the order in which each listener was added, before any other touch processing
* by the RecyclerView itself or child views occurs.</p>
*
* @param e MotionEvent describing the touch event. All coordinates are in
* the RecyclerView's coordinate system.
* @return true if this OnItemTouchListener wishes to begin intercepting touch events, false
* to continue with the current behavior and continue observing future events in
* the gesture.
**/
boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e);
/**
* Process a touch event as part of a gesture that was claimed by returning true from
* a previous call to {@link #onInterceptTouchEvent}.
*
* @param e MotionEvent describing the touch event. All coordinates are in
* the RecyclerView's coordinate system.
**/
void onTouchEvent(RecyclerView rv, MotionEvent e);
/**
* Called when a child of RecyclerView does not want RecyclerView and its ancestors to
* intercept touch events with
* {@link ViewGroup#onInterceptTouchEvent(MotionEvent)}.
*
* @param disallowIntercept True if the child does not want the parent to
* intercept touch events.
* @see ViewParent#requestDisallowInterceptTouchEvent(boolean)
**/
void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept);
}
/**
* An implementation of {@link RecyclerView.OnItemTouchListener} that has empty method bodies
* and default return values.
* <p>
* You may prefer to extend this class if you don't need to override all methods. Another
* benefit of using this class is future compatibility. As the interface may change, we'll
* always provide a default implementation on this class so that your code won't break when
* you update to a new version of the support library.
**/
public static class SimpleOnItemTouchListener implements RecyclerView.OnItemTouchListener {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
/**
* An OnScrollListener can be added to a RecyclerView to receive messages when a scrolling event
* has occurred on that RecyclerView.
* <p>
* @see RecyclerView#addOnScrollListener(OnScrollListener)
* @see RecyclerView#clearOnChildAttachStateChangeListeners()
*
**/
public abstract static class OnScrollListener {
/**
* Callback method to be invoked when RecyclerView's scroll state changes.
*
* @param recyclerView The RecyclerView whose scroll state has changed.
* @param newState The updated scroll state. One of {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}.
**/
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
}
/**
* Callback method to be invoked when the RecyclerView has been scrolled. This will be
* called after the scroll has completed.
* <p>
* This callback will also be called if visible item range changes after a layout
* calculation. In that case, dx and dy will be 0.
*
* @param recyclerView The RecyclerView which scrolled.
* @param dx The amount of horizontal scroll.
* @param dy The amount of vertical scroll.
**/
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
}
}
/**
* A RecyclerListener can be set on a RecyclerView to receive messages whenever
* a view is recycled.
*
* @see RecyclerView#setRecyclerListener(RecyclerListener)
**/
public interface RecyclerListener {
/**
* This method is called whenever the view in the ViewHolder is recycled.
*
* RecyclerView calls this method right before clearing ViewHolder's internal data and
* sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
* before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get
* its adapter position.
*
* @param holder The ViewHolder containing the view that was recycled
**/
void onViewRecycled(ViewHolder holder);
}
/**
* A Listener interface that can be attached to a RecylcerView to get notified
* whenever a ViewHolder is attached to or detached from RecyclerView.
**/
public interface OnChildAttachStateChangeListener {
/**
* Called when a view is attached to the RecyclerView.
*
* @param view The View which is attached to the RecyclerView
**/
void onChildViewAttachedToWindow(View view);
/**
* Called when a view is detached from RecyclerView.
*
* @param view The View which is being detached from the RecyclerView
**/
void onChildViewDetachedFromWindow(View view);
}
/**
* A ViewHolder describes an item view and metadata about its place within the RecyclerView.
*
* <p>{@link Adapter} implementations should subclass ViewHolder and add fields for caching
* potentially expensive {@link View#findViewById(int)} results.</p>
*
* <p>While {@link LayoutParams} belong to the {@link LayoutManager},
* {@link ViewHolder ViewHolders} belong to the adapter. Adapters should feel free to use
* their own custom ViewHolder implementations to store data that makes binding view contents
* easier. Implementations should assume that individual item views will hold strong references
* to <code>ViewHolder</code> objects and that <code>RecyclerView</code> instances may hold
* strong references to extra off-screen item views for caching purposes</p>
**/
public abstract static class ViewHolder {
public final View itemView;
WeakReference<RecyclerView> mNestedRecyclerView;
int mPosition = NO_POSITION;
int mOldPosition = NO_POSITION;
long mItemId = NO_ID;
int mItemViewType = INVALID_TYPE;
int mPreLayoutPosition = NO_POSITION;
// The item that this holder is shadowing during an item change event/animation
ViewHolder mShadowedHolder = null;
// The item that is shadowing this holder during an item change event/animation
ViewHolder mShadowingHolder = null;
/**
* This ViewHolder has been bound to a position; mPosition, mItemId and mItemViewType
* are all valid.
**/
static final int FLAG_BOUND = 1 << 0;
/**
* The data this ViewHolder's view reflects is stale and needs to be rebound
* by the adapter. mPosition and mItemId are consistent.
**/
static final int FLAG_UPDATE = 1 << 1;
/**
* This ViewHolder's data is invalid. The identity implied by mPosition and mItemId
* are not to be trusted and may no longer match the item view type.
* This ViewHolder must be fully rebound to different data.
**/
static final int FLAG_INVALID = 1 << 2;
/**
* This ViewHolder points at data that represents an item previously removed from the
* data set. Its view may still be used for things like outgoing animations.
**/
static final int FLAG_REMOVED = 1 << 3;
/**
* This ViewHolder should not be recycled. This flag is set via setIsRecyclable()
* and is intended to keep views around during animations.
**/
static final int FLAG_NOT_RECYCLABLE = 1 << 4;
/**
* This ViewHolder is returned from scrap which means we are expecting an addView call
* for this itemView. When returned from scrap, ViewHolder stays in the scrap list until
* the end of the layout pass and then recycled by RecyclerView if it is not added back to
* the RecyclerView.
**/
static final int FLAG_RETURNED_FROM_SCRAP = 1 << 5;
/**
* This ViewHolder is fully managed by the LayoutManager. We do not scrap, recycle or remove
* it unless LayoutManager is replaced.
* It is still fully visible to the LayoutManager.
**/
static final int FLAG_IGNORE = 1 << 7;
/**
* When the View is detached form the parent, we set this flag so that we can take correct
* action when we need to remove it or add it back.
**/
static final int FLAG_TMP_DETACHED = 1 << 8;
/**
* Set when we can no longer determine the adapter position of this ViewHolder until it is
* rebound to a new position. It is different than FLAG_INVALID because FLAG_INVALID is
* set even when the type does not match. Also, FLAG_ADAPTER_POSITION_UNKNOWN is set as soon
* as adapter notification arrives vs FLAG_INVALID is set lazily before layout is
* re-calculated.
**/
static final int FLAG_ADAPTER_POSITION_UNKNOWN = 1 << 9;
/**
* Set when a addChangePayload(null) is called
**/
static final int FLAG_ADAPTER_FULLUPDATE = 1 << 10;
/**
* Used by ItemAnimator when a ViewHolder's position changes
**/
static final int FLAG_MOVED = 1 << 11;
/**
* Used by ItemAnimator when a ViewHolder appears in pre-layout
**/
static final int FLAG_APPEARED_IN_PRE_LAYOUT = 1 << 12;
static final int PENDING_ACCESSIBILITY_STATE_NOT_SET = -1;
/**
* Used when a ViewHolder starts the layout pass as a hidden ViewHolder but is re-used from
* hidden list (as if it was scrap) without being recycled in between.
*
* When a ViewHolder is hidden, there are 2 paths it can be re-used:
* a) Animation ends, view is recycled and used from the recycle pool.
* b) LayoutManager asks for the View for that position while the ViewHolder is hidden.
*
* This flag is used to represent "case b" where the ViewHolder is reused without being
* recycled (thus "bounced" from the hidden list). This state requires special handling
* because the ViewHolder must be added to pre layout maps for animations as if it was
* already there.
**/
static final int FLAG_BOUNCED_FROM_HIDDEN_LIST = 1 << 13;
/**
* Flags that RecyclerView assigned {@link RecyclerViewAccessibilityDelegate
* #getItemDelegate()} in onBindView when app does not provide a delegate.
**/
static final int FLAG_SET_A11Y_ITEM_DELEGATE = 1 << 14;
private int mFlags;
private static final List<Object> FULLUPDATE_PAYLOADS = Collections.EMPTY_LIST;
List<Object> mPayloads = null;
List<Object> mUnmodifiedPayloads = null;
private int mIsRecyclableCount = 0;
// If non-null, view is currently considered scrap and may be reused for other data by the
// scrap container.
private Recycler mScrapContainer = null;
// Keeps whether this ViewHolder lives in Change scrap or Attached scrap
private boolean mInChangeScrap = false;
// Saves isImportantForAccessibility value for the view item while it's in hidden state and
// marked as unimportant for accessibility.
private int mWasImportantForAccessibilityBeforeHidden =
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
// set if we defer the accessibility state change of the view holder
@VisibleForTesting
int mPendingAccessibilityState = PENDING_ACCESSIBILITY_STATE_NOT_SET;
/**
* Is set when VH is bound from the adapter and cleaned right before it is sent to
* {@link RecycledViewPool}.
**/
RecyclerView mOwnerRecyclerView;
public ViewHolder(View itemView) {
if (itemView == null) {
throw new IllegalArgumentException("itemView may not be null");
}
this.itemView = itemView;
}
void flagRemovedAndOffsetPosition(int mNewPosition, int offset, boolean applyToPreLayout) {
addFlags(ViewHolder.FLAG_REMOVED);
offsetPosition(offset, applyToPreLayout);
mPosition = mNewPosition;
}
void offsetPosition(int offset, boolean applyToPreLayout) {
if (mOldPosition == NO_POSITION) {
mOldPosition = mPosition;
}
if (mPreLayoutPosition == NO_POSITION) {
mPreLayoutPosition = mPosition;
}
if (applyToPreLayout) {
mPreLayoutPosition += offset;
}
mPosition += offset;
if (itemView.getLayoutParams() != null) {
((LayoutParams) itemView.getLayoutParams()).mInsetsDirty = true;
}
}
void clearOldPosition() {
mOldPosition = NO_POSITION;
mPreLayoutPosition = NO_POSITION;
}
void saveOldPosition() {
if (mOldPosition == NO_POSITION) {
mOldPosition = mPosition;
}
}
boolean shouldIgnore() {
return (mFlags & FLAG_IGNORE) != 0;
}
/**
* @deprecated This method is deprecated because its meaning is ambiguous due to the async
* handling of adapter updates. Please use {@link #getLayoutPosition()} or
* {@link #getAdapterPosition()} depending on your use case.
*
* @see #getLayoutPosition()
* @see #getAdapterPosition()
**/
@Deprecated
public final int getPosition() {
return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition;
}
/**
* Returns the position of the ViewHolder in terms of the latest layout pass.
* <p>
* This position is mostly used by RecyclerView components to be consistent while
* RecyclerView lazily processes adapter updates.
* <p>
* For performance and animation reasons, RecyclerView batches all adapter updates until the
* next layout pass. This may cause mismatches between the Adapter position of the item and
* the position it had in the latest layout calculations.
* <p>
* LayoutManagers should always call this method while doing calculations based on item
* positions. All methods in {@link RecyclerView.LayoutManager}, {@link RecyclerView.State},
* {@link RecyclerView.Recycler} that receive a position expect it to be the layout position
* of the item.
* <p>
* If LayoutManager needs to call an external method that requires the adapter position of
* the item, it can use {@link #getAdapterPosition()} or
* {@link RecyclerView.Recycler#convertPreLayoutPositionToPostLayout(int)}.
*
* @return Returns the adapter position of the ViewHolder in the latest layout pass.
* @see #getAdapterPosition()
**/
public final int getLayoutPosition() {
return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition;
}
/**
* Returns the Adapter position of the item represented by this ViewHolder.
* <p>
* Note that this might be different than the {@link #getLayoutPosition()} if there are
* pending adapter updates but a new layout pass has not happened yet.
* <p>
* RecyclerView does not handle any adapter updates until the next layout traversal. This
* may create temporary inconsistencies between what user sees on the screen and what
* adapter contents have. This inconsistency is not important since it will be less than
* 16ms but it might be a problem if you want to use ViewHolder position to access the
* adapter. Sometimes, you may need to get the exact adapter position to do
* some actions in response to user events. In that case, you should use this method which
* will calculate the Adapter position of the ViewHolder.
* <p>
* Note that if you've called {@link RecyclerView.Adapter#notifyDataSetChanged()}, until the
* next layout pass, the return value of this method will be {@link #NO_POSITION}.
*
* @return The adapter position of the item if it still exists in the adapter.
* {@link RecyclerView#NO_POSITION} if item has been removed from the adapter,
* {@link RecyclerView.Adapter#notifyDataSetChanged()} has been called after the last
* layout pass or the ViewHolder has already been recycled.
**/
public final int getAdapterPosition() {
if (mOwnerRecyclerView == null) {
return NO_POSITION;
}
return mOwnerRecyclerView.getAdapterPositionFor(this);
}
/**
* When LayoutManager supports animations, RecyclerView tracks 3 positions for ViewHolders
* to perform animations.
* <p>
* If a ViewHolder was laid out in the previous onLayout call, old position will keep its
* adapter index in the previous layout.
*
* @return The previous adapter index of the Item represented by this ViewHolder or
* {@link #NO_POSITION} if old position does not exists or cleared (pre-layout is
* complete).
**/
public final int getOldPosition() {
return mOldPosition;
}
/**
* Returns The itemId represented by this ViewHolder.
*
* @return The item's id if adapter has stable ids, {@link RecyclerView#NO_ID}
* otherwise
**/
public final long getItemId() {
return mItemId;
}
/**
* @return The view type of this ViewHolder.
**/
public final int getItemViewType() {
return mItemViewType;
}
boolean isScrap() {
return mScrapContainer != null;
}
void unScrap() {
mScrapContainer.unscrapView(this);
}
boolean wasReturnedFromScrap() {
return (mFlags & FLAG_RETURNED_FROM_SCRAP) != 0;
}
void clearReturnedFromScrapFlag() {
mFlags = mFlags & ~FLAG_RETURNED_FROM_SCRAP;
}
void clearTmpDetachFlag() {
mFlags = mFlags & ~FLAG_TMP_DETACHED;
}
void stopIgnoring() {
mFlags = mFlags & ~FLAG_IGNORE;
}
void setScrapContainer(Recycler recycler, boolean isChangeScrap) {
mScrapContainer = recycler;
mInChangeScrap = isChangeScrap;
}
boolean isInvalid() {
return (mFlags & FLAG_INVALID) != 0;
}
boolean needsUpdate() {
return (mFlags & FLAG_UPDATE) != 0;
}
boolean isBound() {
return (mFlags & FLAG_BOUND) != 0;
}
public boolean isRemoved() {
return (mFlags & FLAG_REMOVED) != 0;
}
boolean hasAnyOfTheFlags(int flags) {
return (mFlags & flags) != 0;
}
boolean isTmpDetached() {
return (mFlags & FLAG_TMP_DETACHED) != 0;
}
boolean isAdapterPositionUnknown() {
return (mFlags & FLAG_ADAPTER_POSITION_UNKNOWN) != 0 || isInvalid();
}
void setFlags(int flags, int mask) {
mFlags = (mFlags & ~mask) | (flags & mask);
}
void addFlags(int flags) {
mFlags |= flags;
}
void addChangePayload(Object payload) {
if (payload == null) {
addFlags(FLAG_ADAPTER_FULLUPDATE);
} else if ((mFlags & FLAG_ADAPTER_FULLUPDATE) == 0) {
createPayloadsIfNeeded();
mPayloads.add(payload);
}
}
private void createPayloadsIfNeeded() {
if (mPayloads == null) {
mPayloads = new ArrayList<Object>();
mUnmodifiedPayloads = Collections.unmodifiableList(mPayloads);
}
}
void clearPayload() {
if (mPayloads != null) {
mPayloads.clear();
}
mFlags = mFlags & ~FLAG_ADAPTER_FULLUPDATE;
}
List<Object> getUnmodifiedPayloads() {
if ((mFlags & FLAG_ADAPTER_FULLUPDATE) == 0) {
if (mPayloads == null || mPayloads.size() == 0) {
// Initial state, no update being called.
return FULLUPDATE_PAYLOADS;
}
// there are none-null payloads
return mUnmodifiedPayloads;
} else {
// a full update has been called.
return FULLUPDATE_PAYLOADS;
}
}
void resetInternal() {
mFlags = 0;
mPosition = NO_POSITION;
mOldPosition = NO_POSITION;
mItemId = NO_ID;
mPreLayoutPosition = NO_POSITION;
mIsRecyclableCount = 0;
mShadowedHolder = null;
mShadowingHolder = null;
clearPayload();
mWasImportantForAccessibilityBeforeHidden = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
mPendingAccessibilityState = PENDING_ACCESSIBILITY_STATE_NOT_SET;
clearNestedRecyclerViewIfNotNested(this);
}
/**
* Called when the child view enters the hidden state
**/
private void onEnteredHiddenState(RecyclerView parent) {
// While the view item is in hidden state, make it invisible for the accessibility.
mWasImportantForAccessibilityBeforeHidden =
ViewCompat.getImportantForAccessibility(itemView);
parent.setChildImportantForAccessibilityInternal(this,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
}
/**
* Called when the child view leaves the hidden state
**/
private void onLeftHiddenState(RecyclerView parent) {
parent.setChildImportantForAccessibilityInternal(this,
mWasImportantForAccessibilityBeforeHidden);
mWasImportantForAccessibilityBeforeHidden = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ViewHolder{"
+ Integer.toHexString(hashCode()) + " position=" + mPosition + " id=" + mItemId
+ ", oldPos=" + mOldPosition + ", pLpos:" + mPreLayoutPosition);
if (isScrap()) {
sb.append(" scrap ")
.append(mInChangeScrap ? "[changeScrap]" : "[attachedScrap]");
}
if (isInvalid()) sb.append(" invalid");
if (!isBound()) sb.append(" unbound");
if (needsUpdate()) sb.append(" update");
if (isRemoved()) sb.append(" removed");
if (shouldIgnore()) sb.append(" ignored");
if (isTmpDetached()) sb.append(" tmpDetached");
if (!isRecyclable()) sb.append(" not recyclable(" + mIsRecyclableCount + ")");
if (isAdapterPositionUnknown()) sb.append(" undefined adapter position");
if (itemView.getParent() == null) sb.append(" no parent");
sb.append("}");
return sb.toString();
}
/**
* Informs the recycler whether this item can be recycled. Views which are not
* recyclable will not be reused for other items until setIsRecyclable() is
* later set to true. Calls to setIsRecyclable() should always be paired (one
* call to setIsRecyclabe(false) should always be matched with a later call to
* setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally
* reference-counted.
*
* @param recyclable Whether this item is available to be recycled. Default value
* is true.
*
* @see #isRecyclable()
**/
public final void setIsRecyclable(boolean recyclable) {
mIsRecyclableCount = recyclable ? mIsRecyclableCount - 1 : mIsRecyclableCount + 1;
if (mIsRecyclableCount < 0) {
mIsRecyclableCount = 0;
if (DEBUG) {
throw new RuntimeException("isRecyclable decremented below 0: "
+ "unmatched pair of setIsRecyable() calls for " + this);
}
Log.e(VIEW_LOG_TAG, "isRecyclable decremented below 0: "
+ "unmatched pair of setIsRecyable() calls for " + this);
} else if (!recyclable && mIsRecyclableCount == 1) {
mFlags |= FLAG_NOT_RECYCLABLE;
} else if (recyclable && mIsRecyclableCount == 0) {
mFlags &= ~FLAG_NOT_RECYCLABLE;
}
if (DEBUG) {
Log.d(TAG, "setIsRecyclable val:" + recyclable + ":" + this);
}
}
/**
* @return true if this item is available to be recycled, false otherwise.
*
* @see #setIsRecyclable(boolean)
**/
public final boolean isRecyclable() {
return (mFlags & FLAG_NOT_RECYCLABLE) == 0
&& !ViewCompat.hasTransientState(itemView);
}
/**
* Returns whether we have animations referring to this view holder or not.
* This is similar to isRecyclable flag but does not check transient state.
**/
private boolean shouldBeKeptAsChild() {
return (mFlags & FLAG_NOT_RECYCLABLE) != 0;
}
/**
* @return True if ViewHolder is not referenced by RecyclerView animations but has
* transient state which will prevent it from being recycled.
**/
private boolean doesTransientStatePreventRecycling() {
return (mFlags & FLAG_NOT_RECYCLABLE) == 0 && ViewCompat.hasTransientState(itemView);
}
boolean isUpdated() {
return (mFlags & FLAG_UPDATE) != 0;
}
}
/**
* This method is here so that we can control the important for a11y changes and test it.
**/
@VisibleForTesting
boolean setChildImportantForAccessibilityInternal(ViewHolder viewHolder,
int importantForAccessibility) {
if (isComputingLayout()) {
viewHolder.mPendingAccessibilityState = importantForAccessibility;
mPendingAccessibilityImportanceChange.add(viewHolder);
return false;
}
ViewCompat.setImportantForAccessibility(viewHolder.itemView, importantForAccessibility);
return true;
}
void dispatchPendingImportantForAccessibilityChanges() {
for (int i = mPendingAccessibilityImportanceChange.size() - 1; i >= 0; i--) {
ViewHolder viewHolder = mPendingAccessibilityImportanceChange.get(i);
if (viewHolder.itemView.getParent() != this || viewHolder.shouldIgnore()) {
continue;
}
int state = viewHolder.mPendingAccessibilityState;
if (state != ViewHolder.PENDING_ACCESSIBILITY_STATE_NOT_SET) {
//noinspection WrongConstant
ViewCompat.setImportantForAccessibility(viewHolder.itemView, state);
viewHolder.mPendingAccessibilityState =
ViewHolder.PENDING_ACCESSIBILITY_STATE_NOT_SET;
}
}
mPendingAccessibilityImportanceChange.clear();
}
int getAdapterPositionFor(ViewHolder viewHolder) {
if (viewHolder.hasAnyOfTheFlags(ViewHolder.FLAG_INVALID
| ViewHolder.FLAG_REMOVED | ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN)
|| !viewHolder.isBound()) {
return RecyclerView.NO_POSITION;
}
return mAdapterHelper.applyPendingUpdatesToPosition(viewHolder.mPosition);
}
@VisibleForTesting
void initFastScroller(StateListDrawable verticalThumbDrawable,
Drawable verticalTrackDrawable, StateListDrawable horizontalThumbDrawable,
Drawable horizontalTrackDrawable) {
if (verticalThumbDrawable == null || verticalTrackDrawable == null
|| horizontalThumbDrawable == null || horizontalTrackDrawable == null) {
throw new IllegalArgumentException(
"Trying to set fast scroller without both required drawables." + exceptionLabel());
}
Resources resources = getContext().getResources();
new FastScroller(this, verticalThumbDrawable, verticalTrackDrawable,
horizontalThumbDrawable, horizontalTrackDrawable,
resources.getDimensionPixelSize(R.dimen.fastscroll_default_thickness),
resources.getDimensionPixelSize(R.dimen.fastscroll_minimum_range),
resources.getDimensionPixelOffset(R.dimen.fastscroll_margin));
}
// NestedScrollingChild
@Override
public void setNestedScrollingEnabled(boolean enabled) {
getScrollingChildHelper().setNestedScrollingEnabled(enabled);
}
@Override
public boolean isNestedScrollingEnabled() {
return getScrollingChildHelper().isNestedScrollingEnabled();
}
@Override
public boolean startNestedScroll(int axes) {
return getScrollingChildHelper().startNestedScroll(axes);
}
@Override
public boolean startNestedScroll(int axes, int type) {
return getScrollingChildHelper().startNestedScroll(axes, type);
}
@Override
public void stopNestedScroll() {
getScrollingChildHelper().stopNestedScroll();
}
@Override
public void stopNestedScroll(int type) {
getScrollingChildHelper().stopNestedScroll(type);
}
@Override
public boolean hasNestedScrollingParent() {
return getScrollingChildHelper().hasNestedScrollingParent();
}
@Override
public boolean hasNestedScrollingParent(int type) {
return getScrollingChildHelper().hasNestedScrollingParent(type);
}
@Override
public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed,
int dyUnconsumed, int[] offsetInWindow) {
return getScrollingChildHelper().dispatchNestedScroll(dxConsumed, dyConsumed,
dxUnconsumed, dyUnconsumed, offsetInWindow);
}
@Override
public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed,
int dyUnconsumed, int[] offsetInWindow, int type) {
return getScrollingChildHelper().dispatchNestedScroll(dxConsumed, dyConsumed,
dxUnconsumed, dyUnconsumed, offsetInWindow, type);
}
@Override
public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
return getScrollingChildHelper().dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
}
@Override
public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow,
int type) {
return getScrollingChildHelper().dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow,
type);
}
@Override
public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
return getScrollingChildHelper().dispatchNestedFling(velocityX, velocityY, consumed);
}
@Override
public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
return getScrollingChildHelper().dispatchNestedPreFling(velocityX, velocityY);
}
/**
* {@link android.view.ViewGroup.MarginLayoutParams LayoutParams} subclass for children of
* {@link RecyclerView}. Custom {@link LayoutManager layout managers} are encouraged
* to create their own subclass of this <code>LayoutParams</code> class
* to store any additional required per-child view metadata about the layout.
**/
public static class LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
ViewHolder mViewHolder;
final Rect mDecorInsets = new Rect();
boolean mInsetsDirty = true;
// Flag is set to true if the view is bound while it is detached from RV.
// In this case, we need to manually call invalidate after view is added to guarantee that
// invalidation is populated through the View hierarchy
boolean mPendingInvalidate = false;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(LayoutParams source) {
super((ViewGroup.LayoutParams) source);
}
/**
* Returns true if the view this LayoutParams is attached to needs to have its content
* updated from the corresponding adapter.
*
* @return true if the view should have its content updated
**/
public boolean viewNeedsUpdate() {
return mViewHolder.needsUpdate();
}
/**
* Returns true if the view this LayoutParams is attached to is now representing
* potentially invalid data. A LayoutManager should scrap/recycle it.
*
* @return true if the view is invalid
**/
public boolean isViewInvalid() {
return mViewHolder.isInvalid();
}
/**
* Returns true if the adapter data item corresponding to the view this LayoutParams
* is attached to has been removed from the data set. A LayoutManager may choose to
* treat it differently in order to animate its outgoing or disappearing state.
*
* @return true if the item the view corresponds to was removed from the data set
**/
public boolean isItemRemoved() {
return mViewHolder.isRemoved();
}
/**
* Returns true if the adapter data item corresponding to the view this LayoutParams
* is attached to has been changed in the data set. A LayoutManager may choose to
* treat it differently in order to animate its changing state.
*
* @return true if the item the view corresponds to was changed in the data set
**/
public boolean isItemChanged() {
return mViewHolder.isUpdated();
}
/**
* @deprecated use {@link #getViewLayoutPosition()} or {@link #getViewAdapterPosition()}
**/
@Deprecated
public int getViewPosition() {
return mViewHolder.getPosition();
}
/**
* Returns the adapter position that the view this LayoutParams is attached to corresponds
* to as of latest layout calculation.
*
* @return the adapter position this view as of latest layout pass
**/
public int getViewLayoutPosition() {
return mViewHolder.getLayoutPosition();
}
/**
* Returns the up-to-date adapter position that the view this LayoutParams is attached to
* corresponds to.
*
* @return the up-to-date adapter position this view. It may return
* {@link RecyclerView#NO_POSITION} if item represented by this View has been removed or
* its up-to-date position cannot be calculated.
**/
public int getViewAdapterPosition() {
return mViewHolder.getAdapterPosition();
}
}
/**
* Observer base class for watching changes to an {@link Adapter}.
* See {@link Adapter#registerAdapterDataObserver(AdapterDataObserver)}.
**/
public abstract static class AdapterDataObserver {
public void onChanged() {
// Do nothing
}
public void onItemRangeChanged(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
// fallback to onItemRangeChanged(positionStart, itemCount) if app
// does not override this method.
onItemRangeChanged(positionStart, itemCount);
}
public void onItemRangeInserted(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeRemoved(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
// do nothing
}
}
/**
* <p>Base class for smooth scrolling. Handles basic tracking of the target view position and
* provides methods to trigger a programmatic scroll.</p>
*
* @see LinearSmoothScroller
**/
public abstract static class SmoothScroller {
private int mTargetPosition = RecyclerView.NO_POSITION;
private RecyclerView mRecyclerView;
private LayoutManager mLayoutManager;
private boolean mPendingInitialRun;
private boolean mRunning;
private View mTargetView;
private final Action mRecyclingAction;
public SmoothScroller() {
mRecyclingAction = new Action(0, 0);
}
/**
* Starts a smooth scroll for the given target position.
* <p>In each animation step, {@link RecyclerView} will check
* for the target view and call either
* {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or
* {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)} until
* SmoothScroller is stopped.</p>
*
* <p>Note that if RecyclerView finds the target view, it will automatically stop the
* SmoothScroller. This <b>does not</b> mean that scroll will stop, it only means it will
* stop calling SmoothScroller in each animation step.</p>
**/
void start(RecyclerView recyclerView, LayoutManager layoutManager) {
mRecyclerView = recyclerView;
mLayoutManager = layoutManager;
if (mTargetPosition == RecyclerView.NO_POSITION) {
throw new IllegalArgumentException("Invalid target position");
}
mRecyclerView.mState.mTargetPosition = mTargetPosition;
mRunning = true;
mPendingInitialRun = true;
mTargetView = findViewByPosition(getTargetPosition());
onStart();
mRecyclerView.mViewFlinger.postOnAnimation();
}
public void setTargetPosition(int targetPosition) {
mTargetPosition = targetPosition;
}
/**
* @return The LayoutManager to which this SmoothScroller is attached. Will return
* <code>null</code> after the SmoothScroller is stopped.
**/
@Nullable
public LayoutManager getLayoutManager() {
return mLayoutManager;
}
/**
* Stops running the SmoothScroller in each animation callback. Note that this does not
* cancel any existing {@link Action} updated by
* {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or
* {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)}.
**/
protected final void stop() {
if (!mRunning) {
return;
}
onStop();
mRecyclerView.mState.mTargetPosition = RecyclerView.NO_POSITION;
mTargetView = null;
mTargetPosition = RecyclerView.NO_POSITION;
mPendingInitialRun = false;
mRunning = false;
// trigger a cleanup
mLayoutManager.onSmoothScrollerStopped(this);
// clear references to avoid any potential leak by a custom smooth scroller
mLayoutManager = null;
mRecyclerView = null;
}
/**
* Returns true if SmoothScroller has been started but has not received the first
* animation
* callback yet.
*
* @return True if this SmoothScroller is waiting to start
**/
public boolean isPendingInitialRun() {
return mPendingInitialRun;
}
/**
* @return True if SmoothScroller is currently active
**/
public boolean isRunning() {
return mRunning;
}
/**
* Returns the adapter position of the target item
*
* @return Adapter position of the target item or
* {@link RecyclerView#NO_POSITION} if no target view is set.
**/
public int getTargetPosition() {
return mTargetPosition;
}
private void onAnimation(int dx, int dy) {
final RecyclerView recyclerView = mRecyclerView;
if (!mRunning || mTargetPosition == RecyclerView.NO_POSITION || recyclerView == null) {
stop();
}
mPendingInitialRun = false;
if (mTargetView != null) {
// verify target position
if (getChildPosition(mTargetView) == mTargetPosition) {
onTargetFound(mTargetView, recyclerView.mState, mRecyclingAction);
mRecyclingAction.runIfNecessary(recyclerView);
stop();
} else {
Log.e(TAG, "Passed over target position while smooth scrolling.");
mTargetView = null;
}
}
if (mRunning) {
onSeekTargetStep(dx, dy, recyclerView.mState, mRecyclingAction);
boolean hadJumpTarget = mRecyclingAction.hasJumpTarget();
mRecyclingAction.runIfNecessary(recyclerView);
if (hadJumpTarget) {
// It is not stopped so needs to be restarted
if (mRunning) {
mPendingInitialRun = true;
recyclerView.mViewFlinger.postOnAnimation();
} else {
stop(); // done
}
}
}
}
/**
* @see RecyclerView#getChildLayoutPosition(android.view.View)
**/
public int getChildPosition(View view) {
return mRecyclerView.getChildLayoutPosition(view);
}
/**
* @see RecyclerView.LayoutManager#getChildCount()
**/
public int getChildCount() {
return mRecyclerView.mLayout.getChildCount();
}
/**
* @see RecyclerView.LayoutManager#findViewByPosition(int)
**/
public View findViewByPosition(int position) {
return mRecyclerView.mLayout.findViewByPosition(position);
}
/**
* @see RecyclerView#scrollToPosition(int)
* @deprecated Use {@link Action#jumpTo(int)}.
**/
@Deprecated
public void instantScrollToPosition(int position) {
mRecyclerView.scrollToPosition(position);
}
protected void onChildAttachedToWindow(View child) {
if (getChildPosition(child) == getTargetPosition()) {
mTargetView = child;
if (DEBUG) {
Log.d(TAG, "smooth scroll target view has been attached");
}
}
}
/**
* Normalizes the vector.
* @param scrollVector The vector that points to the target scroll position
**/
protected void normalize(PointF scrollVector) {
final float magnitude = (float) Math.sqrt(scrollVector.x * scrollVector.x
+ scrollVector.y * scrollVector.y);
scrollVector.x /= magnitude;
scrollVector.y /= magnitude;
}
/**
* Called when smooth scroll is started. This might be a good time to do setup.
**/
protected abstract void onStart();
/**
* Called when smooth scroller is stopped. This is a good place to cleanup your state etc.
* @see #stop()
**/
protected abstract void onStop();
/**
* <p>RecyclerView will call this method each time it scrolls until it can find the target
* position in the layout.</p>
* <p>SmoothScroller should check dx, dy and if scroll should be changed, update the
* provided {@link Action} to define the next scroll.</p>
*
* @param dx Last scroll amount horizontally
* @param dy Last scroll amount vertically
* @param state Transient state of RecyclerView
* @param action If you want to trigger a new smooth scroll and cancel the previous one,
* update this object.
**/
protected abstract void onSeekTargetStep(int dx, int dy, State state, Action action);
/**
* Called when the target position is laid out. This is the last callback SmoothScroller
* will receive and it should update the provided {@link Action} to define the scroll
* details towards the target view.
* @param targetView The view element which render the target position.
* @param state Transient state of RecyclerView
* @param action Action instance that you should update to define final scroll action
* towards the targetView
**/
protected abstract void onTargetFound(View targetView, State state, Action action);
/**
* Holds information about a smooth scroll request by a {@link SmoothScroller}.
**/
public static class Action {
public static final int UNDEFINED_DURATION = Integer.MIN_VALUE;
private int mDx;
private int mDy;
private int mDuration;
private int mJumpToPosition = NO_POSITION;
private Interpolator mInterpolator;
private boolean mChanged = false;
// we track this variable to inform custom implementer if they are updating the action
// in every animation callback
private int mConsecutiveUpdates = 0;
/**
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
**/
public Action(int dx, int dy) {
this(dx, dy, UNDEFINED_DURATION, null);
}
/**
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param duration Duration of the animation in milliseconds
**/
public Action(int dx, int dy, int duration) {
this(dx, dy, duration, null);
}
/**
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param duration Duration of the animation in milliseconds
* @param interpolator Interpolator to be used when calculating scroll position in each
* animation step
**/
public Action(int dx, int dy, int duration, Interpolator interpolator) {
mDx = dx;
mDy = dy;
mDuration = duration;
mInterpolator = interpolator;
}
/**
* Instead of specifying pixels to scroll, use the target position to jump using
* {@link RecyclerView#scrollToPosition(int)}.
* <p>
* You may prefer using this method if scroll target is really far away and you prefer
* to jump to a location and smooth scroll afterwards.
* <p>
* Note that calling this method takes priority over other update methods such as
* {@link #update(int, int, int, Interpolator)}, {@link #setX(float)},
* {@link #setY(float)} and #{@link #setInterpolator(Interpolator)}. If you call
* {@link #jumpTo(int)}, the other changes will not be considered for this animation
* frame.
*
* @param targetPosition The target item position to scroll to using instant scrolling.
**/
public void jumpTo(int targetPosition) {
mJumpToPosition = targetPosition;
}
boolean hasJumpTarget() {
return mJumpToPosition >= 0;
}
void runIfNecessary(RecyclerView recyclerView) {
if (mJumpToPosition >= 0) {
final int position = mJumpToPosition;
mJumpToPosition = NO_POSITION;
recyclerView.jumpToPositionForSmoothScroller(position);
mChanged = false;
return;
}
if (mChanged) {
validate();
if (mInterpolator == null) {
if (mDuration == UNDEFINED_DURATION) {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy);
} else {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration);
}
} else {
recyclerView.mViewFlinger.smoothScrollBy(
mDx, mDy, mDuration, mInterpolator);
}
mConsecutiveUpdates++;
if (mConsecutiveUpdates > 10) {
// A new action is being set in every animation step. This looks like a bad
// implementation. Inform developer.
Log.e(TAG, "Smooth Scroll action is being updated too frequently. Make sure"
+ " you are not changing it unless necessary");
}
mChanged = false;
} else {
mConsecutiveUpdates = 0;
}
}
private void validate() {
if (mInterpolator != null && mDuration < 1) {
throw new IllegalStateException("If you provide an interpolator, you must"
+ " set a positive duration");
} else if (mDuration < 1) {
throw new IllegalStateException("Scroll duration must be a positive number");
}
}
public int getDx() {
return mDx;
}
public void setDx(int dx) {
mChanged = true;
mDx = dx;
}
public int getDy() {
return mDy;
}
public void setDy(int dy) {
mChanged = true;
mDy = dy;
}
public int getDuration() {
return mDuration;
}
public void setDuration(int duration) {
mChanged = true;
mDuration = duration;
}
public Interpolator getInterpolator() {
return mInterpolator;
}
/**
* Sets the interpolator to calculate scroll steps
* @param interpolator The interpolator to use. If you specify an interpolator, you must
* also set the duration.
* @see #setDuration(int)
**/
public void setInterpolator(Interpolator interpolator) {
mChanged = true;
mInterpolator = interpolator;
}
/**
* Updates the action with given parameters.
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param duration Duration of the animation in milliseconds
* @param interpolator Interpolator to be used when calculating scroll position in each
* animation step
**/
public void update(int dx, int dy, int duration, Interpolator interpolator) {
mDx = dx;
mDy = dy;
mDuration = duration;
mInterpolator = interpolator;
mChanged = true;
}
}
/**
* An interface which is optionally implemented by custom {@link RecyclerView.LayoutManager}
* to provide a hint to a {@link SmoothScroller} about the location of the target position.
**/
public interface ScrollVectorProvider {
/**
* Should calculate the vector that points to the direction where the target position
* can be found.
* <p>
* This method is used by the {@link LinearSmoothScroller} to initiate a scroll towards
* the target position.
* <p>
* The magnitude of the vector is not important. It is always normalized before being
* used by the {@link LinearSmoothScroller}.
* <p>
* LayoutManager should not check whether the position exists in the adapter or not.
*
* @param targetPosition the target position to which the returned vector should point
*
* @return the scroll vector for a given position.
**/
PointF computeScrollVectorForPosition(int targetPosition);
}
}
static class AdapterDataObservable extends Observable<AdapterDataObserver> {
public boolean hasObservers() {
return !mObservers.isEmpty();
}
public void notifyChanged() {
// since onChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
public void notifyItemRangeChanged(int positionStart, int itemCount) {
notifyItemRangeChanged(positionStart, itemCount, null);
}
public void notifyItemRangeChanged(int positionStart, int itemCount, Object payload) {
// since onItemRangeChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeChanged(positionStart, itemCount, payload);
}
}
public void notifyItemRangeInserted(int positionStart, int itemCount) {
// since onItemRangeInserted() is implemented by the app, it could do anything,
// including removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeInserted(positionStart, itemCount);
}
}
public void notifyItemRangeRemoved(int positionStart, int itemCount) {
// since onItemRangeRemoved() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeRemoved(positionStart, itemCount);
}
}
public void notifyItemMoved(int fromPosition, int toPosition) {
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeMoved(fromPosition, toPosition, 1);
}
}
}
/**
* This is public so that the CREATOR can be accessed on cold launch.
* @hide
**/
@RestrictTo(LIBRARY_GROUP)
public static class SavedState extends AbsSavedState {
Parcelable mLayoutState;
/**
* called by CREATOR
**/
SavedState(Parcel in, ClassLoader loader) {
super(in, loader);
mLayoutState = in.readParcelable(
loader != null ? loader : LayoutManager.class.getClassLoader());
}
/**
* Called by onSaveInstanceState
**/
SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeParcelable(mLayoutState, 0);
}
void copyFrom(SavedState other) {
mLayoutState = other.mLayoutState;
}
public static final Creator<SavedState> CREATOR = new ClassLoaderCreator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in, loader);
}
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in, null);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
/**
* <p>Contains useful information about the current RecyclerView state like target scroll
* position or view focus. State object can also keep arbitrary data, identified by resource
* ids.</p>
* <p>Often times, RecyclerView components will need to pass information between each other.
* To provide a well defined data bus between components, RecyclerView passes the same State
* object to component callbacks and these components can use it to exchange data.</p>
* <p>If you implement custom components, you can use State's put/get/remove methods to pass
* data between your components without needing to manage their lifecycles.</p>
**/
public static class State {
static final int STEP_START = 1;
static final int STEP_LAYOUT = 1 << 1;
static final int STEP_ANIMATIONS = 1 << 2;
void assertLayoutStep(int accepted) {
if ((accepted & mLayoutStep) == 0) {
throw new IllegalStateException("Layout state should be one of "
+ Integer.toBinaryString(accepted) + " but it is "
+ Integer.toBinaryString(mLayoutStep));
}
}
/** Owned by SmoothScroller **/
private int mTargetPosition = RecyclerView.NO_POSITION;
private SparseArray<Object> mData;
////////////////////////////////////////////////////////////////////////////////////////////
// Fields below are carried from one layout pass to the next
////////////////////////////////////////////////////////////////////////////////////////////
/**
* Number of items adapter had in the previous layout.
**/
int mPreviousLayoutItemCount = 0;
/**
* Number of items that were NOT laid out but has been deleted from the adapter after the
* previous layout.
**/
int mDeletedInvisibleItemCountSincePreviousLayout = 0;
////////////////////////////////////////////////////////////////////////////////////////////
// Fields below must be updated or cleared before they are used (generally before a pass)
////////////////////////////////////////////////////////////////////////////////////////////
@IntDef(flag = true, value = {
STEP_START, STEP_LAYOUT, STEP_ANIMATIONS
})
@Retention(RetentionPolicy.SOURCE)
@interface LayoutState {
}
@LayoutState
int mLayoutStep = STEP_START;
/**
* Number of items adapter has.
**/
int mItemCount = 0;
boolean mStructureChanged = false;
boolean mInPreLayout = false;
boolean mTrackOldChangeHolders = false;
boolean mIsMeasuring = false;
////////////////////////////////////////////////////////////////////////////////////////////
// Fields below are always reset outside of the pass (or passes) that use them
////////////////////////////////////////////////////////////////////////////////////////////
boolean mRunSimpleAnimations = false;
boolean mRunPredictiveAnimations = false;
/**
* This data is saved before a layout calculation happens. After the layout is finished,
* if the previously focused view has been replaced with another view for the same item, we
* move the focus to the new item automatically.
**/
int mFocusedItemPosition;
long mFocusedItemId;
// when a sub child has focus, record its id and see if we can directly request focus on
// that one instead
int mFocusedSubChildId;
int mRemainingScrollHorizontal;
int mRemainingScrollVertical;
////////////////////////////////////////////////////////////////////////////////////////////
State reset() {
mTargetPosition = RecyclerView.NO_POSITION;
if (mData != null) {
mData.clear();
}
mItemCount = 0;
mStructureChanged = false;
mIsMeasuring = false;
return this;
}
/**
* Prepare for a prefetch occurring on the RecyclerView in between traversals, potentially
* prior to any layout passes.
*
* <p>Don't touch any state stored between layout passes, only reset per-layout state, so
* that Recycler#getViewForPosition() can function safely.</p>
**/
void prepareForNestedPrefetch(Adapter adapter) {
mLayoutStep = STEP_START;
mItemCount = adapter.getItemCount();
mInPreLayout = false;
mTrackOldChangeHolders = false;
mIsMeasuring = false;
}
/**
* Returns true if the RecyclerView is currently measuring the layout. This value is
* {@code true} only if the LayoutManager opted into the auto measure API and RecyclerView
* has non-exact measurement specs.
* <p>
* Note that if the LayoutManager supports predictive animations and it is calculating the
* pre-layout step, this value will be {@code false} even if the RecyclerView is in
* {@code onMeasure} call. This is because pre-layout means the previous state of the
* RecyclerView and measurements made for that state cannot change the RecyclerView's size.
* LayoutManager is always guaranteed to receive another call to
* {@link LayoutManager#onLayoutChildren(Recycler, State)} when this happens.
*
* @return True if the RecyclerView is currently calculating its bounds, false otherwise.
**/
public boolean isMeasuring() {
return mIsMeasuring;
}
/**
* Returns true if
* @return
**/
public boolean isPreLayout() {
return mInPreLayout;
}
/**
* Returns whether RecyclerView will run predictive animations in this layout pass
* or not.
*
* @return true if RecyclerView is calculating predictive animations to be run at the end
* of the layout pass.
**/
public boolean willRunPredictiveAnimations() {
return mRunPredictiveAnimations;
}
/**
* Returns whether RecyclerView will run simple animations in this layout pass
* or not.
*
* @return true if RecyclerView is calculating simple animations to be run at the end of
* the layout pass.
**/
public boolean willRunSimpleAnimations() {
return mRunSimpleAnimations;
}
/**
* Removes the mapping from the specified id, if there was any.
* @param resourceId Id of the resource you want to remove. It is suggested to use R.id.* to
* preserve cross functionality and avoid conflicts.
**/
public void remove(int resourceId) {
if (mData == null) {
return;
}
mData.remove(resourceId);
}
/**
* Gets the Object mapped from the specified id, or <code>null</code>
* if no such data exists.
*
* @param resourceId Id of the resource you want to remove. It is suggested to use R.id.*
* to
* preserve cross functionality and avoid conflicts.
**/
@SuppressWarnings("TypeParameterUnusedInFormals")
public <T> T get(int resourceId) {
if (mData == null) {
return null;
}
return (T) mData.get(resourceId);
}
/**
* Adds a mapping from the specified id to the specified value, replacing the previous
* mapping from the specified key if there was one.
*
* @param resourceId Id of the resource you want to add. It is suggested to use R.id.* to
* preserve cross functionality and avoid conflicts.
* @param data The data you want to associate with the resourceId.
**/
public void put(int resourceId, Object data) {
if (mData == null) {
mData = new SparseArray<Object>();
}
mData.put(resourceId, data);
}
/**
* If scroll is triggered to make a certain item visible, this value will return the
* adapter index of that item.
* @return Adapter index of the target item or
* {@link RecyclerView#NO_POSITION} if there is no target
* position.
**/
public int getTargetScrollPosition() {
return mTargetPosition;
}
/**
* Returns if current scroll has a target position.
* @return true if scroll is being triggered to make a certain position visible
* @see #getTargetScrollPosition()
**/
public boolean hasTargetScrollPosition() {
return mTargetPosition != RecyclerView.NO_POSITION;
}
/**
* @return true if the structure of the data set has changed since the last call to
* onLayoutChildren, false otherwise
**/
public boolean didStructureChange() {
return mStructureChanged;
}
/**
* Returns the total number of items that can be laid out. Note that this number is not
* necessarily equal to the number of items in the adapter, so you should always use this
* number for your position calculations and never access the adapter directly.
* <p>
* RecyclerView listens for Adapter's notify events and calculates the effects of adapter
* data changes on existing Views. These calculations are used to decide which animations
* should be run.
* <p>
* To support predictive animations, RecyclerView may rewrite or reorder Adapter changes to
* present the correct state to LayoutManager in pre-layout pass.
* <p>
* For example, a newly added item is not included in pre-layout item count because
* pre-layout reflects the contents of the adapter before the item is added. Behind the
* scenes, RecyclerView offsets {@link Recycler#getViewForPosition(int)} calls such that
* LayoutManager does not know about the new item's existence in pre-layout. The item will
* be available in second layout pass and will be included in the item count. Similar
* adjustments are made for moved and removed items as well.
* <p>
* You can get the adapter's item count via {@link LayoutManager#getItemCount()} method.
*
* @return The number of items currently available
* @see LayoutManager#getItemCount()
**/
public int getItemCount() {
return mInPreLayout
? (mPreviousLayoutItemCount - mDeletedInvisibleItemCountSincePreviousLayout)
: mItemCount;
}
/**
* Returns remaining horizontal scroll distance of an ongoing scroll animation(fling/
* smoothScrollTo/SmoothScroller) in pixels. Returns zero if {@link #getScrollState()} is
* other than {@link #SCROLL_STATE_SETTLING}.
*
* @return Remaining horizontal scroll distance
**/
public int getRemainingScrollHorizontal() {
return mRemainingScrollHorizontal;
}
/**
* Returns remaining vertical scroll distance of an ongoing scroll animation(fling/
* smoothScrollTo/SmoothScroller) in pixels. Returns zero if {@link #getScrollState()} is
* other than {@link #SCROLL_STATE_SETTLING}.
*
* @return Remaining vertical scroll distance
**/
public int getRemainingScrollVertical() {
return mRemainingScrollVertical;
}
@Override
public String toString() {
return "State{"
+ "mTargetPosition=" + mTargetPosition
+ ", mData=" + mData
+ ", mItemCount=" + mItemCount
+ ", mPreviousLayoutItemCount=" + mPreviousLayoutItemCount
+ ", mDeletedInvisibleItemCountSincePreviousLayout="
+ mDeletedInvisibleItemCountSincePreviousLayout
+ ", mStructureChanged=" + mStructureChanged
+ ", mInPreLayout=" + mInPreLayout
+ ", mRunSimpleAnimations=" + mRunSimpleAnimations
+ ", mRunPredictiveAnimations=" + mRunPredictiveAnimations
+ '}';
}
}
/**
* This class defines the behavior of fling if the developer wishes to handle it.
* <p>
* Subclasses of {@link OnFlingListener} can be used to implement custom fling behavior.
*
* @see #setOnFlingListener(OnFlingListener)
**/
public abstract static class OnFlingListener {
/**
* Override this to handle a fling given the velocities in both x and y directions.
* Note that this method will only be called if the associated {@link LayoutManager}
* supports scrolling and the fling is not handled by nested scrolls first.
*
* @param velocityX the fling velocity on the X axis
* @param velocityY the fling velocity on the Y axis
*
* @return true if the fling was handled, false otherwise.
**/
public abstract boolean onFling(int velocityX, int velocityY);
}
/**
* Internal listener that manages items after animations finish. This is how items are
* retained (not recycled) during animations, but allowed to be recycled afterwards.
* It depends on the contract with the ItemAnimator to call the appropriate dispatch*Finished()
* method on the animator's listener when it is done animating any item.
**/
private class ItemAnimatorRestoreListener implements ItemAnimator.ItemAnimatorListener {
ItemAnimatorRestoreListener() {
}
@Override
public void onAnimationFinished(ViewHolder item) {
item.setIsRecyclable(true);
if (item.mShadowedHolder != null && item.mShadowingHolder == null) { // old vh
item.mShadowedHolder = null;
}
// always null this because an OldViewHolder can never become NewViewHolder w/o being
// recycled.
item.mShadowingHolder = null;
if (!item.shouldBeKeptAsChild()) {
if (!removeAnimatingView(item.itemView) && item.isTmpDetached()) {
removeDetachedView(item.itemView, false);
}
}
}
}
/**
* This class defines the animations that take place on items as changes are made
* to the adapter.
*
* Subclasses of ItemAnimator can be used to implement custom animations for actions on
* ViewHolder items. The RecyclerView will manage retaining these items while they
* are being animated, but implementors must call {@link #dispatchAnimationFinished(ViewHolder)}
* when a ViewHolder's animation is finished. In other words, there must be a matching
* {@link #dispatchAnimationFinished(ViewHolder)} call for each
* {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) animateAppearance()},
* {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateChange()}
* {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo) animatePersistence()},
* and
* {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateDisappearance()} call.
*
* <p>By default, RecyclerView uses {@link DefaultItemAnimator}.</p>
*
* @see #setItemAnimator(ItemAnimator)
**/
@SuppressWarnings("UnusedParameters")
public abstract static class ItemAnimator {
/**
* The Item represented by this ViewHolder is updated.
* <p>
* @see #recordPreLayoutInformation(State, ViewHolder, int, List)
**/
public static final int FLAG_CHANGED = ViewHolder.FLAG_UPDATE;
/**
* The Item represented by this ViewHolder is removed from the adapter.
* <p>
* @see #recordPreLayoutInformation(State, ViewHolder, int, List)
**/
public static final int FLAG_REMOVED = ViewHolder.FLAG_REMOVED;
/**
* Adapter {@link Adapter#notifyDataSetChanged()} has been called and the content
* represented by this ViewHolder is invalid.
* <p>
* @see #recordPreLayoutInformation(State, ViewHolder, int, List)
**/
public static final int FLAG_INVALIDATED = ViewHolder.FLAG_INVALID;
/**
* The position of the Item represented by this ViewHolder has been changed. This flag is
* not bound to {@link Adapter#notifyItemMoved(int, int)}. It might be set in response to
* any adapter change that may have a side effect on this item. (e.g. The item before this
* one has been removed from the Adapter).
* <p>
* @see #recordPreLayoutInformation(State, ViewHolder, int, List)
**/
public static final int FLAG_MOVED = ViewHolder.FLAG_MOVED;
/**
* This ViewHolder was not laid out but has been added to the layout in pre-layout state
* by the {@link LayoutManager}. This means that the item was already in the Adapter but
* invisible and it may become visible in the post layout phase. LayoutManagers may prefer
* to add new items in pre-layout to specify their virtual location when they are invisible
* (e.g. to specify the item should <i>animate in</i> from below the visible area).
* <p>
* @see #recordPreLayoutInformation(State, ViewHolder, int, List)
**/
public static final int FLAG_APPEARED_IN_PRE_LAYOUT =
ViewHolder.FLAG_APPEARED_IN_PRE_LAYOUT;
/**
* The set of flags that might be passed to
* {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
**/
@IntDef(flag = true, value = {
FLAG_CHANGED, FLAG_REMOVED, FLAG_MOVED, FLAG_INVALIDATED,
FLAG_APPEARED_IN_PRE_LAYOUT
})
@Retention(RetentionPolicy.SOURCE)
public @interface AdapterChanges {
}
private ItemAnimatorListener mListener = null;
private ArrayList<ItemAnimatorFinishedListener> mFinishedListeners =
new ArrayList<ItemAnimatorFinishedListener>();
private long mAddDuration = 120;
private long mRemoveDuration = 120;
private long mMoveDuration = 250;
private long mChangeDuration = 250;
/**
* Gets the current duration for which all move animations will run.
*
* @return The current move duration
**/
public long getMoveDuration() {
return mMoveDuration;
}
/**
* Sets the duration for which all move animations will run.
*
* @param moveDuration The move duration
**/
public void setMoveDuration(long moveDuration) {
mMoveDuration = moveDuration;
}
/**
* Gets the current duration for which all add animations will run.
*
* @return The current add duration
**/
public long getAddDuration() {
return mAddDuration;
}
/**
* Sets the duration for which all add animations will run.
*
* @param addDuration The add duration
**/
public void setAddDuration(long addDuration) {
mAddDuration = addDuration;
}
/**
* Gets the current duration for which all remove animations will run.
*
* @return The current remove duration
**/
public long getRemoveDuration() {
return mRemoveDuration;
}
/**
* Sets the duration for which all remove animations will run.
*
* @param removeDuration The remove duration
**/
public void setRemoveDuration(long removeDuration) {
mRemoveDuration = removeDuration;
}
/**
* Gets the current duration for which all change animations will run.
*
* @return The current change duration
**/
public long getChangeDuration() {
return mChangeDuration;
}
/**
* Sets the duration for which all change animations will run.
*
* @param changeDuration The change duration
**/
public void setChangeDuration(long changeDuration) {
mChangeDuration = changeDuration;
}
/**
* Internal only:
* Sets the listener that must be called when the animator is finished
* animating the item (or immediately if no animation happens). This is set
* internally and is not intended to be set by external code.
*
* @param listener The listener that must be called.
**/
void setListener(ItemAnimatorListener listener) {
mListener = listener;
}
/**
* Called by the RecyclerView before the layout begins. Item animator should record
* necessary information about the View before it is potentially rebound, moved or removed.
* <p>
* The data returned from this method will be passed to the related <code>animate**</code>
* methods.
* <p>
* Note that this method may be called after pre-layout phase if LayoutManager adds new
* Views to the layout in pre-layout pass.
* <p>
* The default implementation returns an {@link ItemHolderInfo} which holds the bounds of
* the View and the adapter change flags.
*
* @param state The current State of RecyclerView which includes some useful data
* about the layout that will be calculated.
* @param viewHolder The ViewHolder whose information should be recorded.
* @param changeFlags Additional information about what changes happened in the Adapter
* about the Item represented by this ViewHolder. For instance, if
* item is deleted from the adapter, {@link #FLAG_REMOVED} will be set.
* @param payloads The payload list that was previously passed to
* {@link Adapter#notifyItemChanged(int, Object)} or
* {@link Adapter#notifyItemRangeChanged(int, int, Object)}.
*
* @return An ItemHolderInfo instance that preserves necessary information about the
* ViewHolder. This object will be passed back to related <code>animate**</code> methods
* after layout is complete.
*
* @see #recordPostLayoutInformation(State, ViewHolder)
* @see #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* @see #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* @see #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
* @see #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
**/
public @NonNull
ItemHolderInfo recordPreLayoutInformation(@NonNull State state,
@NonNull ViewHolder viewHolder, @AdapterChanges int changeFlags,
@NonNull List<Object> payloads) {
return obtainHolderInfo().setFrom(viewHolder);
}
/**
* Called by the RecyclerView after the layout is complete. Item animator should record
* necessary information about the View's final state.
* <p>
* The data returned from this method will be passed to the related <code>animate**</code>
* methods.
* <p>
* The default implementation returns an {@link ItemHolderInfo} which holds the bounds of
* the View.
*
* @param state The current State of RecyclerView which includes some useful data about
* the layout that will be calculated.
* @param viewHolder The ViewHolder whose information should be recorded.
*
* @return An ItemHolderInfo that preserves necessary information about the ViewHolder.
* This object will be passed back to related <code>animate**</code> methods when
* RecyclerView decides how items should be animated.
*
* @see #recordPreLayoutInformation(State, ViewHolder, int, List)
* @see #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* @see #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* @see #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
* @see #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
**/
public @NonNull
ItemHolderInfo recordPostLayoutInformation(@NonNull State state,
@NonNull ViewHolder viewHolder) {
return obtainHolderInfo().setFrom(viewHolder);
}
/**
* Called by the RecyclerView when a ViewHolder has disappeared from the layout.
* <p>
* This means that the View was a child of the LayoutManager when layout started but has
* been removed by the LayoutManager. It might have been removed from the adapter or simply
* become invisible due to other factors. You can distinguish these two cases by checking
* the change flags that were passed to
* {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
* <p>
* Note that when a ViewHolder both changes and disappears in the same layout pass, the
* animation callback method which will be called by the RecyclerView depends on the
* ItemAnimator's decision whether to re-use the same ViewHolder or not, and also the
* LayoutManager's decision whether to layout the changed version of a disappearing
* ViewHolder or not. RecyclerView will call
* {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateChange} instead of {@code animateDisappearance} if and only if the ItemAnimator
* returns {@code false} from
* {@link #canReuseUpdatedViewHolder(ViewHolder) canReuseUpdatedViewHolder} and the
* LayoutManager lays out a new disappearing view that holds the updated information.
* Built-in LayoutManagers try to avoid laying out updated versions of disappearing views.
* <p>
* If LayoutManager supports predictive animations, it might provide a target disappear
* location for the View by laying it out in that location. When that happens,
* RecyclerView will call {@link #recordPostLayoutInformation(State, ViewHolder)} and the
* response of that call will be passed to this method as the <code>postLayoutInfo</code>.
* <p>
* ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} when the animation
* is complete (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it
* decides not to animate the view).
*
* @param viewHolder The ViewHolder which should be animated
* @param preLayoutInfo The information that was returned from
* {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
* @param postLayoutInfo The information that was returned from
* {@link #recordPostLayoutInformation(State, ViewHolder)}. Might be
* null if the LayoutManager did not layout the item.
*
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
**/
public abstract boolean animateDisappearance(@NonNull ViewHolder viewHolder,
@NonNull ItemHolderInfo preLayoutInfo, @Nullable ItemHolderInfo postLayoutInfo);
/**
* Called by the RecyclerView when a ViewHolder is added to the layout.
* <p>
* In detail, this means that the ViewHolder was <b>not</b> a child when the layout started
* but has been added by the LayoutManager. It might be newly added to the adapter or
* simply become visible due to other factors.
* <p>
* ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} when the animation
* is complete (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it
* decides not to animate the view).
*
* @param viewHolder The ViewHolder which should be animated
* @param preLayoutInfo The information that was returned from
* {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
* Might be null if Item was just added to the adapter or
* LayoutManager does not support predictive animations or it could
* not predict that this ViewHolder will become visible.
* @param postLayoutInfo The information that was returned from {@link
* #recordPreLayoutInformation(State, ViewHolder, int, List)}.
*
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
**/
public abstract boolean animateAppearance(@NonNull ViewHolder viewHolder,
@Nullable ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo);
/**
* Called by the RecyclerView when a ViewHolder is present in both before and after the
* layout and RecyclerView has not received a {@link Adapter#notifyItemChanged(int)} call
* for it or a {@link Adapter#notifyDataSetChanged()} call.
* <p>
* This ViewHolder still represents the same data that it was representing when the layout
* started but its position / size may be changed by the LayoutManager.
* <p>
* If the Item's layout position didn't change, RecyclerView still calls this method because
* it does not track this information (or does not necessarily know that an animation is
* not required). Your ItemAnimator should handle this case and if there is nothing to
* animate, it should call {@link #dispatchAnimationFinished(ViewHolder)} and return
* <code>false</code>.
* <p>
* ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} when the animation
* is complete (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it
* decides not to animate the view).
*
* @param viewHolder The ViewHolder which should be animated
* @param preLayoutInfo The information that was returned from
* {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
* @param postLayoutInfo The information that was returned from {@link
* #recordPreLayoutInformation(State, ViewHolder, int, List)}.
*
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
**/
public abstract boolean animatePersistence(@NonNull ViewHolder viewHolder,
@NonNull ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo);
/**
* Called by the RecyclerView when an adapter item is present both before and after the
* layout and RecyclerView has received a {@link Adapter#notifyItemChanged(int)} call
* for it. This method may also be called when
* {@link Adapter#notifyDataSetChanged()} is called and adapter has stable ids so that
* RecyclerView could still rebind views to the same ViewHolders. If viewType changes when
* {@link Adapter#notifyDataSetChanged()} is called, this method <b>will not</b> be called,
* instead, {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)} will be
* called for the new ViewHolder and the old one will be recycled.
* <p>
* If this method is called due to a {@link Adapter#notifyDataSetChanged()} call, there is
* a good possibility that item contents didn't really change but it is rebound from the
* adapter. {@link DefaultItemAnimator} will skip animating the View if its location on the
* screen didn't change and your animator should handle this case as well and avoid creating
* unnecessary animations.
* <p>
* When an item is updated, ItemAnimator has a chance to ask RecyclerView to keep the
* previous presentation of the item as-is and supply a new ViewHolder for the updated
* presentation (see: {@link #canReuseUpdatedViewHolder(ViewHolder, List)}.
* This is useful if you don't know the contents of the Item and would like
* to cross-fade the old and the new one ({@link DefaultItemAnimator} uses this technique).
* <p>
* When you are writing a custom item animator for your layout, it might be more performant
* and elegant to re-use the same ViewHolder and animate the content changes manually.
* <p>
* When {@link Adapter#notifyItemChanged(int)} is called, the Item's view type may change.
* If the Item's view type has changed or ItemAnimator returned <code>false</code> for
* this ViewHolder when {@link #canReuseUpdatedViewHolder(ViewHolder, List)} was called, the
* <code>oldHolder</code> and <code>newHolder</code> will be different ViewHolder instances
* which represent the same Item. In that case, only the new ViewHolder is visible
* to the LayoutManager but RecyclerView keeps old ViewHolder attached for animations.
* <p>
* ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} for each distinct
* ViewHolder when their animation is complete
* (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it decides not to
* animate the view).
* <p>
* If oldHolder and newHolder are the same instance, you should call
* {@link #dispatchAnimationFinished(ViewHolder)} <b>only once</b>.
* <p>
* Note that when a ViewHolder both changes and disappears in the same layout pass, the
* animation callback method which will be called by the RecyclerView depends on the
* ItemAnimator's decision whether to re-use the same ViewHolder or not, and also the
* LayoutManager's decision whether to layout the changed version of a disappearing
* ViewHolder or not. RecyclerView will call
* {@code animateChange} instead of
* {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateDisappearance} if and only if the ItemAnimator returns {@code false} from
* {@link #canReuseUpdatedViewHolder(ViewHolder) canReuseUpdatedViewHolder} and the
* LayoutManager lays out a new disappearing view that holds the updated information.
* Built-in LayoutManagers try to avoid laying out updated versions of disappearing views.
*
* @param oldHolder The ViewHolder before the layout is started, might be the same
* instance with newHolder.
* @param newHolder The ViewHolder after the layout is finished, might be the same
* instance with oldHolder.
* @param preLayoutInfo The information that was returned from
* {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
* @param postLayoutInfo The information that was returned from {@link
* #recordPreLayoutInformation(State, ViewHolder, int, List)}.
*
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
**/
public abstract boolean animateChange(@NonNull ViewHolder oldHolder,
@NonNull ViewHolder newHolder,
@NonNull ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo);
@AdapterChanges
static int buildAdapterChangeFlagsForAnimations(ViewHolder viewHolder) {
int flags = viewHolder.mFlags & (FLAG_INVALIDATED | FLAG_REMOVED | FLAG_CHANGED);
if (viewHolder.isInvalid()) {
return FLAG_INVALIDATED;
}
if ((flags & FLAG_INVALIDATED) == 0) {
final int oldPos = viewHolder.getOldPosition();
final int pos = viewHolder.getAdapterPosition();
if (oldPos != NO_POSITION && pos != NO_POSITION && oldPos != pos) {
flags |= FLAG_MOVED;
}
}
return flags;
}
/**
* Called when there are pending animations waiting to be started. This state
* is governed by the return values from
* {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateAppearance()},
* {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateChange()}
* {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animatePersistence()}, and
* {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateDisappearance()}, which inform the RecyclerView that the ItemAnimator wants to be
* called later to start the associated animations. runPendingAnimations() will be scheduled
* to be run on the next frame.
**/
public abstract void runPendingAnimations();
/**
* Method called when an animation on a view should be ended immediately.
* This could happen when other events, like scrolling, occur, so that
* animating views can be quickly put into their proper end locations.
* Implementations should ensure that any animations running on the item
* are canceled and affected properties are set to their end values.
* Also, {@link #dispatchAnimationFinished(ViewHolder)} should be called for each finished
* animation since the animations are effectively done when this method is called.
*
* @param item The item for which an animation should be stopped.
**/
public abstract void endAnimation(ViewHolder item);
/**
* Method called when all item animations should be ended immediately.
* This could happen when other events, like scrolling, occur, so that
* animating views can be quickly put into their proper end locations.
* Implementations should ensure that any animations running on any items
* are canceled and affected properties are set to their end values.
* Also, {@link #dispatchAnimationFinished(ViewHolder)} should be called for each finished
* animation since the animations are effectively done when this method is called.
**/
public abstract void endAnimations();
/**
* Method which returns whether there are any item animations currently running.
* This method can be used to determine whether to delay other actions until
* animations end.
*
* @return true if there are any item animations currently running, false otherwise.
**/
public abstract boolean isRunning();
/**
* Method to be called by subclasses when an animation is finished.
* <p>
* For each call RecyclerView makes to
* {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateAppearance()},
* {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animatePersistence()}, or
* {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateDisappearance()}, there
* should
* be a matching {@link #dispatchAnimationFinished(ViewHolder)} call by the subclass.
* <p>
* For {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateChange()}, subclass should call this method for both the <code>oldHolder</code>
* and <code>newHolder</code> (if they are not the same instance).
*
* @param viewHolder The ViewHolder whose animation is finished.
* @see #onAnimationFinished(ViewHolder)
**/
public final void dispatchAnimationFinished(ViewHolder viewHolder) {
onAnimationFinished(viewHolder);
if (mListener != null) {
mListener.onAnimationFinished(viewHolder);
}
}
/**
* Called after {@link #dispatchAnimationFinished(ViewHolder)} is called by the
* ItemAnimator.
*
* @param viewHolder The ViewHolder whose animation is finished. There might still be other
* animations running on this ViewHolder.
* @see #dispatchAnimationFinished(ViewHolder)
**/
public void onAnimationFinished(ViewHolder viewHolder) {
}
/**
* Method to be called by subclasses when an animation is started.
* <p>
* For each call RecyclerView makes to
* {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateAppearance()},
* {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animatePersistence()}, or
* {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateDisappearance()}, there should be a matching
* {@link #dispatchAnimationStarted(ViewHolder)} call by the subclass.
* <p>
* For {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
* animateChange()}, subclass should call this method for both the <code>oldHolder</code>
* and <code>newHolder</code> (if they are not the same instance).
* <p>
* If your ItemAnimator decides not to animate a ViewHolder, it should call
* {@link #dispatchAnimationFinished(ViewHolder)} <b>without</b> calling
* {@link #dispatchAnimationStarted(ViewHolder)}.
*
* @param viewHolder The ViewHolder whose animation is starting.
* @see #onAnimationStarted(ViewHolder)
**/
public final void dispatchAnimationStarted(ViewHolder viewHolder) {
onAnimationStarted(viewHolder);
}
/**
* Called when a new animation is started on the given ViewHolder.
*
* @param viewHolder The ViewHolder which started animating. Note that the ViewHolder
* might already be animating and this might be another animation.
* @see #dispatchAnimationStarted(ViewHolder)
**/
public void onAnimationStarted(ViewHolder viewHolder) {
}
/**
* Like {@link #isRunning()}, this method returns whether there are any item
* animations currently running. Additionally, the listener passed in will be called
* when there are no item animations running, either immediately (before the method
* returns) if no animations are currently running, or when the currently running
* animations are {@link #dispatchAnimationsFinished() finished}.
*
* <p>Note that the listener is transient - it is either called immediately and not
* stored at all, or stored only until it is called when running animations
* are finished sometime later.</p>
*
* @param listener A listener to be called immediately if no animations are running
* or later when currently-running animations have finished. A null listener is
* equivalent to calling {@link #isRunning()}.
* @return true if there are any item animations currently running, false otherwise.
**/
public final boolean isRunning(ItemAnimatorFinishedListener listener) {
boolean running = isRunning();
if (listener != null) {
if (!running) {
listener.onAnimationsFinished();
} else {
mFinishedListeners.add(listener);
}
}
return running;
}
/**
* When an item is changed, ItemAnimator can decide whether it wants to re-use
* the same ViewHolder for animations or RecyclerView should create a copy of the
* item and ItemAnimator will use both to run the animation (e.g. cross-fade).
* <p>
* Note that this method will only be called if the {@link ViewHolder} still has the same
* type ({@link Adapter#getItemViewType(int)}). Otherwise, ItemAnimator will always receive
* both {@link ViewHolder}s in the
* {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)} method.
* <p>
* If your application is using change payloads, you can override
* {@link #canReuseUpdatedViewHolder(ViewHolder, List)} to decide based on payloads.
*
* @param viewHolder The ViewHolder which represents the changed item's old content.
*
* @return True if RecyclerView should just rebind to the same ViewHolder or false if
* RecyclerView should create a new ViewHolder and pass this ViewHolder to the
* ItemAnimator to animate. Default implementation returns <code>true</code>.
*
* @see #canReuseUpdatedViewHolder(ViewHolder, List)
**/
public boolean canReuseUpdatedViewHolder(@NonNull ViewHolder viewHolder) {
return true;
}
/**
* When an item is changed, ItemAnimator can decide whether it wants to re-use
* the same ViewHolder for animations or RecyclerView should create a copy of the
* item and ItemAnimator will use both to run the animation (e.g. cross-fade).
* <p>
* Note that this method will only be called if the {@link ViewHolder} still has the same
* type ({@link Adapter#getItemViewType(int)}). Otherwise, ItemAnimator will always receive
* both {@link ViewHolder}s in the
* {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)} method.
*
* @param viewHolder The ViewHolder which represents the changed item's old content.
* @param payloads A non-null list of merged payloads that were sent with change
* notifications. Can be empty if the adapter is invalidated via
* {@link RecyclerView.Adapter#notifyDataSetChanged()}. The same list of
* payloads will be passed into
* {@link RecyclerView.Adapter#onBindViewHolder(ViewHolder, int, List)}
* method <b>if</b> this method returns <code>true</code>.
*
* @return True if RecyclerView should just rebind to the same ViewHolder or false if
* RecyclerView should create a new ViewHolder and pass this ViewHolder to the
* ItemAnimator to animate. Default implementation calls
* {@link #canReuseUpdatedViewHolder(ViewHolder)}.
*
* @see #canReuseUpdatedViewHolder(ViewHolder)
**/
public boolean canReuseUpdatedViewHolder(@NonNull ViewHolder viewHolder,
@NonNull List<Object> payloads) {
return canReuseUpdatedViewHolder(viewHolder);
}
/**
* This method should be called by ItemAnimator implementations to notify
* any listeners that all pending and active item animations are finished.
**/
public final void dispatchAnimationsFinished() {
final int count = mFinishedListeners.size();
for (int i = 0; i < count; ++i) {
mFinishedListeners.get(i).onAnimationsFinished();
}
mFinishedListeners.clear();
}
/**
* Returns a new {@link ItemHolderInfo} which will be used to store information about the
* ViewHolder. This information will later be passed into <code>animate**</code> methods.
* <p>
* You can override this method if you want to extend {@link ItemHolderInfo} and provide
* your own instances.
*
* @return A new {@link ItemHolderInfo}.
**/
public ItemHolderInfo obtainHolderInfo() {
return new ItemHolderInfo();
}
/**
* The interface to be implemented by listeners to animation events from this
* ItemAnimator. This is used internally and is not intended for developers to
* create directly.
**/
interface ItemAnimatorListener {
void onAnimationFinished(ViewHolder item);
}
/**
* This interface is used to inform listeners when all pending or running animations
* in an ItemAnimator are finished. This can be used, for example, to delay an action
* in a data set until currently-running animations are complete.
*
* @see #isRunning(ItemAnimatorFinishedListener)
**/
public interface ItemAnimatorFinishedListener {
/**
* Notifies when all pending or running animations in an ItemAnimator are finished.
**/
void onAnimationsFinished();
}
/**
* A simple data structure that holds information about an item's bounds.
* This information is used in calculating item animations. Default implementation of
* {@link #recordPreLayoutInformation(RecyclerView.State, ViewHolder, int, List)} and
* {@link #recordPostLayoutInformation(RecyclerView.State, ViewHolder)} returns this data
* structure. You can extend this class if you would like to keep more information about
* the Views.
* <p>
* If you want to provide your own implementation but still use `super` methods to record
* basic information, you can override {@link #obtainHolderInfo()} to provide your own
* instances.
**/
public static class ItemHolderInfo {
/**
* The left edge of the View (excluding decorations)
**/
public int left;
/**
* The top edge of the View (excluding decorations)
**/
public int top;
/**
* The right edge of the View (excluding decorations)
**/
public int right;
/**
* The bottom edge of the View (excluding decorations)
**/
public int bottom;
/**
* The change flags that were passed to
* {@link #recordPreLayoutInformation(RecyclerView.State, ViewHolder, int, List)}.
**/
@AdapterChanges
public int changeFlags;
public ItemHolderInfo() {
}
/**
* Sets the {@link #left}, {@link #top}, {@link #right} and {@link #bottom} values from
* the given ViewHolder. Clears all {@link #changeFlags}.
*
* @param holder The ViewHolder whose bounds should be copied.
* @return This {@link ItemHolderInfo}
**/
public ItemHolderInfo setFrom(RecyclerView.ViewHolder holder) {
return setFrom(holder, 0);
}
/**
* Sets the {@link #left}, {@link #top}, {@link #right} and {@link #bottom} values from
* the given ViewHolder and sets the {@link #changeFlags} to the given flags parameter.
*
* @param holder The ViewHolder whose bounds should be copied.
* @param flags The adapter change flags that were passed into
* {@link #recordPreLayoutInformation(RecyclerView.State, ViewHolder, int,
* List)}.
* @return This {@link ItemHolderInfo}
**/
public ItemHolderInfo setFrom(RecyclerView.ViewHolder holder,
@AdapterChanges int flags) {
final View view = holder.itemView;
this.left = view.getLeft();
this.top = view.getTop();
this.right = view.getRight();
this.bottom = view.getBottom();
return this;
}
}
}
@Override
protected int getChildDrawingOrder(int childCount, int i) {
if (mChildDrawingOrderCallback == null) {
return super.getChildDrawingOrder(childCount, i);
} else {
return mChildDrawingOrderCallback.onGetChildDrawingOrder(childCount, i);
}
}
/**
* A callback interface that can be used to alter the drawing order of RecyclerView children.
* <p>
* It works using the {@link ViewGroup#getChildDrawingOrder(int, int)} method, so any case
* that applies to that method also applies to this callback. For example, changing the drawing
* order of two views will not have any effect if their elevation values are different since
* elevation overrides the result of this callback.
**/
public interface ChildDrawingOrderCallback {
/**
* Returns the index of the child to draw for this iteration. Override this
* if you want to change the drawing order of children. By default, it
* returns i.
*
* @param i The current iteration.
* @return The index of the child to draw this iteration.
*
* @see RecyclerView#setChildDrawingOrderCallback(RecyclerView.ChildDrawingOrderCallback)
**/
int onGetChildDrawingOrder(int childCount, int i);
}
private NestedScrollingChildHelper getScrollingChildHelper() {
if (mScrollingChildHelper == null) {
mScrollingChildHelper = new NestedScrollingChildHelper(this);
}
return mScrollingChildHelper;
}
}
| [
"2994734692@qq.com"
] | 2994734692@qq.com |
a4d66adfc9719c47e3f8da2333521d61a39d4d2d | d158f0854e9fcfe7720aec1e2fc7610bf6c61b96 | /src/tk/bolovsrol/utils/containers/Lazy.java | 9e29c7582c2ce1b94cd581600452b19f24862f7d | [] | no_license | sellsky/utils2 | 55fea0f7eb9867528d995a07a39a44ece2801771 | 0f8f1db7d3bde1fbd1a8290bc265d8ab1c02ce70 | refs/heads/master | 2020-05-24T00:36:52.307853 | 2019-05-17T09:52:41 | 2019-05-17T09:52:41 | 187,018,868 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 997 | java | package tk.bolovsrol.utils.containers;
import java.util.function.Supplier;
/**
* Простейший контейнер с ленивой инициализацией. Выполняет инициализацию при первом {@link #get()}.
*
* @param <O>
*/
public class Lazy<O> {
private O value;
private final Supplier<O> supplier;
public Lazy(Supplier<O> supplier) {
this.supplier = supplier;
}
public O get() {
if (value == null) {
value = supplier.get();
}
return value;
}
/**
* @return инициализированное значение либо нул, если значение не было инициализировано
*/
public O peek() {
return value;
}
public boolean isInitialized() {
return value != null;
}
public boolean isEmpty() {
return value == null;
}
public void reset() {
this.value = null;
}
}
| [
"kosmonavt.panchenko@gmail.com"
] | kosmonavt.panchenko@gmail.com |
24d57aa99d5b6308d7ba467b9aadeac5d41e36d0 | 0e06e096a9f95ab094b8078ea2cd310759af008b | /sources/com/tapjoy/internal/cv.java | 6006dddfb3538760a93927abfcfd21f1433efe4f | [] | no_license | Manifold0/adcom_decompile | 4bc2907a057c73703cf141dc0749ed4c014ebe55 | fce3d59b59480abe91f90ba05b0df4eaadd849f7 | refs/heads/master | 2020-05-21T02:01:59.787840 | 2019-05-10T00:36:27 | 2019-05-10T00:36:27 | 185,856,424 | 1 | 2 | null | 2019-05-10T00:36:28 | 2019-05-09T19:04:28 | Java | UTF-8 | Java | false | false | 283 | java | package com.tapjoy.internal;
import java.util.Collection;
public final class cv {
/* renamed from: a */
static final cq f7299a = new cq(", ");
/* renamed from: a */
public static Collection m7342a(Iterable iterable) {
return (Collection) iterable;
}
}
| [
"querky1231@gmail.com"
] | querky1231@gmail.com |
fbe6a9c073303953b53ce9e91e0b69d0df5440d2 | 9d5b328b00994228ee7d03105855e8a3ee3f395d | /app/src/main/java/com/fh/miltec/AdapterMensagem.java | 0e39f598872a717761655e29dc8975cb95bf3304 | [] | no_license | Regis-Dias/Android-fishing-here | f1cb76ec75fccd96aa33cd961f7b6550878f94ae | 35a64fd33f4f14edb58ebe87a390dc4b511897e7 | refs/heads/master | 2023-01-07T23:29:00.161263 | 2020-09-02T14:09:17 | 2020-09-02T14:09:17 | 288,763,564 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,388 | java | package com.fh.miltec;
import android.content.Context;
import android.content.res.TypedArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import fh.miltec.model.Mensagem;
public class AdapterMensagem extends ArrayAdapter<Mensagem> {
public Context context;
public TypedArray imagens;
public ArrayList<Mensagem> mensagens;
AdapterMensagem(Context c, ArrayList<Mensagem> msgs, TypedArray imgs){
super(c, R.layout.activity_item_mensagem, R.id.txt1, msgs);
this.context = c;
this.imagens = imgs;
this.mensagens = msgs;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.activity_item_mensagem,parent,false);
ImageView images = (ImageView) row.findViewById(R.id.icon);
TextView textoMensagem = (TextView) row.findViewById(R.id.txt1);
images.setImageResource(imagens.getResourceId(position, - 1));
textoMensagem.setText(mensagens.get(position).getMensagem());
return row;
}
}
| [
"rsdias@fazenda.ms.gov.br"
] | rsdias@fazenda.ms.gov.br |
f4e5e9d1a73b5c30a75aa049f383e98500a81a92 | 3e773c007574037d4146db4bec40558be1d3ad2b | /Source/Server/src/main/java/handler/CpuUsageChartHandler.java | 4fb9f8cd7a4997245689d82f7eeb450426a3b612 | [] | no_license | TK-Wensday-1115/AndroidMonitoring | b2d6a289716e890a9518fb50789ade52bb18213d | 8a77d5e1a427f1d9b120f4a2a6c774b6b0581f3c | refs/heads/master | 2020-12-24T21:11:56.688519 | 2016-06-08T09:28:06 | 2016-06-08T09:28:06 | 59,050,550 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,122 | java | package handler;
import pl.edu.agh.student.smialek.tk.communications.server.SensorReading;
import pl.edu.agh.toik.historychart.DataLineDoesNotExistException;
import pl.edu.agh.toik.historychart.HistoryChart;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Maciej Imiolek on 2016-06-06.
*/
public class CpuUsageChartHandler implements IChartHandler {
private final HistoryChart chart;
private Map<String, Integer> cpuUsages;
public CpuUsageChartHandler(HistoryChart chart) {
this.chart = chart;
this.cpuUsages = new HashMap<>();
}
@Override
public void addReading(SensorReading reading) {
if (!cpuUsages.containsKey(reading.getColor())) {
cpuUsages.put(reading.getColor(), chart.registerNewLine(reading.getColor()));
}
int lineId = cpuUsages.get(reading.getColor());
try {
chart.addNewEntry(lineId, Double.parseDouble(reading.getValue()), Date.from(reading.getTimestamp()));
} catch (DataLineDoesNotExistException e) {
e.printStackTrace();
}
}
}
| [
"maciej.imiolek@gmail.com"
] | maciej.imiolek@gmail.com |
78b115ba4e0d68ce295a34d064f0313f17c2a3f8 | 323e4a1a7a5a4d2c4412ad9a4ec76b8d52a175b4 | /testeCalculo2.java | 6572fc3ab220ebea8a9164b72b50d9fabaf05ecb | [] | no_license | Leandro-Peres/Aula7 | fdf9663458603b9d802eccd8068e363c1350f5a6 | 127b47c95cb0fb1efd000ba24c8da1a320083d0b | refs/heads/master | 2022-11-09T09:50:26.730105 | 2020-06-22T21:01:10 | 2020-06-22T21:01:10 | 274,195,673 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 839 | java |
public class testeCalculo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Calculo2 calc1 = new Calculo2(); //calc1 = objeto
calc1.setNumero1(20); //chamar método
calc1.setNumero2(5); //chamar método
System.out.println("Número 1 = " + calc1.getNumero1());
System.out.println("Número 2 = " + calc1.getNumero1());
calc1.exibirSoma();
System.out.println("Resultado 2 = " + calc1.exibeSoma2());
calc1.exibeSubtracao();
System.out.println("Resultado Subtracao = " + calc1.exibeSubtracao());
calc1.exibeMultiplicacao();
System.out.println("Resultado Multiplição = " + calc1.exibeMultiplicacao());
calc1.exibeDivisao();
System.out.println("Resultado Divisão = " + calc1.exibeDivisao());
}
}
| [
"noreply@github.com"
] | Leandro-Peres.noreply@github.com |
df61faa83f4aaf95e8f5fed4bb8daf0d66dcc8c5 | c286f4867c1fafd2f66febc16d4dfd7a693e7ffb | /core/src/test/java/fixio/fixprotocol/FixMessageBuilderImplTest.java | 83381fda67c7acd79d05856d05f895fdb7725420 | [
"Apache-2.0"
] | permissive | barchart/fixio | 3abcc83db44121426f12450385365b0678dca0b3 | 1b4ddeca78f123f46b1b04902e3a686d961df7f6 | refs/heads/master | 2023-03-18T07:48:02.937808 | 2015-10-13T21:04:37 | 2015-10-13T21:04:37 | 21,871,059 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,193 | java | /*
* Copyright 2014 The FIX.io Project
*
* The FIX.io Project licenses this file to you 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 fixio.fixprotocol;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Random;
import static org.apache.commons.lang3.RandomStringUtils.randomAscii;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
public class FixMessageBuilderImplTest {
private static final Random RANDOM = new Random();
private FixMessageBuilderImpl fixMessage;
@Before
public void setUp() throws Exception {
fixMessage = new FixMessageBuilderImpl();
}
@Test
public void testHeaderFields() {
String beginString = randomAscii(2);
String senderCompID = randomAscii(3);
String targetCompID = randomAscii(4);
String msgType = randomAscii(5);
fixMessage.getHeader().setBeginString(beginString);
fixMessage.setMessageType(msgType);
fixMessage.getHeader().setSenderCompID(senderCompID);
fixMessage.getHeader().setTargetCompID(targetCompID);
assertEquals("beginString", beginString, fixMessage.getHeader().getBeginString());
assertEquals("msgType", msgType, fixMessage.getMessageType());
assertEquals("senderCompID", senderCompID, fixMessage.getHeader().getSenderCompID());
assertEquals("targetCompID", targetCompID, fixMessage.getHeader().getTargetCompID());
}
@Test
public void testWithGroups() {
String clientOrderId = randomAscii(4);
String quoteRequestId = randomAscii(3);
FixMessageBuilderImpl quoteRequest = new FixMessageBuilderImpl(MessageTypes.QUOTE_REQUEST);
quoteRequest.add(FieldType.QuoteReqID, quoteRequestId);
quoteRequest.add(FieldType.ClOrdID, clientOrderId);
Group instrument1 = quoteRequest.newGroup(FieldType.NoRelatedSym, 2);
instrument1.add(FieldType.Symbol, "EUR/USD");
instrument1.add(FieldType.SecurityType, "CURRENCY");
Group instrument2 = quoteRequest.newGroup(FieldType.NoRelatedSym);
instrument2.add(FieldType.Symbol, "EUR/CHF");
instrument2.add(FieldType.SecurityType, "CURRENCY");
quoteRequest.add(FieldType.QuoteRequestType, 2); //QuoteRequestType=AUTOMATIC
// read
List<Group> instruments = quoteRequest.getGroups(146);
assertEquals(2, instruments.size());
assertSame(instrument1, instruments.get(0));
assertSame(instrument2, instruments.get(1));
}
@Test
public void testAddStringByTypeAndTag() {
String value = randomAscii(3);
int tagNum = new Random().nextInt(100) + 100;
FixMessageBuilderImpl messageBuilder = new FixMessageBuilderImpl();
assertSame(messageBuilder, messageBuilder.add(DataType.STRING, tagNum, value));
assertEquals(value, messageBuilder.getString(tagNum));
}
@Test
public void testAddIntByTypeAndTag() {
int value = RANDOM.nextInt(1000);
int tagNum = RANDOM.nextInt(100) + 100;
FixMessageBuilderImpl messageBuilder = new FixMessageBuilderImpl();
assertSame(messageBuilder, messageBuilder.add(DataType.LENGTH, tagNum, value));
assertEquals((Integer) value, messageBuilder.getInt(tagNum));
}
@Test
public void testAddIntByTag() {
int value = RANDOM.nextInt(1000);
FieldType tag = FieldType.MsgSeqNum;
FixMessageBuilderImpl messageBuilder = new FixMessageBuilderImpl();
assertSame(messageBuilder, messageBuilder.add(tag, value));
assertEquals((Integer) value, messageBuilder.getInt(tag));
}
}
| [
"kpavlov@dev.null"
] | kpavlov@dev.null |
3450263b6c195a59a2842157ecd888c1e788b26d | 2e040ea5d29548c47f6c87628209db02166465a9 | /src/main/java/polymorphism/LgTV.java | 3c0f99b584bb8c042470958446ed28e6c0003332 | [] | no_license | owner0gn/BoardWeb | 427062a3973b41bc8e81533e3073fa12aa74be66 | 5d729c1863140489ff524e15cb1d5876f0c654fc | refs/heads/master | 2020-04-21T15:58:12.052949 | 2019-02-11T06:27:59 | 2019-02-11T06:27:59 | 169,685,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 453 | java | package polymorphism;
public class LgTV implements TV {
public LgTV() {
System.out.println("===> LgTV Object be created");
}
public void powerOn() {
System.out.println("LgTV---power on.");
}
public void powerOff() {
System.out.println("LgTV---power off.");
}
public void volumeUp() {
System.out.println("LgTV---volume up.");
}
public void volumeDown() {
System.out.println("LgTV---volume down.");
}
}
| [
"owner0gn@gmail.com"
] | owner0gn@gmail.com |
0926413b7fe9099d5c02a7b455926ca8c7b7c636 | 0f2c008898c5cb261df1604181fd1e1bb0e59112 | /bi-webservice/src/main/java/com/chengfeng/common/util/Loggerlevel.java | 13231585a78e3f722209bed196f3f93dcc84806d | [] | no_license | konglingjuanyi/bi-webservice | 179e218c62a9b5e03f35c3205209e42377edf45c | aa3514017cfc5408e792f590d40e4821c2a1e0e9 | refs/heads/master | 2021-01-22T08:06:59.627743 | 2016-03-24T09:32:16 | 2016-03-24T09:32:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 312 | java | package com.chengfeng.common.util;
/**
* 功能描述: 日志等级
* Copyright: Copyright (c) 2013
* Company:
* @author zwczhangwencong@163.com
* @version 1.0 2013-12-5下午1:27:18
* @see
* HISTORY
* 2013-12-5
*/
public enum Loggerlevel {
FATAL,
ERROR,
WARN,
INFO,
DEBUG
}
| [
"569039428@qq.com"
] | 569039428@qq.com |
8e148a1dc16f4969b23752f687933c7e47fdb7e2 | 995fccc3026fa474da6af9cb87237ba4640a25e9 | /src/main/java/com/lothrazar/cyclicmagic/module/EnchantModule.java | 06a4333306607467f12b5820352aec7e4a884582 | [
"MIT"
] | permissive | Aemande123/Cyclic | 51c8f9d9068c95783dbb6c426e28e86a26bd58b5 | f457d243104ab2495b06f7acca0fda453b401145 | refs/heads/master | 2021-04-09T16:19:24.329957 | 2018-03-18T03:24:45 | 2018-03-18T03:24:45 | 99,875,313 | 0 | 0 | null | 2017-08-10T03:06:18 | 2017-08-10T03:06:18 | null | UTF-8 | Java | false | false | 6,544 | java | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (C) 2014-2018 Sam Bassett (aka Lothrazar)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package com.lothrazar.cyclicmagic.module;
import com.lothrazar.cyclicmagic.config.IHasConfig;
import com.lothrazar.cyclicmagic.data.Const;
import com.lothrazar.cyclicmagic.enchantment.EnchantAutoSmelt;
import com.lothrazar.cyclicmagic.enchantment.EnchantBase;
import com.lothrazar.cyclicmagic.enchantment.EnchantBeheading;
import com.lothrazar.cyclicmagic.enchantment.EnchantExcavation;
import com.lothrazar.cyclicmagic.enchantment.EnchantLaunch;
import com.lothrazar.cyclicmagic.enchantment.EnchantLifeLeech;
import com.lothrazar.cyclicmagic.enchantment.EnchantMagnet;
import com.lothrazar.cyclicmagic.enchantment.EnchantMultishot;
import com.lothrazar.cyclicmagic.enchantment.EnchantQuickdraw;
import com.lothrazar.cyclicmagic.enchantment.EnchantReach;
import com.lothrazar.cyclicmagic.enchantment.EnchantVenom;
import com.lothrazar.cyclicmagic.enchantment.EnchantWaterwalking;
import com.lothrazar.cyclicmagic.enchantment.EnchantXpBoost;
import com.lothrazar.cyclicmagic.registry.EnchantRegistry;
import net.minecraftforge.common.config.Configuration;
public class EnchantModule extends BaseModule implements IHasConfig {
public static EnchantLaunch launch;
public static EnchantMagnet magnet;
public static EnchantVenom venom;
public static EnchantLifeLeech lifeleech;
public static EnchantAutoSmelt autosmelt;
public static EnchantXpBoost xpboost;
public static EnchantReach reach;
public static EnchantBeheading beheading;
public static EnchantQuickdraw quickdraw;
public static EnchantWaterwalking waterwalk;
private static EnchantExcavation excavation;
private boolean enablexpboost;
private boolean enableLaunch;
private boolean enableMagnet;
private boolean enableVenom;
private boolean enableLifeleech;
private boolean enableautosmelt;
private boolean enablereach;
private boolean enablebeheading;
private boolean enableQuickdraw;
private boolean enablewaterwalk;
private boolean enableExcavate;
private boolean enableMultishot;
private EnchantMultishot multishot;
@Override
public void onPreInit() {
super.onPreInit();
if (enablewaterwalk) {
waterwalk = new EnchantWaterwalking();
EnchantRegistry.register(waterwalk);
}
if (enablereach) {
reach = new EnchantReach();
EnchantRegistry.register(reach);
}
if (enablexpboost) {
xpboost = new EnchantXpBoost();
EnchantRegistry.register(xpboost);
}
if (enableautosmelt) {
autosmelt = new EnchantAutoSmelt();
EnchantRegistry.register(autosmelt);
}
if (enableLaunch) {
launch = new EnchantLaunch();
EnchantRegistry.register(launch);
}
if (enableMagnet) {
magnet = new EnchantMagnet();
EnchantRegistry.register(magnet);
}
if (enableVenom) {
venom = new EnchantVenom();
EnchantRegistry.register(venom);
}
if (enableLifeleech) {
lifeleech = new EnchantLifeLeech();
EnchantRegistry.register(lifeleech);
}
if (enablebeheading) {
beheading = new EnchantBeheading();
EnchantRegistry.register(beheading);
}
if (enableQuickdraw) {
quickdraw = new EnchantQuickdraw();
EnchantRegistry.register(quickdraw);
}
if (enableExcavate) {
excavation = new EnchantExcavation();
EnchantRegistry.register(excavation);
}
if (enableMultishot) {
multishot = new EnchantMultishot();
EnchantRegistry.register(multishot);
}
}
@Override
public void syncConfig(Configuration c) {
enableMultishot = c.getBoolean("EnchantMultishot", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enableExcavate = c.getBoolean("EnchantExcavation", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enablewaterwalk = c.getBoolean("EnchantWaterwalk", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enablereach = c.getBoolean("EnchantReach", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enablexpboost = c.getBoolean("EnchantExpBoost", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enableautosmelt = c.getBoolean("EnchantAutoSmelt", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enableLaunch = c.getBoolean("EnchantLaunch", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enableMagnet = c.getBoolean("EnchantMagnet", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enableVenom = c.getBoolean("EnchantVenom", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enableLifeleech = c.getBoolean("EnchantLifeLeech", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enablebeheading = c.getBoolean("EnchantBeheading", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
enableQuickdraw = c.getBoolean("EnchantQuickdraw", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText);
for (EnchantBase b : EnchantRegistry.enchants) {
if (b instanceof IHasConfig) {
((IHasConfig) b).syncConfig(c);
}
}
}
}
| [
"samson.bassett@gmail.com"
] | samson.bassett@gmail.com |
59104744cde7fbbff5377e80d573ef3adeee0263 | 0f75c551a193c546b3db7f57e70e36bf2c192552 | /bigdata-module/bigdata-tx-manager/src/main/java/com/bosssoft/bigdata/manager/redis/RedisServerService.java | d8f5f64611e8e2e46243fb60a8f35f80302fc9b0 | [] | no_license | coomia/big-parent | f4ca69a0afdcabdefbf243add9bb26755647010e | ab33f26a47dd363eb99a2053bd7af951346f8ae5 | refs/heads/master | 2020-05-27T23:18:28.295712 | 2019-04-25T00:54:52 | 2019-04-25T00:54:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 649 | java | package com.bosssoft.bigdata.manager.redis;
import java.util.List;
import com.bosssoft.bigdata.manager.netty.model.TxGroup;
/**
* @author LCN on 2019/11/11
*/
public interface RedisServerService {
String loadNotifyJson();
void saveTransaction(String key, String json);
TxGroup getTxGroupByKey(String key);
void saveCompensateMsg(String name, String json);
List<String> getKeys(String key);
List<String> getValuesByKeys(List<String> keys);
String getValueByKey(String key);
void deleteKey(String key);
void saveLoadBalance(String groupName, String key, String data);
String getLoadBalance(String groupName, String key);
}
| [
"975668939@qq.com"
] | 975668939@qq.com |
44498b7320e54ef7bdc012f23cf26c63eae9bbaa | a4bb516afc70689fa9a53ee9252ddc6a6a29de8c | /app/src/main/java/com/example/karol/turek/notes/ui/notes/INotesPresenter.java | c562273539a56dfee8e42fc635d9154d18e28e0b | [] | no_license | KarolTurek1988/Notes | 8bd6191f71f51258f4a3d3306c77aa35dfec4c2e | aec65aa7facada1fceac95bf8ccd7a73a9dd3cbe | refs/heads/master | 2021-01-19T17:52:28.683697 | 2017-04-15T12:13:35 | 2017-04-15T12:13:35 | 88,305,415 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 266 | java | package com.example.karol.turek.notes.ui.notes;
import com.example.karol.turek.notes.cache.ICache;
public interface INotesPresenter {
void getNotes();
ICache getCache();
void closeNotesList();
void onBindView(INotes view);
void unBindView();
}
| [
"karol.turek1988@gmail.com"
] | karol.turek1988@gmail.com |
94165cc3f07c3fe69c4edcc27aee8555353fa406 | 4f661a8588a8d47f1ce3d4631258699a1dfec238 | /src/main/java/fr/insalyon/dasi/proactifb3328/dao/ClientDao.java | ce5df0922d868f018a391970343356428d9335bb | [] | no_license | mariefrgon/DasiB33 | b5711280faea20fabfa6b725c2c83ccd1ad6f49f | f223b5ebce9528a3a286e15a2f303913dbab4cc5 | refs/heads/master | 2020-03-14T12:42:47.938560 | 2018-05-05T16:45:44 | 2018-05-05T16:45:44 | 131,617,938 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,081 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fr.insalyon.dasi.proactifb3328.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import modele.Client;
/**
*
* @author ebosca
*/
public class ClientDao {
public ClientDao() {
}
public void insererClient(Client c){
JpaUtil.obtenirEntityManager().persist(c);
}
public Client recupererClient(int id){
EntityManager em = JpaUtil.obtenirEntityManager();
Query query = em.createQuery("Select c from Client c where c.nClient = :id");
query.setParameter("id", id);
List<Client> resultats = (List<Client>) query.getResultList();
Client c = null;
try {
c = (Client) query.getSingleResult();
} catch (Exception e) {
}
return c;
}
}
| [
"eborghino@IF501-202-06.insa-lyon.fr"
] | eborghino@IF501-202-06.insa-lyon.fr |
6cae05dbfa45cf33a2b46d0d935eb92454c9a9bb | da76c1a98effcecedcfa29395444bb70b0e4ad5e | /lab7.com/common/lab/Position.java | fd9f8a29f1bb0c7faf3154e9d77ff964f00ac45c | [] | no_license | Septemberer/Lab7 | 4b890f535b4c9eed2875fb8e64baeaff16a10307 | 58e3c4d5c995fe0ec5781a6c538044d8ccf79cfa | refs/heads/main | 2023-06-01T01:55:26.850401 | 2021-06-18T12:23:58 | 2021-06-18T12:23:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 128 | java | package com.lab7.common.lab;
public enum Position {
NONE,
HEAD_OF_DIVISION,
COOK,
MANAGER_OF_CLEANING,
} | [
"noreply@github.com"
] | Septemberer.noreply@github.com |
483fa6101aa784e979da9b8bad8e59f2eab4e681 | 4417886f50f85f3348a44b417e57c1ecac9930a4 | /src/main/java/com/sliu/framework/app/wfw/model/ZsTsfl.java | 954d21e91be24c1f5a823b63f07fb53308056be8 | [] | no_license | itxiaojian/wechatpf | 1fcf2ecc783c36c5c84d8408d78639de22263bde | bdf2b36c9733b1125feabb5d078e84f51034f718 | refs/heads/master | 2021-01-19T20:55:50.196667 | 2017-04-19T02:20:35 | 2017-04-19T02:20:35 | 88,578,665 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,260 | java | package com.sliu.framework.app.wfw.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* 图书分类
* @author duanpeijun
* @version 创建时间:2015年6月9日 上午10:37:31
*/
@Entity
@Table(name = "ZS_TSFL")
public class ZsTsfl implements Serializable{
private Long id;//主键
private String zl;//种类
private Integer sl;//数量
private String bz;//备注
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "zl", nullable = true)
public String getZl() {
return zl;
}
public void setZl(String zl) {
this.zl = zl;
}
@Column(name = "sl", nullable = true)
public Integer getSl() {
return sl;
}
public void setSl(Integer sl) {
this.sl = sl;
}
@Column(name = "bz", length = 500, nullable = true)
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
}
| [
"2629690209@qq.com"
] | 2629690209@qq.com |
43ba70d1432242ee004af8b05c5f2815d0ae4b38 | 6792f9a37233cf537a897b8b38aca38eaf089037 | /src/main/java/com/tomek/gamevidence/dao/PlayerDaoImpl.java | 33afb5869b8147b23442e9d14cc45f184de5b0e6 | [] | no_license | jtomekcz/gameevidence | c675be8d1516c1d83790f1b6cb88447f8b6d56d5 | a8b961a51dc4793b8a00de4ff18ba46e972e8d25 | refs/heads/master | 2020-04-01T22:02:01.312302 | 2018-10-22T23:09:53 | 2018-10-22T23:09:53 | 153,687,846 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 661 | java | package com.tomek.gamevidence.dao;
import com.tomek.gamevidence.domain.Player;
import org.springframework.stereotype.Repository;
import javax.persistence.Query;
import java.util.List;
@Repository
public class PlayerDaoImpl extends AbstractDaoImpl implements PlayerDao {
@Override
public List<Player> getAllPlayers() {
StringBuilder sb = new StringBuilder(" FROM ");
sb.append(Player.class.getName());
sb.append(" WHERE validity.valid = :valid ");
sb.append(" ORDER BY winnersCount DESC");
Query query = entityManager.createQuery(sb.toString());
query.setParameter("valid", Boolean.TRUE);
return query.getResultList();
}
}
| [
"jan.tomek@arbes.com"
] | jan.tomek@arbes.com |
2c1dbd9d8f204056b3daafe23cd2bec2570cbc60 | cbea23d5e087a862edcf2383678d5df7b0caab67 | /aws-java-sdk-networkfirewall/src/main/java/com/amazonaws/services/networkfirewall/model/transform/RuleGroupResponseMarshaller.java | 9a032cb568cff014a67c0a51e9035139b75587d7 | [
"Apache-2.0"
] | permissive | phambryan/aws-sdk-for-java | 66a614a8bfe4176bf57e2bd69f898eee5222bb59 | 0f75a8096efdb4831da8c6793390759d97a25019 | refs/heads/master | 2021-12-14T21:26:52.580137 | 2021-12-03T22:50:27 | 2021-12-03T22:50:27 | 4,263,342 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,901 | java | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.networkfirewall.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.networkfirewall.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* RuleGroupResponseMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RuleGroupResponseMarshaller {
private static final MarshallingInfo<String> RULEGROUPARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RuleGroupArn").build();
private static final MarshallingInfo<String> RULEGROUPNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RuleGroupName").build();
private static final MarshallingInfo<String> RULEGROUPID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RuleGroupId").build();
private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build();
private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Type").build();
private static final MarshallingInfo<Integer> CAPACITY_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Capacity").build();
private static final MarshallingInfo<String> RULEGROUPSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RuleGroupStatus").build();
private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Tags").build();
private static final MarshallingInfo<Integer> CONSUMEDCAPACITY_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ConsumedCapacity").build();
private static final MarshallingInfo<Integer> NUMBEROFASSOCIATIONS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("NumberOfAssociations").build();
private static final RuleGroupResponseMarshaller instance = new RuleGroupResponseMarshaller();
public static RuleGroupResponseMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(RuleGroupResponse ruleGroupResponse, ProtocolMarshaller protocolMarshaller) {
if (ruleGroupResponse == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(ruleGroupResponse.getRuleGroupArn(), RULEGROUPARN_BINDING);
protocolMarshaller.marshall(ruleGroupResponse.getRuleGroupName(), RULEGROUPNAME_BINDING);
protocolMarshaller.marshall(ruleGroupResponse.getRuleGroupId(), RULEGROUPID_BINDING);
protocolMarshaller.marshall(ruleGroupResponse.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(ruleGroupResponse.getType(), TYPE_BINDING);
protocolMarshaller.marshall(ruleGroupResponse.getCapacity(), CAPACITY_BINDING);
protocolMarshaller.marshall(ruleGroupResponse.getRuleGroupStatus(), RULEGROUPSTATUS_BINDING);
protocolMarshaller.marshall(ruleGroupResponse.getTags(), TAGS_BINDING);
protocolMarshaller.marshall(ruleGroupResponse.getConsumedCapacity(), CONSUMEDCAPACITY_BINDING);
protocolMarshaller.marshall(ruleGroupResponse.getNumberOfAssociations(), NUMBEROFASSOCIATIONS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| [
""
] | |
304bb7cd1cee33483928ee50513290d694307263 | f2e3ad40fe5285ba74c25425892d9de0d537e283 | /main.java | f4167e1f98bfc8580adfa3f2c5a0f56954f9e5af | [] | no_license | bmaxwell99/proj06 | 2bda281ba80f6941903a9016336d5bd5df1df32d | 95bee5b28e0043ed3fc58a774e0c6d8c8167d0d3 | refs/heads/master | 2020-05-30T14:44:46.778429 | 2019-06-09T08:39:23 | 2019-06-09T08:39:23 | 189,798,718 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 398 | java |
/**
* Write a description of class Main here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Main
{
public static void Main(String[] args){
GenerateFractal genFract = new GenerateFractal();
GUI gui = new GUI(genFract);
Display display = new Display(genFract);
genFract.attach(display);
}
}
| [
"bmaxwell99@gmail.com"
] | bmaxwell99@gmail.com |
ebbc9f81fc78c817f6fc4d8ac2e0d11ba21643db | 331c835b92dbea86bb906e6e1661e7f3864e7dbd | /shop/shop/app/src/main/java/freaktemplate/shopping/utils/ConnectionDetector.java | acd29895b122b07e1285d3cd9c4d1a54c0dcc59f | [] | no_license | Karthikrajt/onlineshopping | 598d4da16fa483b4e3e273f96a23c7eb210a90a4 | ea71dae6ae999a660ccfd314edc03cc111b8ba61 | refs/heads/master | 2022-12-12T11:34:20.986425 | 2020-09-01T07:13:57 | 2020-09-01T07:13:57 | 291,921,151 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 780 | java | package siragu.shopping.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private final Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
for (NetworkInfo anInfo : info)
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
| [
"karthikrajt1@gmail.com"
] | karthikrajt1@gmail.com |
5b0cfd8e25a290f4704a45b4948c96995d213faf | 4216bbcdb0c499e2015650694eac5e80b46eb53f | /src/main/java/basketball/domain/Game.java | 264dbe81438bc034baa6c03b4d6fd286d6395e91 | [] | no_license | GingerMoon/basketball | 657bd7e154a68eeb62cd6ee40c6ccb1e92e9c3e4 | edd42456ad3600caa967e60b2c7b43bda96bd28f | refs/heads/master | 2016-08-12T22:20:01.532409 | 2016-02-14T03:30:40 | 2016-02-14T03:30:40 | 51,647,629 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,411 | java | package basketball.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
public class Game implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id = (long) -1;
@NotNull
Date date = new Date();
@NotNull
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<GameStaticalData> gameStaticalDataList = new ArrayList<GameStaticalData>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<GameStaticalData> getGameStaticalDatas() {
return gameStaticalDataList;
}
public void setGameStaticalDatas(List<GameStaticalData> gameStaticalDatas) {
this.gameStaticalDataList = gameStaticalDatas;
}
} | [
"376752150@qq.com"
] | 376752150@qq.com |
bdc03e0420d8092baee644408317cf6b951e7b46 | 6d323dd746230f0ae1b47fba097cf48ba653c083 | /00_testProject/src/testProject/Ex3_14.java | aec303ff93b35df53e96e37849ac2f7e50e17da4 | [] | no_license | stkddks/Java-kh_class | aee9b198eff3d601673e8ef199159e5fa1517464 | 0f160436e060c97464aa183a95d72698b0a422fc | refs/heads/master | 2023-01-10T05:19:50.805601 | 2020-11-10T09:34:36 | 2020-11-10T09:34:36 | 307,237,069 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 1,299 | java | package testProject;
public class Ex3_14 {
public static void main(String[] args) {
String str1 = "abc"; //스택
String str2 = new String("abc"); //힙 // String 타입의 변수 str2에 새롭게(new) String 객체를 생성하여 연결!
System.out.printf("\"abc\"==\"abc\" ? %b%n", "abc"=="abc");
System.out.printf(" str1==\"abc\" ? %b%n", str1=="abc");
System.out.printf(" str2==\"abc\" ? %b%n", str2=="abc");
System.out.printf("str1.equals(\"abc\") ? %b%n", str1.equals("abc"));
System.out.printf("str2.equals(\"abc\") ? %b%n", str2.equals("abc"));
System.out.printf("str2.equals(\"ABC\") ? %b%n", str2.equals("ABC"));
System.out.printf("str2.equalsIgnoreCase(\"ABC\") ? %b%n", str2.equalsIgnoreCase("ABC"));
}
}
// 문자열 비교
// 문자열을 비교할 떄는 무조건 equals를 쓸것
/*
*
* //구조체 : 다른 타입의 변수들의 묶음 자료형
//사용자 정의 자료형
class Student{
int age;
int score;
String name;
}
public class Stuent_Test {
public static void main(String[] args) {
Student s = new Student(); //우리가 만든 데이터 타입
s.age = 20;
s.score = 100;
s.name = "성연";
System.out.println(s.age + " / "+ s.score + " / " + s.name);
}
}
*/
| [
"user1@DESKTOP-O3A9LP8"
] | user1@DESKTOP-O3A9LP8 |
a7369f569f1a4961d94f8b9af3d1727c0fe0768e | 4c304a7a7aa8671d7d1b9353acf488fdd5008380 | /src/main/java/com/alipay/api/domain/AlipayOpenMiniDataVisitQueryModel.java | 4e70df809d05cddb714ce8c799ecf804df099167 | [
"Apache-2.0"
] | permissive | zhaorongxi/alipay-sdk-java-all | c658983d390e432c3787c76a50f4a8d00591cd5c | 6deda10cda38a25dcba3b61498fb9ea839903871 | refs/heads/master | 2021-02-15T19:39:11.858966 | 2020-02-16T10:44:38 | 2020-02-16T10:44:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,249 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 小程序当日访问数据查询
*
* @author auto create
* @since 1.0, 2019-06-12 12:04:36
*/
public class AlipayOpenMiniDataVisitQueryModel extends AlipayObject {
private static final long serialVersionUID = 3328637985599433164L;
/**
* 查询数据范围;APP_SUMMARY代表仅查询小程序的访问数据,AREA_DETAIL代表同时查询区域下该小程序的访问数据
*/
@ApiField("data_scope")
private String dataScope;
/**
* 国标六位省份行政区划编码,参考http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/;data_scope传入AREA_DETAIL时该参数有效,传空表示同时查询各省的访问数据,否则同时查询该省份行政区划下的各城市访问数据。
*/
@ApiField("province_code")
private String provinceCode;
public String getDataScope() {
return this.dataScope;
}
public void setDataScope(String dataScope) {
this.dataScope = dataScope;
}
public String getProvinceCode() {
return this.provinceCode;
}
public void setProvinceCode(String provinceCode) {
this.provinceCode = provinceCode;
}
}
| [
"ben.zy@antfin.com"
] | ben.zy@antfin.com |
103f4ceb375845dfd912c61df8b6495939f7977d | ae8590da201145feaf58e1574be00d8b4d5b86f9 | /src/com/android/cassandra/droidbargain/profile/MyDealsFragment.java | f06c478ee62a649f081aff6f2b213aa50c8aef34 | [] | no_license | ajithnadig/AndroidCassandra | c1f7e3af60665234d0f5ef28b507413eddf67a57 | be5afcabbb53dedfffaa45b1c01757dc61defa56 | refs/heads/master | 2021-01-17T08:54:15.010036 | 2013-07-14T04:09:06 | 2013-07-14T04:09:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,357 | java | package com.android.cassandra.droidbargain.profile;
import java.util.ArrayList;
import java.util.Collections;
import com.android.cassandra.droidbargain.R;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.cassandra.droidbargain.feed.DealFactory;
import com.android.cassandra.droidbargain.feed.FeedAdapter;
public class MyDealsFragment extends ListFragment {
ArrayList<DealFactory> myDeals;
private User bargain_user;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.activity_feed,container, false);
bargain_user = (User) getActivity().getIntent().getSerializableExtra("USER_PROFILE");
myDeals = Profile.user_deal_data;
if(myDeals != null){
Collections.sort(myDeals);
}
return rootView;
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
FeedAdapter adapter = new FeedAdapter(getActivity(), R.layout.feed_item, myDeals, bargain_user.getUser_ID());
setListAdapter(adapter);
setRetainInstance(true);
}
}
| [
"shehaaz@gmail.com"
] | shehaaz@gmail.com |
2378fdc64644810a212d88e55e286f67a5cbe120 | b59daa53bbb05d803d2c6abf6dcbbd89ab1c30fc | /testes/pdf2/teste.java | 083bfcbf00a252a3e3764a55b234b05c975f3def | [] | no_license | xmgio/PraticasGQS | a1779dadab0dfaf575211f0acec2e100d0b0f3e3 | 81176db71f836e99342d16e28b715a3a6cdf92e6 | refs/heads/main | 2023-06-04T13:50:40.120813 | 2021-06-19T00:51:08 | 2021-06-19T00:51:08 | 356,427,754 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 834 | java | package Teste;
import static org.junit.Assert.*;
import java.time.DayOfWeek;
import java.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
import TelaPrincipal.Main;
public class TesteMain {
Main verificarValorProduto;
@Before
public void setUp() throws Exception {
verificarValorProduto = new Main();
}
@Test
public void test() {
double total = 0.0;
boolean clienteVIP = false;
if (clienteVIP) {
total *= 0.90; }
else { total *= 0.95; }
DayOfWeek diaSemana = LocalDate.now().getDayOfWeek();
if (diaSemana == DayOfWeek.SUNDAY) {
total += 10.00; }
else { total += 5.00; }
assertEquals(total);
}
private void assertEquals(double total) {
// TODO Auto-generated method stub
}
} | [
"giovannagilmatos2@gmail.com"
] | giovannagilmatos2@gmail.com |
345ca6cd9e341d91c5cb6a53045152e3e2cbe4d9 | 183d057ee3f1255551c9f2bc6080dfcc23262639 | /app/src/main/java/com/cliffex/videomaker/videoeditor/introvd/template/p203b/p204a/C4573d.java | baa4bf4b01216bb3a94798d6ea50bd4ebb04656e | [] | no_license | datcoind/VideoMaker-1 | 5567ff713f771b19154ba463469b97d18d0164ec | bcd6697db53b1e76ee510e6e805e46b24a4834f4 | refs/heads/master | 2023-03-19T20:33:16.016544 | 2019-09-27T13:55:07 | 2019-09-27T13:55:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,719 | java | package com.introvd.template.p203b.p204a;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
/* renamed from: com.introvd.template.b.a.d */
public class C4573d extends Handler {
private final Queue<C4576e> bLu;
private final LayoutParams bLv;
/* renamed from: com.introvd.template.b.a.d$a */
private static class C4575a {
/* access modifiers changed from: private */
public static final C4573d bLz = new C4573d();
}
private C4573d() {
this.bLu = new LinkedBlockingQueue();
this.bLv = new LayoutParams();
}
/* renamed from: SD */
public static C4573d m11591SD() {
return C4575a.bLz;
}
/* renamed from: SE */
private void m11592SE() {
if (!this.bLu.isEmpty()) {
C4576e eVar = (C4576e) this.bLu.poll();
while (eVar != null) {
View anchorView = eVar.getAnchorView();
if (anchorView != null && !m11600ce(anchorView)) {
break;
}
this.bLu.poll();
eVar = (C4576e) this.bLu.peek();
}
if (eVar != null) {
if (!eVar.isShowing()) {
m11596a(eVar, 109528);
} else {
m11597a(eVar, 109527, m11593a(eVar));
}
}
}
}
/* renamed from: a */
private long m11593a(C4576e eVar) {
return eVar.mo24856SM() + eVar.mo24855SL();
}
/* access modifiers changed from: private */
/* renamed from: a */
public void m11596a(C4576e eVar, int i) {
Message obtainMessage = obtainMessage(i);
obtainMessage.obj = eVar;
sendMessage(obtainMessage);
}
/* access modifiers changed from: private */
/* renamed from: a */
public void m11597a(C4576e eVar, int i, long j) {
Message obtainMessage = obtainMessage(i);
obtainMessage.obj = eVar;
sendMessageDelayed(obtainMessage, j);
}
/* renamed from: b */
private void m11598b(final C4576e eVar) {
if (!eVar.isShowing()) {
final View contentView = eVar.getContentView();
if (!m11600ce(contentView)) {
try {
if (contentView.getParent() == null && !m11600ce(contentView)) {
contentView.setVisibility(4);
m11604h(eVar).addView(contentView, m11599c(eVar));
}
contentView.requestLayout();
ViewTreeObserver viewTreeObserver = contentView.getViewTreeObserver();
if (viewTreeObserver != null) {
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@TargetApi(16)
public void onGlobalLayout() {
contentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
C4573d.this.m11596a(eVar, 109529);
if (!eVar.mo24858SO()) {
C4573d.this.m11597a(eVar, 109530, eVar.mo24856SM() + eVar.mo24853SJ());
}
}
});
}
} catch (Exception unused) {
}
}
}
}
/* renamed from: c */
private LayoutParams m11599c(C4576e eVar) {
if (eVar != null) {
C4572c SN = eVar.mo24857SN();
this.bLv.x = SN.getX();
this.bLv.y = SN.getY();
this.bLv.type = 1002;
this.bLv.format = 1;
this.bLv.width = -1;
this.bLv.gravity = 51;
this.bLv.height = -2;
this.bLv.token = eVar.getAnchorView().getWindowToken();
this.bLv.flags = eVar.mo24859SP();
return this.bLv;
}
throw new IllegalArgumentException("Toast can't be null");
}
/* renamed from: ce */
private boolean m11600ce(View view) {
boolean z = true;
if (view == null) {
return true;
}
Context context = view.getContext();
if (context instanceof Activity) {
z = ((Activity) context).isFinishing();
}
return z;
}
/* renamed from: d */
private void m11601d(C4576e eVar) {
eVar.mo24851SH();
eVar.getContentView().setVisibility(0);
}
/* renamed from: f */
private void m11602f(C4576e eVar) {
View contentView = eVar.getContentView();
if (contentView != null && contentView.getParent() != null) {
m11604h(eVar).removeView(contentView);
C4576e eVar2 = (C4576e) this.bLu.poll();
if (eVar2 != null) {
eVar2.destroy();
}
}
}
/* renamed from: g */
private void m11603g(C4576e eVar) {
eVar.mo24852SI();
}
/* renamed from: h */
private WindowManager m11604h(C4576e eVar) {
return (WindowManager) eVar.getContext().getSystemService("window");
}
/* renamed from: a */
public void mo24847a(C4576e eVar, boolean z) {
if (this.bLu.size() < 1 || z) {
this.bLu.add(eVar);
m11592SE();
}
}
/* renamed from: e */
public void mo24848e(C4576e eVar) {
View contentView = eVar.getContentView();
if (contentView != null && contentView.getParent() != null) {
m11596a(eVar, 109531);
m11597a(eVar, 109532, eVar.mo24854SK());
m11597a(eVar, 109527, eVar.mo24854SK());
}
}
public void handleMessage(Message message) {
C4576e eVar = (C4576e) message.obj;
switch (message.what) {
case 109527:
m11592SE();
return;
case 109528:
m11598b(eVar);
return;
case 109529:
m11601d(eVar);
return;
case 109530:
mo24848e(eVar);
return;
case 109531:
m11603g(eVar);
return;
case 109532:
m11602f(eVar);
return;
default:
return;
}
}
}
| [
"bhagat.singh@cliffex.com"
] | bhagat.singh@cliffex.com |
164114fce823d1d78df887ec656f33d5535650aa | e34f836ffd44cf2b8e21aaeb653b5cfdc8ad0b45 | /CC-java-sdk-api/src/main/java/com/ceres/api/domain/trade/InstantTradingAskPriceReq.java | 505dfa8cef58e82aa5656b3aa8735f22cd19d59e | [] | no_license | lmttrade/open-api-v1-sdk | 037b57f324a7d656927ee5c91d239928034259ae | 314c472898f27ed4760c6687384f909f033e3696 | refs/heads/master | 2022-06-24T11:27:09.467814 | 2020-01-16T06:06:47 | 2020-01-16T06:06:47 | 167,154,370 | 1 | 1 | null | 2022-06-17T02:05:12 | 2019-01-23T09:21:03 | Java | UTF-8 | Java | false | false | 1,433 | java | package com.ceres.api.domain.trade;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author: LMT
* @date: 19/9/4
* @description:
*/
public class InstantTradingAskPriceReq {
@JsonProperty("symbol")
private String symbol;
@JsonProperty("entrust_type")
private int entrustType;
@JsonProperty("entrust_amount")
private String entrustAmount;
@JsonProperty("entrust_bs")
private String entrustBs;
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public int getEntrustType() {
return entrustType;
}
public void setEntrustType(int entrustType) {
this.entrustType = entrustType;
}
public String getEntrustAmount() {
return entrustAmount;
}
public void setEntrustAmount(String entrustAmount) {
this.entrustAmount = entrustAmount;
}
public String getEntrustBs() {
return entrustBs;
}
public void setEntrustBs(String entrustBs) {
this.entrustBs = entrustBs;
}
@Override
public String toString() {
return "InstantTradingAskPriceReq{" +
"symbol='" + symbol + '\'' +
", entrustType='" + entrustType + '\'' +
", entrustAmount='" + entrustAmount + '\'' +
", entrustBs='" + entrustBs + '\'' +
'}';
}
}
| [
"wulei@qbao.com"
] | wulei@qbao.com |
f94b12a4c0251b139d7871c86d6378883fe66b64 | 0ccd9f92861d14ebbdecad4c1fe5b115a0a5622a | /src/main/java/dataStructure/utils/printer/Strings.java | 06899649a532a18a7adef269ec72849829c425d3 | [] | no_license | longlong-godcoder/javaBaseStucture | 857b0c06022d13780b024826cd0eec057082eaad | 46b3eda6a44c99e2524a8495464bac1dca13f555 | refs/heads/master | 2020-11-29T03:58:22.620051 | 2020-02-12T06:46:42 | 2020-02-12T06:46:42 | 230,011,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 448 | java | package dataStructure.utils.printer;
public class Strings {
public static String repeat(String string, int count) {
if (string == null) return null;
StringBuilder builder = new StringBuilder();
while (count-- > 0) {
builder.append(string);
}
return builder.toString();
}
public static String blank(int length) {
if (length < 0) return null;
if (length == 0) return "";
return String.format("%" + length + "s", "");
}
}
| [
"743096549@qq.com"
] | 743096549@qq.com |
89791aae4c1fbd504d70b39ffec1f51ab6d4cb9f | 13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3 | /crash-reproduction-ws/results/XRENDERING-418-19-9-Single_Objective_GGA-WeightedSum/org/xwiki/rendering/internal/parser/xhtml/wikimodel/XWikiCommentHandler_ESTest_scaffolding.java | 6ffff73e0be97f5cb524a6e2069a58a2b323c842 | [
"MIT",
"CC-BY-4.0"
] | permissive | STAMP-project/Botsing-basic-block-coverage-application | 6c1095c6be945adc0be2b63bbec44f0014972793 | 80ea9e7a740bf4b1f9d2d06fe3dcc72323b848da | refs/heads/master | 2022-07-28T23:05:55.253779 | 2022-04-20T13:54:11 | 2022-04-20T13:54:11 | 285,771,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 475 | java | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Tue Mar 31 05:03:42 UTC 2020
*/
package org.xwiki.rendering.internal.parser.xhtml.wikimodel;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
@EvoSuiteClassExclude
public class XWikiCommentHandler_ESTest_scaffolding {
// Empty scaffolding for empty test suite
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
86b8c48ebc34d10e5bdf3a830eae0dc89901365a | d99f825d812d79a7e863dfea24d5f91d6e3fffb9 | /bookmark-services/src/main/java/com/jk/tool/bookmark/model/BookmarkType.java | d476b8a058dd379a4cc10df705bb04c87d6c052b | [] | no_license | juneshs/bookmark | fd456efbb02cef813544ee2b41698b4ff1a218dd | 900440c3a78fc5c96e142111801bc37dd28a60cb | refs/heads/master | 2021-05-03T09:23:21.557619 | 2019-07-10T05:43:30 | 2019-07-10T05:43:30 | 120,574,891 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 328 | java | package com.jk.tool.bookmark.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class BookmarkType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
}
| [
"juneshkumar.subramani@astrazeneca.com"
] | juneshkumar.subramani@astrazeneca.com |
d14a3cae57b5c840bec4f93799758bc3fa260838 | d3aa14a21b8ebd8e0b0bd05fd1b40fc6344cd9ac | /src/main/java/com/steammachine/jsonchecker/impl/directcomparison/pathformats/Formats.java | 32c09b6cf87528ace3069fe7f74989729810563e | [] | no_license | DarrylZero/json.compare | 2d706c1c828174d4ed1903fc2706e00202415591 | ded957a7eadf079b1f0917f5f437feb1adf14d9c | refs/heads/development | 2021-05-05T06:28:00.371241 | 2018-04-09T18:28:18 | 2018-04-09T18:28:18 | 118,802,333 | 0 | 0 | null | 2018-04-08T15:38:21 | 2018-01-24T18:04:47 | Java | UTF-8 | Java | false | false | 4,599 | java | package com.steammachine.jsonchecker.impl.directcomparison.pathformats;
import com.steammachine.common.lazyeval.LazyBuider;
import com.steammachine.jsonchecker.defaults.AddressType;
import com.steammachine.jsonchecker.types.Path;
import com.steammachine.jsonchecker.types.exceptions.PathError;
import com.steammachine.jsonchecker.types.exceptions.WrongDataFormat;
import com.steammachine.common.lazyeval.LazyEval;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.steammachine.common.utils.commonutils.CommonUtils.check;
/**
* Класс - Комбинированный формат данных используемый для отображения пути в виде.
* <p>
* /monkeyId/@componentType/monkeyId/ ... etc.
* <p>
* <p>
* 30.12.2017 10:21:45
*
* @author Vladimir Bogodukhov
**/
public class Formats {
private static final LazyEval<Map<String, PathFormat>> PATH_FORMATS = LazyEval.eval(() -> {
Map<String, PathFormat> map = new HashMap<>();
map.put(AddressType.DIRECT.name(), new DotFormat());
map.put(AddressType.MONKEY.name(), new MonkeyIdCompTypeFormat());
return Collections.unmodifiableMap(map);
});
/**
* @return Стрим со всеми форматами (всегда не null)
*/
public static Stream<PathFormat> formats() {
return PATH_FORMATS.value().values().stream();
}
/**
* Проверить что строка соответствует одному из фoрматов пути.
* <p>
* Implementation notes - также проверяется что путь соответсвует только одному из форматов.
* (Возможно это не будет актуально в будущем)
*
* @param path проверемый путь.
* @exception PathFormat - если строка не соответсвует ни одному формату.
*/
public static void checkPathFormat(String path) {
if (PATH_FORMATS.value().values().stream().noneMatch(f -> f.checkPathFormat(path))) {
throw new PathError("path " + path + " is not correct path ");
}
if (PATH_FORMATS.value().values().stream().filter(f -> f.checkPathFormat(path)).count() > 1) {
/* Если строка соответсвует более чем одному формату - это ошибка. */
throw new PathError(LazyBuider.lazy(() ->
"path " + path + " is matched more than one format " +
PATH_FORMATS.value().values().stream().
filter(f -> f.checkPathFormat(path)).map(PathFormat::name).
collect(Collectors.joining(",")))
);
}
}
/**
* Проверить что путь соответвует шаблону сравнения какого-либо формата.
*
* @param path Путь
* @param pathTemplate Шаблон пути
* @return {@code true} если соответствует
* {@code false} если не соответвует шаблону
* @throws PathFormat если строка не соответсвует ни одному формату.
*/
public static boolean isApplied(String kind, Path path, Path pathTemplate) {
PathFormat pathFormat = PATH_FORMATS.value().get(kind);
check(() -> pathFormat != null, IllegalStateException::new);
return pathFormat.isApplied(path, pathTemplate);
}
/**
* Получить значение типа формата - обозначенного данной строкой
*
* @param path - Путь
* @return тип формата
* @throws WrongDataFormat в случае если путь не соответствует ни одному формату.
*/
public static String formatType(String path) {
return PATH_FORMATS.value().entrySet().stream().
filter(e -> e.getValue().checkPathFormat(path)).
map(Map.Entry::getKey).
findFirst().orElseThrow(() -> new WrongDataFormat("path " + path + " does not match any format"));
}
public static PathFormat format(String data) {
PathFormat pathFormat = PATH_FORMATS.value().get(data);
check(() -> pathFormat != null, IllegalStateException::new);
return pathFormat;
}
}
| [
"ubob@inbox.ru"
] | ubob@inbox.ru |
12c808d42dc5fb7d7a28ff24218fa9e634ef2109 | 0e4e6b95b94f9a8d77a8f620992ef4d5f0e45e76 | /graduationDesignUtil/src/main/java/graduationDesign/util/UUIDBuild.java | cf3f4312678db1f4ffa28b8d724d2df6cbb5f0cf | [] | no_license | Fingthingman/graduationDesign | 8712956bf368f9d31aff40da3b9f70e13055af9a | 8fdaf68af63f6c2c3d3a6e25a4478ea87b9e44a7 | refs/heads/master | 2021-04-29T08:01:44.594044 | 2017-01-05T00:57:10 | 2017-01-05T00:57:10 | 77,971,994 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,628 | java | package graduationDesign.util;
import java.net.InetAddress;
import java.util.UUID;
public class UUIDBuild {
private String sep = "";
private static final int IP;
private static short counter = (short) 0;
private static final int JVM = (int) (System.currentTimeMillis() >>> 8);
private static UUIDBuild uuidgen = new UUIDBuild();
static {
int ipadd;
try {
ipadd = toInt(InetAddress.getLocalHost().getAddress());
} catch (Exception e) {
ipadd = 0;
}
IP = ipadd;
}
public static UUIDBuild getInstance() {
return uuidgen;
}
public static int toInt(byte[] bytes) {
int result = 0;
for (int i = 0; i < 4; i++) {
result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
}
return result;
}
protected String format(int intval) {
String formatted = Integer.toHexString(intval);
StringBuffer buf = new StringBuffer("00000000");
buf.replace(8 - formatted.length(), 8, formatted);
return buf.toString();
}
protected String format(short shortval) {
String formatted = Integer.toHexString(shortval);
StringBuffer buf = new StringBuffer("0000");
buf.replace(4 - formatted.length(), 4, formatted);
return buf.toString();
}
protected int getJVM() {
return JVM;
}
protected synchronized short getCount() {
if (counter < 0) {
counter = 0;
}
return counter++;
}
protected int getIP() {
return IP;
}
protected short getHiTime() {
return (short) (System.currentTimeMillis() >>> 32);
}
protected int getLoTime() {
return (int) System.currentTimeMillis();
}
public String generate() {
return new StringBuffer(36).append(format(getIP())).append(sep).append(
format(getJVM())).append(sep).append(format(getHiTime()))
.append(sep).append(format(getLoTime())).append(sep).append(
format(getCount())).toString();
}
public static void main(String[] str) {
// 得到一个序号
System.out.println(getUUID());
// 一次得到多个序号
String[] UUID_s = getUUID(10);
for (int i = 0; i < UUID_s.length; i++) {
System.out.println(UUID_s[i]);
}
}
// 得到一个序号
public static String getUUID() {
String s = UUID.randomUUID().toString();
return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18)
+ s.substring(19, 23) + s.substring(24);
}
/**
* 一次得到多个序号
*
* @param number
* int 需要获得的序号数量
* @return String[] 序号数组
*/
public static String[] getUUID(int number) {
if (number < 1) {
return null;
}
String[] ss = new String[number];
for (int i = 0; i < ss.length; i++) {
ss[i] = getUUID();
}
return ss;
}
}
| [
"851696643@qq.com"
] | 851696643@qq.com |
53a30820eb9ed118b6d4a17d2769dee22ebf44f5 | 2a89c6db353d5c7eacde69cee91892f7a5dec0da | /jvm/src/main/java/com/lcc/jvm/ref/WeakHashMapDemo.java | 0de765567a1089ecb2c03797512d98c5270f386b | [] | no_license | chuangehh/java_demo | 61288f9b0acb1fb4e7c51a3e65c83af953700401 | fbf92a77a8ac8924428bf78eb8dcac7732d248a2 | refs/heads/master | 2023-04-13T19:26:47.304116 | 2023-03-28T13:04:18 | 2023-03-28T13:04:18 | 188,777,762 | 5 | 1 | null | 2020-10-13T19:27:40 | 2019-05-27T05:40:18 | Java | UTF-8 | Java | false | false | 1,697 | java | package com.lcc.jvm.ref;
import java.util.HashMap;
import java.util.WeakHashMap;
/**
* 原理是使用了 WeakReference包装了key
*
* @see WeakHashMap.Entry super(key, queue);
* @see WeakHashMap#expungeStaleEntries()
*
* -Xms5m -Xmx5m -XX:+PrintGCDetails -XX:+UseSerialGC
*/
public class WeakHashMapDemo {
public static void main(String[] args) {
// stringKey();
HashMap<Integer, Object> hashMap = new HashMap<>(16);
Integer hashKey = new Integer(100);
hashMap.put(hashKey, "hashValue");
hashKey = null;
System.out.println(hashMap);
System.gc();
System.out.println(hashMap);
System.out.println("================================");
WeakHashMap<Integer, Object> weakHashMap = new WeakHashMap<>();
Integer weakHashKey = new Integer(200);
weakHashMap.put(weakHashKey, "weakHashValue");
weakHashKey = null;
System.out.println(weakHashMap);
System.gc();
System.out.println(weakHashMap);
}
/**
* 使用字符串不行,使用Integer/Long .. -128~127 不行
* 字符串有常量池,是强引用
* Integer/Long .. 包装类型里有一个缓冲区,也是强引用
*/
private static void stringKey() {
HashMap<String, Object> hashMap = new HashMap<>(16);
String hashKey = "hashKey";
hashMap.put(hashKey, "hashValue");
hashKey = null;
System.out.println(hashMap);
System.gc();
System.out.println(hashMap);
System.out.println("================================");
WeakHashMap<String, Object> weakHashMap = new WeakHashMap<>();
String weakHashKey = "weakHashKey";
weakHashMap.put(weakHashKey, "weakHashValue");
weakHashKey = null;
System.out.println(weakHashMap);
System.gc();
System.out.println(weakHashMap);
}
}
| [
"liangchuanchuan@banggood.com"
] | liangchuanchuan@banggood.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.