text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```java package com.baronzhang.android.weather.feature.selectcity; import android.content.Context; import com.baronzhang.android.weather.data.db.dao.CityDao; import com.baronzhang.android.weather.di.component.DaggerPresenterComponent; import com.baronzhang.android.weather.di.module.ApplicationModule; import com.baronzhang.android.weather.di.scope.ActivityScoped; import javax.inject.Inject; import rx.Observable; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) */ @ActivityScoped public final class SelectCityPresenter implements SelectCityContract.Presenter { private final SelectCityContract.View cityListView; private CompositeSubscription subscriptions; @Inject CityDao cityDao; @Inject SelectCityPresenter(Context context, SelectCityContract.View view) { this.cityListView = view; this.subscriptions = new CompositeSubscription(); cityListView.setPresenter(this); DaggerPresenterComponent.builder() .applicationModule(new ApplicationModule(context)) .build().inject(this); } @Override public void loadCities() { Subscription subscription = Observable.just(cityDao.queryCityList()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(cityListView::displayCities); subscriptions.add(subscription); } @Override public void subscribe() { loadCities(); } @Override public void unSubscribe() { subscriptions.clear(); } } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/feature/selectcity/SelectCityPresenter.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
328
```java package com.baronzhang.android.weather.feature.selectcity; import android.os.Bundle; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.baronzhang.android.weather.base.BaseFragment; import com.baronzhang.android.weather.R; import com.baronzhang.android.weather.data.db.entities.City; import com.baronzhang.android.weather.data.preference.PreferenceHelper; import com.baronzhang.android.weather.data.preference.WeatherSettings; import com.baronzhang.android.library.view.DividerItemDecoration; import java.io.InvalidClassException; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) */ public class SelectCityFragment extends BaseFragment implements SelectCityContract.View { public List<City> cities; public CityListAdapter cityListAdapter; @BindView(R.id.rv_city_list) RecyclerView recyclerView; private Unbinder unbinder; private SelectCityContract.Presenter presenter; public SelectCityFragment() { } public static SelectCityFragment newInstance() { return new SelectCityFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_select_city, container, false); unbinder = ButterKnife.bind(this, rootView); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST)); cities = new ArrayList<>(); cityListAdapter = new CityListAdapter(cities); cityListAdapter.setOnItemClickListener((parent, view, position, id) -> { try { City selectedCity = cityListAdapter.mFilterData.get(position); PreferenceHelper.savePreference(WeatherSettings.SETTINGS_CURRENT_CITY_ID, selectedCity.getCityId() + ""); Toast.makeText(this.getActivity(), selectedCity.getCityName(), Toast.LENGTH_LONG).show(); getActivity().finish(); } catch (InvalidClassException e) { e.printStackTrace(); } }); recyclerView.setAdapter(cityListAdapter); presenter.subscribe(); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); presenter.unSubscribe(); } @Override public void displayCities(List<City> cities) { this.cities.addAll(cities); cityListAdapter.notifyDataSetChanged(); } @Override public void setPresenter(SelectCityContract.Presenter presenter) { this.presenter = presenter; } } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/feature/selectcity/SelectCityFragment.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
575
```java package com.baronzhang.android.weather.feature.selectcity; import com.baronzhang.android.weather.di.component.ApplicationComponent; import com.baronzhang.android.weather.di.scope.ActivityScoped; import dagger.Component; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) * 2016/11/30 */ @ActivityScoped @Component(modules = SelectCityModule.class, dependencies = ApplicationComponent.class) public interface SelectCityComponent { void inject(SelectCityActivity selectCityActivity); } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/feature/selectcity/SelectCityComponent.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
115
```java package com.baronzhang.android.weather.feature.selectcity; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import com.annimon.stream.Stream; import com.baronzhang.android.weather.base.BaseRecyclerViewAdapter; import com.baronzhang.android.weather.R; import com.baronzhang.android.weather.data.db.entities.City; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) * 16/3/16 */ public class CityListAdapter extends BaseRecyclerViewAdapter<CityListAdapter.ViewHolder> implements Filterable { private List<City> cities; public List<City> mFilterData;// private RecyclerViewFilter filter; public CityListAdapter(List<City> cities) { this.cities = cities; mFilterData = cities; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_city, parent, false); return new ViewHolder(itemView, this); } @Override public void onBindViewHolder(ViewHolder holder, int position) { City city = mFilterData.get(position); String cityName = city.getCityName(); String parentName = city.getParent(); if (!cityName.equals(parentName)) { cityName = parentName + "." + cityName; } holder.cityNameTextView.setText(cityName); } @Override public int getItemCount() { return mFilterData == null ? 0 : mFilterData.size(); } static class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.city_name_text_view) TextView cityNameTextView; ViewHolder(View itemView, CityListAdapter cityListAdapter) { super(itemView); ButterKnife.bind(this, itemView); itemView.setOnClickListener(v -> cityListAdapter.onItemHolderClick(this)); } } @Override public Filter getFilter() { if (filter == null) { filter = new RecyclerViewFilter(); } return filter; } private class RecyclerViewFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence charSequence) { //resultsArrayList<City> FilterResults results = new FilterResults(); //null if (charSequence == null || charSequence.length() == 0) { results.values = null; results.count = 0; } else { String prefixString = charSequence.toString().toLowerCase(); //Values ArrayList<City> newValues = new ArrayList<>(); Stream.of(cities) .filter(city -> (city.getCityName().contains(prefixString) || city.getCityNameEn().contains(prefixString) || city.getParent().contains(prefixString) || city.getRoot().contains(prefixString))) .forEach(newValues::add); results.values = newValues; results.count = newValues.size(); } return results; } @Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { mFilterData = (List<City>) filterResults.values; if (filterResults.count > 0) { notifyDataSetChanged();// } else { mFilterData = cities; notifyDataSetChanged();// } } } } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/feature/selectcity/CityListAdapter.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
717
```java package com.baronzhang.android.weather.feature.selectcity; import android.os.Bundle; import androidx.core.view.MenuItemCompat; import androidx.appcompat.widget.SearchView; import androidx.appcompat.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.baronzhang.android.weather.base.BaseActivity; import com.baronzhang.android.library.util.ActivityUtils; import com.baronzhang.android.weather.R; import com.baronzhang.android.weather.WeatherApplication; import com.jakewharton.rxbinding.support.v7.widget.RxSearchView; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com ==>> baronzhang.com) */ public class SelectCityActivity extends BaseActivity { @BindView(R.id.toolbar) Toolbar toolbar; SelectCityFragment selectCityFragment; @Inject SelectCityPresenter selectCityPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_city); ButterKnife.bind(this); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } selectCityFragment = (SelectCityFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container); if (selectCityFragment == null) { selectCityFragment = SelectCityFragment.newInstance(); ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), selectCityFragment, R.id.fragment_container); } DaggerSelectCityComponent.builder() .applicationComponent(WeatherApplication.getInstance().getApplicationComponent()) .selectCityModule(new SelectCityModule(selectCityFragment)) .build().inject(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_city, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_search) { SearchView searchView = (SearchView) MenuItemCompat.getActionView(item); RxSearchView.queryTextChanges(searchView) .map(charSequence -> charSequence == null ? null : charSequence.toString().trim()) .throttleLast(100, TimeUnit.MILLISECONDS) .debounce(100, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(searchText -> selectCityFragment.cityListAdapter.getFilter().filter(searchText)); return true; } return super.onOptionsItemSelected(item); } } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/feature/selectcity/SelectCityActivity.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
543
```java package com.baronzhang.android.weather.di.component; import com.baronzhang.android.weather.di.module.ApplicationModule; import com.baronzhang.android.weather.feature.home.drawer.DrawerMenuPresenter; import com.baronzhang.android.weather.feature.selectcity.SelectCityPresenter; import javax.inject.Singleton; import dagger.Component; import com.baronzhang.android.weather.feature.home.HomePagePresenter; /** * @author (baron[dot]zhanglei[at]gmail[dot]com) * 2016/12/2 */ @Singleton @Component(modules = {ApplicationModule.class}) public interface PresenterComponent { void inject(HomePagePresenter presenter); void inject(SelectCityPresenter presenter); void inject(DrawerMenuPresenter presenter); } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/di/component/PresenterComponent.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
157
```java package com.baronzhang.android.weather.di.module; import android.content.Context; import com.baronzhang.android.weather.WeatherApplication; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; /** * @author (baronzhang[at]anjuke[dot]com) * 2016/11/30 */ @Module public class ApplicationModule { private Context context; public ApplicationModule(Context context) { this.context = context; } @Provides @Singleton WeatherApplication provideApplication() { return (WeatherApplication) context.getApplicationContext(); } @Provides @Singleton Context provideContext() { return context; } } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/di/module/ApplicationModule.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
149
```java package com.baronzhang.android.weather.di.component; import android.content.Context; import com.baronzhang.android.weather.WeatherApplication; import com.baronzhang.android.weather.di.module.ApplicationModule; import javax.inject.Singleton; import dagger.Component; /** * @author (baron[dot]zhanglei[at]gmail[dot]com) * 2016/11/30 */ @Singleton @Component(modules = {ApplicationModule.class}) public interface ApplicationComponent { WeatherApplication getApplication(); Context getContext(); } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/di/component/ApplicationComponent.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
112
```java package com.baronzhang.android.weather.di.scope; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.inject.Scope; /** * @author (baronzhang[at]anjuke[dot]com) * 2016/12/1 */ @Scope @Documented @Retention(RetentionPolicy.RUNTIME) public @interface ActivityScoped { } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/di/scope/ActivityScoped.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
90
```java package com.baronzhang.android.weather.base; import androidx.recyclerview.widget.RecyclerView; import android.widget.AdapterView; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) * 16/4/15 */ public abstract class BaseRecyclerViewAdapter<T extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<T>{ protected AdapterView.OnItemClickListener onItemClickListener; public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } protected void onItemHolderClick(RecyclerView.ViewHolder itemHolder) { if (onItemClickListener != null) { onItemClickListener.onItemClick(null, itemHolder.itemView, itemHolder.getAdapterPosition(), itemHolder.getItemId()); } else { throw new IllegalStateException("Please call setOnItemClickListener method set the click event listeners"); } } } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/base/BaseRecyclerViewAdapter.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
173
```java package com.baronzhang.android.weather.base; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) */ public class BaseFragment extends Fragment { // private PublishSubject<FragmentLifecycleEvent> fragmentLifecycleSubject = PublishSubject.create(); @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onDestroyView() { // fragmentLifecycleSubject.onNext(FragmentLifecycleEvent.DESTROY_VIEW); super.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); } } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/base/BaseFragment.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
195
```java package com.baronzhang.android.weather.base; /** * presenter interface,Presenter * * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) */ public interface BasePresenter { void subscribe(); void unSubscribe(); } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/base/BasePresenter.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
58
```java package com.baronzhang.android.weather.base; /** * view interface,View(ViewFragmentViewGroup) * * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) */ public interface BaseView<T> { void setPresenter(T presenter); } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/base/BaseView.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
62
```java package com.baronzhang.android.weather.util; import android.content.Context; import okhttp3.OkHttpClient; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) * 2017/7/25 */ public interface StethoHelper { void init(Context context); OkHttpClient.Builder addNetworkInterceptor(OkHttpClient.Builder builder); } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/util/StethoHelper.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
83
```java package com.baronzhang.android.weather.base; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.appcompat.widget.SearchView; import android.view.Menu; import android.view.MenuItem; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) */ public class BaseActivity extends AppCompatActivity { /* * Vector * * First up, this functionality was originally released in 23.2.0, * but then we found some memory usage and Configuration updating * issues so we it removed in 23.3.0. In 23.4.0 (technically a fix * release) weve re-added the same functionality but behind a flag * which you need to manually enable. * * path_to_url */ static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/base/BaseActivity.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
301
```java package com.baronzhang.android.weather.util.stetho; import android.content.Context; import com.baronzhang.android.weather.util.StethoHelper; import okhttp3.OkHttpClient; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) * 2017/7/25 */ public class ReleaseStethoHelper implements StethoHelper { @Override public void init(Context context) { } @Override public OkHttpClient.Builder addNetworkInterceptor(OkHttpClient.Builder builder) { return null; } } ```
/content/code_sandbox/app/src/main/java/com/baronzhang/android/weather/util/stetho/ReleaseStethoHelper.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
126
```java package com.baronzhang.android.weather; import android.content.Context; import com.baronzhang.android.weather.util.StethoHelper; import com.facebook.stetho.Stetho; import com.facebook.stetho.okhttp3.StethoInterceptor; import okhttp3.OkHttpClient; /** * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com) * 2017/7/25 */ public class DebugStethoHelper implements StethoHelper { @Override public void init(Context context) { Stetho.initializeWithDefaults(context); } @Override public OkHttpClient.Builder addNetworkInterceptor(OkHttpClient.Builder builder) { return builder.addNetworkInterceptor(new StethoInterceptor()); } } ```
/content/code_sandbox/app/src/debug/java/com/baronzhang/android/weather/DebugStethoHelper.java
java
2016-04-07T08:14:27
2024-07-20T11:58:31
MinimalistWeather
BaronZ88/MinimalistWeather
2,440
163
```swift // // Attachable.swift // FaceAware // // // // 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. import Foundation internal class ClosureWrapper<T> { var closure: (T) -> Void init(_ closure: @escaping (T) -> Void) { self.closure = closure } } internal protocol Attachable { func set(_ attachObj: Any?, forKey key: inout UInt) func getAttach(forKey key: inout UInt) -> Any? } extension Attachable { public func set(_ attachObj: Any?, forKey key: inout UInt) { objc_setAssociatedObject(self, &key, attachObj, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } public func getAttach(forKey key: inout UInt) -> Any? { return objc_getAssociatedObject(self, &key) } } ```
/content/code_sandbox/FaceAware/Attachable.swift
swift
2016-07-22T14:15:00
2024-08-02T19:01:02
FaceAware
BeauNouvelle/FaceAware
3,019
405
```ruby # # Be sure to run `pod spec lint FaceAware.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see path_to_url # To see working Podspecs in the CocoaPods repo see path_to_url # Pod::Spec.new do |s| s.name = "FaceAware" s.version = "2.1.0" s.summary = "A UIImageView extension that focus on faces within an image." s.swift_version = '5.1' s.description = <<-DESC An extension that gives UIImageView the ability to focus on faces within an image when using AspectFill. DESC s.homepage = "path_to_url" s.screenshots = "path_to_url", "path_to_url" s.license = { :type => "MIT", :file => "LICENSE" } s.author = "Beau Nouvelle" s.social_media_url = "path_to_url" s.platform = :ios, "8.0" s.source = { :git => "path_to_url", :tag => "#{s.version}" } s.source_files = "FaceAware/*.{swift}" s.exclude_files = "Classes/Exclude" end ```
/content/code_sandbox/FaceAware.podspec
ruby
2016-07-22T14:15:00
2024-08-02T19:01:02
FaceAware
BeauNouvelle/FaceAware
3,019
292
```swift // // UIImageView+FaceAware.swift // FaceAware // // // // 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. import UIKit import ObjectiveC private var closureKey: UInt = 0 private var debugKey: UInt = 1 @IBDesignable extension UIImageView: Attachable { @IBInspectable /// Adds a red bordered rectangle around any faces detected. public var debugFaceAware: Bool { set { set(newValue, forKey: &debugKey) } get { guard let debug = getAttach(forKey: &debugKey) as? Bool else { return false } return debug } } @IBInspectable /// Set this to true if you want to center the image on any detected faces. public var focusOnFaces: Bool { set { let image = self.image set(image: image, focusOnFaces: newValue) } get { return sublayer() != nil ? true : false } } public func set(image: UIImage?, focusOnFaces: Bool) { guard focusOnFaces == true else { self.removeImageLayer(image: image) return } setImageAndFocusOnFaces(image: image) } /// You can provide a closure here to receive a callback for when all face /// detection and image adjustments have been finished. public var didFocusOnFaces: (() -> Void)? { set { set(newValue, forKey: &closureKey) } get { return getAttach(forKey: &closureKey) as? (() -> Void) } } private func setImageAndFocusOnFaces(image: UIImage?) { DispatchQueue.global(qos: .default).async { guard let image = image else { return } guard let ciImage = CIImage(image: image) else { return } let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyLow]) let features = detector!.features(in: ciImage) if !features.isEmpty { if self.debugFaceAware { print("found \(features.count) faces") } let imgSize = CGSize(width: image.cgImage!.width, height: image.cgImage!.height) self.applyFaceDetection(for: features, size: imgSize, image: image) } else { if self.debugFaceAware { print("No faces found") } self.removeImageLayer(image: image) } } } private func applyFaceDetection(for features: [CIFeature], size: CGSize, image: UIImage) { var rect = features[0].bounds rect.origin.y = size.height - rect.minY - rect.height var rightBorder = Double(rect.minX + rect.width) var bottomBorder = Double(rect.minY + rect.height) for feature in features.dropFirst() { var oneRect = feature.bounds oneRect.origin.y = size.height - oneRect.minY - oneRect.height rect.origin.x = min(oneRect.minX, rect.minX) rect.origin.y = min(oneRect.minY, rect.minY) rightBorder = max(Double(oneRect.minX + oneRect.width), Double(rightBorder)) bottomBorder = max(Double(oneRect.minY + oneRect.height), Double(bottomBorder)) } rect.size.width = CGFloat(rightBorder) - rect.minX rect.size.height = CGFloat(bottomBorder) - rect.minY var offset = CGPoint.zero var finalSize = size DispatchQueue.main.async { if size.width / size.height > self.bounds.width / self.bounds.height { var centerX = rect.minX + rect.width / 2.0 finalSize.height = self.bounds.height finalSize.width = size.width / size.height * finalSize.height centerX = finalSize.width / size.width * centerX offset.x = centerX - self.bounds.width * 0.5 if offset.x < 0 { offset.x = 0 } else if offset.x + self.bounds.width > finalSize.width { offset.x = finalSize.width - self.bounds.width } offset.x = -offset.x } else { var centerY = rect.minY + rect.height / 2.0 finalSize.width = self.bounds.width finalSize.height = size.height / size.width * finalSize.width centerY = finalSize.width / size.width * centerY offset.y = centerY - self.bounds.height * CGFloat(1-0.618) if offset.y < 0 { offset.y = 0 } else if offset.y + self.bounds.height > finalSize.height { finalSize.height = self.bounds.height offset.y = finalSize.height } offset.y = -offset.y } } let newImage: UIImage if self.debugFaceAware { newImage = drawDebugRectangles(from: image, size: size, features: features) } else { newImage = image } DispatchQueue.main.sync { self.image = newImage let layer = self.imageLayer() layer.contents = newImage.cgImage layer.frame = CGRect(origin: offset, size: finalSize) self.didFocusOnFaces?() } } private func drawDebugRectangles(from image: UIImage, size: CGSize, features: [CIFeature]) -> UIImage { // Draw rectangles around detected faces let rawImage = UIImage(cgImage: image.cgImage!) UIGraphicsBeginImageContext(size) rawImage.draw(at: .zero) let context = UIGraphicsGetCurrentContext() context?.setStrokeColor(UIColor.red.cgColor) context?.setLineWidth(3) features.forEach({ var faceViewBounds = $0.bounds faceViewBounds.origin.y = size.height - faceViewBounds.minY - faceViewBounds.height context?.addRect(faceViewBounds) context?.drawPath(using: .stroke) }) let newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } private func imageLayer() -> CALayer { if let layer = sublayer() { return layer } let subLayer = CALayer() subLayer.name = "AspectFillFaceAware" subLayer.actions = ["contents": NSNull(), "bounds": NSNull(), "position": NSNull()] layer.addSublayer(subLayer) return subLayer } private func removeImageLayer(image: UIImage?) { DispatchQueue.main.async { // avoid redundant layer when focus on faces for the image of cell specified in UITableView self.imageLayer().removeFromSuperlayer() self.image = image } } private func sublayer() -> CALayer? { return layer.sublayers?.first { $0.name == "AspectFillFaceAware" } } override open func layoutSubviews() { super.layoutSubviews() if focusOnFaces { setImageAndFocusOnFaces(image: self.image) } } } ```
/content/code_sandbox/FaceAware/UIImageView+FaceAware.swift
swift
2016-07-22T14:15:00
2024-08-02T19:01:02
FaceAware
BeauNouvelle/FaceAware
3,019
1,740
```objective-c // // FaceAware.h // FaceAware // // Created by Beau Nouvelle on 30/5/18. // #import <UIKit/UIKit.h> //! Project version number for FaceAware. FOUNDATION_EXPORT double FaceAwareVersionNumber; //! Project version string for FaceAware. FOUNDATION_EXPORT const unsigned char FaceAwareVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <FaceAware/PublicHeader.h> ```
/content/code_sandbox/Example/FaceAware/FaceAware.h
objective-c
2016-07-22T14:15:00
2024-08-02T19:01:02
FaceAware
BeauNouvelle/FaceAware
3,019
97
```swift // // ViewController.swift // Example // // Created by Beau Nouvelle on 17/9/16. // import UIKit import FaceAware class ViewController: UIViewController { @IBOutlet weak var faceAwareImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. faceAwareImageView.didFocusOnFaces = { print("Did finish focussing") } } @IBAction func toggle(_ sender: UIButton) { faceAwareImageView.focusOnFaces = !faceAwareImageView.focusOnFaces } } ```
/content/code_sandbox/Example/Example/ViewController.swift
swift
2016-07-22T14:15:00
2024-08-02T19:01:02
FaceAware
BeauNouvelle/FaceAware
3,019
130
```swift // // AppDelegate.swift // Example // // Created by Beau Nouvelle on 17/9/16. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } ```
/content/code_sandbox/Example/Example/AppDelegate.swift
swift
2016-07-22T14:15:00
2024-08-02T19:01:02
FaceAware
BeauNouvelle/FaceAware
3,019
390
```html google-site-verification: googlefa72b21fb50e2d3b.html ```
/content/code_sandbox/googlefa72b21fb50e2d3b.html
html
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
19
```python # Merge Sort implementation in Python with in depth comments # # Author: BedirT # Merge Sort is a divide and conquer algorithm that divides the input array into two halves, # calls itself for the two halves, and then merges the two sorted halves. The merge() # function is used for merging two halves. The merge(arr, l, m, r) is key process that # assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. # Time Complexity: O(nlogn) # Space Complexity: O(n) def merge_sort(arr): if len(arr) > 1: # Finding the mid of the array mid = len(arr) // 2 # Dividing the array elements L = arr[:mid] # into 2 halves R = arr[mid:] # Sorting the first half merge_sort(L) # Sorting the second half merge_sort(R) i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 # Code to print the list def print_list(arr): for i in range(len(arr)): print(arr[i], end=" ") print() # Driver Code if __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] print("Given array is", end="\n") print_list(arr) merge_sort(arr) print("Sorted array is: ", end="\n") print_list(arr) ```
/content/code_sandbox/Week04/vanilla_implementations/merge_sort.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
459
```python def main(): T = int(input()) while T: T -= 1 ct = 1 s, t, i = map(int, input().split()) if s <= i and i <= t: print(s, t) while s != t: if t-i < i-s: s = s + int((t-s)/2) + 1 ct += 1 print(s, t) else: t = s + int((t-s)/2) ct += 1 print(s, t) print(ct) else: print(-1) if __name__ == "__main__": main() ```
/content/code_sandbox/Week04/solutions/merge_sort_codechef.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
149
```python # Vanilla implementation of gcd and lcm # # Author: Bedir Tapkan # Date: 04/12/2022 def gcd(a, b): """ Euclidean algorithm implementation """ while b: a, b = b, a % b return a def lcm(a, b): """ Least common multiple implementation """ return a * b // gcd(a, b) def example(): """ Example """ print(gcd(12, 8)) # 4 print(lcm(12, 8)) # 24 if __name__ == "__main__": example() ```
/content/code_sandbox/Week02/vanilla_implementations/gcd_lcm.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
141
```c++ #include <iostream> #include <string> using namespace std; struct Node { bool isEnd; Node* child[26]; Node() { isEnd = false; memset(child, 0, sizeof(child)); } }; Node* root = new Node(); void add(const string& str) { auto node = root; for(int i = 0; i < str.length(); i++) { if(node->child[str[i] - 'a'] != nullptr) { node = node->child[str[i] - 'a']; } else { node->child[str[i] - 'a'] = new Node(); if(i == str.length() - 1) { node->child[str[i] - 'a']->isEnd = true; return; } node = node->child[str[i] - 'a']; } } } bool find(const string& str) { auto node = root; for(int i = 0; i < str.length(); i++) { if(node->child[str[i] - 'a'] != nullptr) { node = node->child[str[i] - 'a']; } else { return false; } } return node->isEnd; } int main() { // Number of queries int n; cin >> n; for(int i = 0; i < n; i++) { // 1: add a new word // 2: search for an existing word int option; string word; cin >> option >> word; if(option == 1) { add(word); } else if(option == 2) { cout << (find(word) ? "Found" : "Not found") << endl; } else { continue; } } return 0; } ```
/content/code_sandbox/Week12/Source/trie.cpp
c++
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
425
```python # path_to_url # # Author: Bedir Tapkan def gcd(a, b): while b: a, b = b, a%b return a def solve(a, b): cur_gcd = a for i in range(a+1, b+1): cur_gcd = gcd(i, cur_gcd) if cur_gcd == 1: return 1 return cur_gcd if __name__ == "__main__": a, b = map(int, input().split(" ")) print(solve(a,b)) ```
/content/code_sandbox/Week02/solutions/complicated_gcd.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
126
```c++ // Solution for the problem: GCD of large numbers // path_to_url #include <iostream> #include <string> #include <vector> using namespace std; int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { int a; string b; cin >> a >> b; if (a == 0) { cout << b << endl; continue; } int b_mod_a = 0; for (int j = 0; j < b.size(); ++j) { b_mod_a = (b_mod_a * 10 + (b[j] - '0')) % a; } cout << gcd(a, b_mod_a) << endl; } return 0; } ```
/content/code_sandbox/Week02/solutions/gcd_of_large_number.cc
c++
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
208
```python # path_to_url # # Author: Bedir Tapkan mod_val = 10**9 + 7 def gcd(a, b): while b: a, b = b, a%b return a def modexp(a, b, x): a %= x result = 1 while b > 0: if b & 1: result = (result * a) % x a = a ** 2 % x b >>= 1 return result def solve(a, b, n): delta = a - b if delta == 0: return (modexp(a, n, mod_val) + modexp(b, n, mod_val)) % mod_val else: value = modexp(a, n, delta) + modexp(b, n, delta) value %= delta return gcd(delta, value) % mod_val if __name__ == "__main__": T = int(input()) for t in range(T): a, b, n = map(int, input().split(" ")) print(solve(a,b,n)) ```
/content/code_sandbox/Week02/solutions/modular_gcd.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
247
```python # path_to_url # # Author: Bedir Tapkan import math import os import random import re import sys # # Complete the 'solve' function below. # # The function is expected to return a STRING. # The function accepts INTEGER_ARRAY a as parameter. # def gcd(a, b): while b: a, b = b, a%b return a def solve(a): # if all the gcd of all the elements is 1 return 'YES' # otherwise return 'NO' a = list(set(a)) tot_gcd = a[0] for i in range(1, len(a)): tot_gcd = gcd(tot_gcd, a[i]) if tot_gcd > 1: return 'NO' return 'YES' if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input().strip()) for t_itr in range(t): a_count = int(input().strip()) a = list(map(int, input().rstrip().split())) result = solve(a) fptr.write(result + '\n') fptr.close() ```
/content/code_sandbox/Week02/solutions/sherlock_and_gcd.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
255
```c++ // Modular Exponentiation (Power in Modular Aritmetic) (x^y) #include <iostream> using namespace std; int main () { long long int x,y,mod, res=1; cin >> x >> y >> mod; x = x%mod; while (y > 0) { if (y%2) res = (res*x)%mod; y = y/2; x= (x*x)%mod; } cout << res << endl; return 0; } ```
/content/code_sandbox/Week01/vanilla_implementations/modularExponentiation.cpp
c++
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
112
```c++ #include <cstdlib> #include <iostream> #include <algorithm> #include <vector> // STL #include <bitset> // STL using namespace std; vector<int> primes; void sieve(int size) { bitset<10000010> was; was.set(); was[0] = was[1] = 0; for (int i = 2; i <= size; i++) if (was[i]) { primes.push_back(i); for (int j = i * i; j <= size; j += i) was[j] = 0; } } vector<int> primeFactors(int N){ vector<int> vc; // Comment line below for using other method (iterator) // int idx = 0, f = primes[idx]; // f standing for FACTOR - idx is index that we will increment // // More advanced usage would be pointers : // vector<int>::iterator it = primes.begin(); int f = *it; ///// Uncomment for using iterator // while(N != 1 && N >= f * f){ while(N % f == 0){ N /= f; vc.push_back(f); } // // f = *(++it); ///// Uncomment for using iterator // f = primes[++idx]; // Comment this for using other method (iterator) // } if(N != 1) vc.push_back(N); // This case is for prime numbers or having factor greater than sqrt(N). return vc; } int main(){ sieve(10000); int n = 18; // cin >> n; vector<int> pF = primeFactors(n); for(int i = 0; i < pF.size() ; ++i){ cout << pF[i] << " " ; } cout << endl; } ```
/content/code_sandbox/Week01/vanilla_implementations/primeFactorization.cpp
c++
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
393
```c++ // Sieve of Eratosthenes // // Author: Bedir Tapkan // // Desc: Find the prime numbers from 1 - n #include <iostream> #include <vector> #include <cstring> using namespace std; void sieve(long n, bool * composite, vector<int> &primes){ // n -> the max number to check for primes // composite -> bool arr to mark composite nums // primes -> vector that contains primes from 2 -> n // O(n*sqrt(n)) - but much faster in practice for (long i = 2; i <= n; ++i){ // Check 2->n if they are already marked as composite // and mark composites along the way if (!composite[i]){ // Checking if prime primes.push_back(i); for (long j = i*i; j <= n; j += i){ composite[j] = true; } } } } void printVector(vector<int> vc) { for (int i = 0; i < vc.size(); ++i) cout << vc[i] << " "; cout << endl << endl; } int main() { long n; cin >> n; // number to check for primes up to bool composite[n+1]; memset(composite, false, sizeof composite); vector<int> primes; sieve(n, composite, primes); printVector(primes); } ```
/content/code_sandbox/Week01/vanilla_implementations/sieveOfEratosthenes.cpp
c++
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
309
```python # Sieve of Eratosthenes implementation in Python # # Author: Bedir Tapkan # Date: 04/11/2022 def sieve_of_eratosthenes(n): """ Sieve of Eratosthenes implementation; Finding prime numbers from 2 to n (inclusive). """ primes = [True] * (n + 1) primes[0] = False primes[1] = False results = [] # List to store the prime numbers for i in range(2, int(n ** 0.5) + 1): if primes[i]: results.append(i) for j in range(i * i, n + 1, i): primes[j] = False return results + [i for i in range(int(n ** 0.5) + 1, n + 1) if primes[i]] def main(): """ Main function """ n = int(input("n: ")) primes = sieve_of_eratosthenes(n) print(primes) if __name__ == "__main__": main() ```
/content/code_sandbox/Week01/vanilla_implementations/sieve_of_eratosthenes.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
245
```python # path_to_url # This is a conceptual code snippet. It won't pass the test cases # due to language limitations. # # Author: Bedir Tapkan def sieveE(n): primes = [0] * (n + 1) primes[0] = 0 primes[1] = 0 for i in range(2, n + 1): if not primes[i]: for j in range(i * i, n + 1, i): if not primes[j]: primes[j] = i # smallest prime factor return primes def factorize(n, primes): """ Return the prime factors of the num n as string including 1 ie. for n=4; 1 x 2 x 2 """ factors = ["1"] while primes[n] != 0 and n % primes[n] == 0: # n is not prime and n is divisible by f factors.append(str(primes[n])) n = n // primes[n] if n != 1: factors.append(str(n)) return " x ".join(factors) def solution(): # Input is until there is no more input given # When reached EOF, break primes = sieveE(10001) while True: try: n = int(input()) if n == 1: print("1") else: print(factorize(n, primes)) except EOFError: break if __name__ == "__main__": solution() ```
/content/code_sandbox/Week01/solutions/medium_factorization.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
336
```python # path_to_url # Finding prime numbers in a range. (Using Sieve of Eratosthenes) # # Author: Bedir Tapkan def sieve_of_eratosthenes(n): """ Sieve of Eratosthenes implementation """ primes = [True] * (n + 1) primes[0] = False primes[1] = False results = [] for i in range(2, int(n ** 0.5) + 1): if primes[i]: # i is prime results.append(i) for j in range(i * i, n + 1, i): primes[j] = False return results + [i for i in range(int(n ** 0.5) + 1, n + 1) if primes[i]] def solution(): """ Given a start and an end point, Prints the prime numbers in between. """ _start = int(input("Start: ")) _end = int(input("End: ")) res = sieve_of_eratosthenes(_end) for i, x in enumerate(res): if x >= _start: start_idx = i break print(res[start_idx:]) if __name__ == "__main__": solution() ```
/content/code_sandbox/Week01/solutions/tiny_implementation.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
283
```python # path_to_url # # Author: Bedir Tapkan def sieveE(n): primes = [True] * (n + 1) primes[0] = False primes[1] = False prime_nums = [] for i in range(2, int(n ** 0.5) + 1): if primes[i]: prime_nums.append(i) for j in range(i * i, n + 1 ,i): primes[j] = False return prime_nums + [i for i in range(int(n**0.5)+1, n+1) if primes[i]], primes # Prime integers, Truth values in a table def noldbach(): primes, primes_table = sieveE(3500) # 1000+ primes n, k = map(int, input().split()) res = 0 for i in range(len(primes)-1): num_check = primes[i] + primes[i+1] + 1 if num_check > n: break if primes_table[num_check]: res += 1 if res >= k: print("YES") else: print("NO") if __name__=="__main__": noldbach() ```
/content/code_sandbox/Week01/solutions/noldbach_problem.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
275
```python # path_to_url # # Author: Bedir Tapkan def sieve_of_eratosthenes_modified(n): """ Sieve of Eratosthenes implementation with a tweak: Instead of true-false calculate the number of prime numbers to generate the composites. """ primes = [0] * (n + 1) primes[0] = -1 primes[1] = -1 for i in range(2, n + 1): if not primes[i]: # 0 for prime for j in range(i + i, n + 1, i): primes[j] += 1 return [i for i in range(2, n + 1) if primes[i] >= 3] def solution(): res = sieve_of_eratosthenes_modified(2700) T = int(input()) for t in range(T): n = int(input()) print(res[n-1]) if __name__ == "__main__": solution() ```
/content/code_sandbox/Week01/solutions/distinct_primes.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
226
```python # Depth First Search (DFS) implementation # # A simple implementation of DFS using a queue # with in depth comments # # Author: BedirT def dfs(graph, start, goal): # Initialize a stack with the start node stack = [start] # Initialize a set to keep track of visited nodes visited = set() # Create a list to keep track of the order in which we visit the nodes # This is not necessary for the algorithm to work visited set is enough # But it is useful for visualization order = [] # While the stack is not empty while stack: # Pop the last element from the stack node = stack.pop() # If the node has not been visited if node not in visited: # Mark the node as visited visited.add(node) # Add the node to the order list order.append(node) # If the node is the goal, return the path if node == goal: return order # Add the neighbors of the node to the stack stack.extend(graph[node]) # If the stack is empty, return None return None if __name__ == "__main__": # Example usage graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] } print(dfs(graph, 'A', 'F')) # Output: ['A', 'C', 'F'] # Another example graph = { 'A': ['B', 'C'], 'B': ['A'], 'C': ['A'], 'G': ['H'], 'H': ['G'] } print(dfs(graph, 'A', 'H')) # Output: None ```
/content/code_sandbox/Week05/vanilla_implementations/dfs.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
423
```python # Breadth First Search (BFS) implementation # # A simple implementation of BFS using a queue # with in depth comments # # Author: BedirT def bfs(graph, start, goal): # Initialize a queue with the start node queue = [start] # Initialize a set to keep track of visited nodes visited = set() # Create a list to keep track of the order in which we visit the nodes # This is not necessary for the algorithm to work visited set is enough # But it is useful for visualization order = [] # While the queue is not empty while queue: # Pop the first element from the queue node = queue.pop(0) # If the node has not been visited if node not in visited: # Mark the node as visited visited.add(node) # Add the node to the order list order.append(node) # If the node is the goal, return the path if node == goal: return order # Add the neighbors of the node to the queue queue.extend(graph[node]) # If the queue is empty, return None return None if __name__ == "__main__": # Example usage graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] } print(bfs(graph, 'A', 'F')) # Output: ['A', 'B', 'C', 'D', 'E', 'F'] # Another example graph = { 'A': ['B', 'C'], 'B': ['A'], 'C': ['A'], 'G': ['H'], 'H': ['G'] } print(bfs(graph, 'A', 'H')) # Output: None ```
/content/code_sandbox/Week05/vanilla_implementations/bfs.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
437
```c++ // Same as the python solution, but in C++. #include <iostream> #include <set> #include <vector> using namespace std; int main() { int n, m; cin >> n >> m; vector<string> graph; for (int i = 0; i < n; i++) { string s; cin >> s; graph.push_back(s); } set<pair<int, int>> visited; int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (visited.find({i, j}) == visited.end()) { set<pair<int, int>> just_visited; pair<int, int> node = {i, j}; while (just_visited.find(node) == just_visited.end()) { if (visited.find(node) != visited.end()) { break; } just_visited.insert(node); visited.insert(node); if (graph[node.first][node.second] == 'N' && node.first > 0) { node = {node.first-1, node.second}; } else if (graph[node.first][node.second] == 'S' && node.first < n-1) { node = {node.first+1, node.second}; } else if (graph[node.first][node.second] == 'E' && node.second < m-1) { node = {node.first, node.second+1}; } else if (graph[node.first][node.second] == 'W' && node.second > 0) { node = {node.first, node.second-1}; } else { break; } } if (just_visited.find(node) != just_visited.end()) { count += 1; } } } } cout << count << endl; return 0; } ```
/content/code_sandbox/Week05/solutions/herding.cpp
c++
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
409
```python # Solving HIKE problem on SPOJ # Note: This solution will not pass SPOJ's time limit due to the use of Python # The solution is correct however SPOJ has very slow Python interpreters import sys mx_number = int(1e9) def solution(): # Read the input until we don't get any more while True: # Read the input line = input() # If n is 0, we are done if line == '0': break # Split the line into a list of strings n, p1, p2, p3 = map(int, line.split()) # Create a list of lists to hold the graph graph = [] # Read the graph for i in range(n): graph.append(list(input().split())) # Queue for BFS queue = [] # Add the starting nodes for each player to the queue queue.extend([p1-1, p2-1, p3-1]) # players are 1-indexed # Create distance list, nxnxn distance = [[[mx_number for i in range(n)] for j in range(n)] for k in range(n)] # Set the distance of the starting nodes to 0 distance[p1-1][p2-1][p3-1] = 0 # While there are still nodes in the queue while queue: a = queue.pop(0) b = queue.pop(0) c = queue.pop(0) for i in range(n): # If the color of the edge between a and i is the same as the color of the edge # between b and c, then we can move a to i. We update the distance and add the # new nodes to the queue only if the distance is less than the current distance. # We do this for all three players. if graph[a][i] == graph[b][c] and distance[a][b][c] + 1 < distance[i][b][c]: distance[i][b][c] = distance[a][b][c] + 1 queue.extend([i, b, c]) if graph[b][i] == graph[a][c] and distance[a][b][c] + 1 < distance[a][i][c]: distance[a][i][c] = distance[a][b][c] + 1 queue.extend([a, i, c]) if graph[c][i] == graph[a][b] and distance[a][b][c] + 1 < distance[a][b][i]: distance[a][b][i] = distance[a][b][c] + 1 queue.extend([a, b, i]) # If the distance from the starting nodes to the same node is less than infinity, then # we can get all three players to the same node. Otherwise, we can't. res = mx_number for i in range(n): res = min(res, distance[i][i][i]) if res == mx_number: print('impossible') else: print(res) if __name__ == "__main__": solution() ```
/content/code_sandbox/Week05/solutions/hike.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
699
```python def main(): n, m = map(int, input().split()) graph = [] for i in range(n): graph.append(input()) visited = set() count = 0 for i in range(n): for j in range(m): if (i, j) not in visited: just_visited = set() node = (i, j) while node not in just_visited: if node in visited: break just_visited.add(node) visited.add(node) if graph[node[0]][node[1]] == 'N' and node[0] > 0: node = (node[0]-1, node[1]) elif graph[node[0]][node[1]] == 'S' and node[0] < n-1: node = (node[0]+1, node[1]) elif graph[node[0]][node[1]] == 'E' and node[1] < m-1: node = (node[0], node[1]+1) elif graph[node[0]][node[1]] == 'W' and node[1] > 0: node = (node[0], node[1]-1) else: break if node in just_visited: count += 1 print(count) if __name__ == "__main__": main() ```
/content/code_sandbox/Week05/solutions/herding.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
298
```python class Solution: def stock_span(self, prices): stack = [] res = [] for i, p in enumerate(prices): res.append(1) # initial val for i while stack and prices[stack[-1]] <= p: top = stack.pop() res[i] += res[top] stack.append(i) return res # Test prices = [100, 80, 60, 70, 60, 75, 85] print(Solution().stock_span(prices)) # Output # [1, 1, 1, 2, 1, 4, 6] prices = [10, 4, 5, 90, 120, 80] print(Solution().stock_span(prices)) # Output # [1, 1, 2, 4, 5, 1] ```
/content/code_sandbox/Week05/solutions/stock_span_problem.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
190
```python class Solution: def largestRectangleArea(self, heights: List[int]) -> int: stack = [] max_area = 0 for i, height in enumerate(heights): s = i while stack and stack[-1][1] > height: idx, h = stack.pop() max_area = max(max_area, h * (i - idx)) s = idx stack.append((s, height)) for idx, h in stack: max_area = max(max_area, h * (len(heights) - idx)) return max_area ```
/content/code_sandbox/Week05/solutions/largest_rectangle.py
python
2016-05-01T22:57:08
2024-08-13T22:32:54
ACM-ICPC-Preparation
BedirT/ACM-ICPC-Preparation
2,102
125
```qmake # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/olegbeloy/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in createLayouter.gradle. # # For more details, see # path_to_url # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ```
/content/code_sandbox/sample/proguard-rules.pro
qmake
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
145
```java package com.beloo.chipslayoutmanager.sample; import com.google.firebase.crash.FirebaseCrash; public class Application extends android.app.Application { @Override public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler((t, e) -> { if (BuildConfig.isReportCrashes) { FirebaseCrash.report(e); } }); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/Application.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
81
```java package com.beloo.chipslayoutmanager.sample.entity; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; public class ChipsEntity implements Parcelable { @DrawableRes private Integer drawableResId; @Nullable private String description; @NonNull private String name; public Integer getDrawableResId() { return drawableResId; } @Nullable public String getDescription() { return description; } @NonNull public String getName() { return name; } public void setName(@NonNull String name) { this.name = name; } private ChipsEntity(Builder builder) { drawableResId = builder.drawableResId; description = builder.description; name = builder.name; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private int drawableResId; private String description; private String name; private Builder() { } @NonNull public Builder drawableResId(int drawableResId) { this.drawableResId = drawableResId; return this; } public Builder name(@NonNull String name) { this.name = name; return this; } @NonNull public Builder description(@Nullable String description) { this.description = description; return this; } @NonNull public ChipsEntity build() { return new ChipsEntity(this); } } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.drawableResId); dest.writeString(this.description); dest.writeString(this.name); } protected ChipsEntity(Parcel in) { this.drawableResId = in.readInt(); this.description = in.readString(); this.name = in.readString(); } public static final Parcelable.Creator<ChipsEntity> CREATOR = new Parcelable.Creator<ChipsEntity>() { @Override public ChipsEntity createFromParcel(Parcel source) { return new ChipsEntity(source); } @Override public ChipsEntity[] newArray(int size) { return new ChipsEntity[size]; } }; } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/entity/ChipsEntity.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
488
```java package com.beloo.chipslayoutmanager.sample; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; public class CircleTransform extends BitmapTransformation { public CircleTransform(Context context) { super(context); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return circleCrop(pool, toTransform); } private static Bitmap circleCrop(BitmapPool pool, Bitmap source) { if (source == null) return null; int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; // TODO this could be acquired from the pool too Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); return result; } @Override public String getId() { return getClass().getName(); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/CircleTransform.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
348
```java package com.beloo.chipslayoutmanager.sample.ui; public interface OnRemoveListener { void onItemRemoved(int position); } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/OnRemoveListener.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
27
```java package com.beloo.chipslayoutmanager.sample.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import com.beloo.widget.chipslayoutmanager.BuildConfig; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.DrawerBuilder; import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.beloo.chipslayoutmanager.sample.R; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { @BindView(R.id.toolbar) Toolbar toolbar; private Drawer drawer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); toolbar.setTitle(getString(R.string.app_name_and_version, BuildConfig.VERSION_NAME)); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.fragmentContainer, ItemsFragment.newInstance()) .commit(); } setSupportActionBar(toolbar); assert getSupportActionBar() != null; getSupportActionBar().setDisplayHomeAsUpEnabled(true); drawer = new DrawerBuilder(this) .withToolbar(toolbar) .addDrawerItems(new PrimaryDrawerItem().withName(R.string.main).withIdentifier(1)) .addDrawerItems(new PrimaryDrawerItem().withName(R.string.bottom_sheet).withIdentifier(2)) .withOnDrawerItemClickListener(this::onDrawerItemClickListener) .build(); } private boolean onDrawerItemClickListener(View view, int position, IDrawerItem drawerItem) { int id = (int) drawerItem.getIdentifier(); switch (id) { case 1: getSupportFragmentManager().beginTransaction() .replace(R.id.fragmentContainer, ItemsFragment.newInstance()) .commit(); drawer.closeDrawer(); break; case 2: getSupportFragmentManager().beginTransaction() .replace(R.id.fragmentContainer, BottomSheetFragment.newInstance()) .commit(); drawer.closeDrawer(); break; } return true; } @Override protected void onResumeFragments() { super.onResumeFragments(); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/MainActivity.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
455
```java package com.beloo.chipslayoutmanager.sample.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.BottomSheetBehavior; import android.support.v4.app.Fragment; import android.support.v4.widget.NestedScrollView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; import com.beloo.chipslayoutmanager.sample.ui.adapter.ChipsAdapter; import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration; import java.util.List; import com.beloo.chipslayoutmanager.sample.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** */ public class BottomSheetFragment extends Fragment { public BottomSheetFragment() { // Required empty public constructor } public static BottomSheetFragment newInstance() { Bundle args = new Bundle(); BottomSheetFragment fragment = new BottomSheetFragment(); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_bottom_sheet, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); } @OnClick(R.id.btnShowSheet) void onShowSheetClicked(View view) { BottomSheetDialogFragment fragment = BottomSheetDialogFragment.newInstance(); fragment.show(getChildFragmentManager(), fragment.getTag()); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/BottomSheetFragment.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
341
```java package com.beloo.chipslayoutmanager.sample.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.annotation.RestrictTo; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Spinner; import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager; import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.beloo.chipslayoutmanager.sample.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** */ public class ItemsFragment extends Fragment { private static final String EXTRA = "data"; @BindView(R.id.rvTest) RecyclerView rvTest; @BindView(R.id.spinnerPosition) Spinner spinnerPosition; @BindView(R.id.spinnerMoveTo) Spinner spinnerMoveTo; private RecyclerView.Adapter adapter; private List<String> positions; private List items; /** replace here different data sets */ private IItemsFactory itemsFactory = new ShortChipsFactory(); @RestrictTo(RestrictTo.Scope.SUBCLASSES) public ItemsFragment() { // Required empty public constructor } public static ItemsFragment newInstance() { return new ItemsFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_items, container, false); } @SuppressWarnings("unchecked") private RecyclerView.Adapter createAdapter(Bundle savedInstanceState) { List<String> items; if (savedInstanceState == null) { // items = itemsFactory.getFewItems(); // items = itemsFactory.getALotOfItems(); items = itemsFactory.getItems(); } else { items = savedInstanceState.getStringArrayList(EXTRA); } adapter = itemsFactory.createAdapter(items, onRemoveListener); this.items = items; return adapter; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); adapter = createAdapter(savedInstanceState); ChipsLayoutManager spanLayoutManager = ChipsLayoutManager.newBuilder(getContext()) .setOrientation(ChipsLayoutManager.HORIZONTAL) .build(); rvTest.addItemDecoration(new SpacingItemDecoration(getResources().getDimensionPixelOffset(R.dimen.item_space), getResources().getDimensionPixelOffset(R.dimen.item_space))); positions = new LinkedList<>(); for (int i = 0; i< items.size(); i++) { positions.add(String.valueOf(i)); } ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, android.R.id.text1, positions); ArrayAdapter<String> spinnerAdapterMoveTo = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, android.R.id.text1, positions); spinnerPosition.setAdapter(spinnerAdapter); spinnerMoveTo.setAdapter(spinnerAdapterMoveTo); rvTest.setLayoutManager(spanLayoutManager); rvTest.getRecycledViewPool().setMaxRecycledViews(0, 10); rvTest.getRecycledViewPool().setMaxRecycledViews(1, 10); rvTest.setAdapter(adapter); } private OnRemoveListener onRemoveListener = new OnRemoveListener() { @Override public void onItemRemoved(int position) { items.remove(position); Log.i("activity", "delete at " + position); adapter.notifyItemRemoved(position); updateSpinners(); } }; @Override @SuppressWarnings("unchecked") public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelableArrayList(EXTRA, new ArrayList<>(items)); } private void updateSpinners() { positions = new LinkedList<>(); for (int i = 0; i< items.size(); i++) { positions.add(String.valueOf(i)); } int selectedPosition = Math.min(spinnerPosition.getSelectedItemPosition(), positions.size() - 1); int selectedMoveToPosition = Math.min(spinnerMoveTo.getSelectedItemPosition(), positions.size() -1); ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, android.R.id.text1, positions); spinnerPosition.setAdapter(spinnerAdapter); selectedPosition = Math.min(spinnerAdapter.getCount() -1 , selectedPosition); spinnerPosition.setSelection(selectedPosition); ArrayAdapter<String> spinnerAdapterMoveTo = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, android.R.id.text1, positions); spinnerMoveTo.setAdapter(spinnerAdapterMoveTo); spinnerMoveTo.setSelection(selectedMoveToPosition); } @OnClick(R.id.btnRevert) public void onRevertClicked(View view) { int position = spinnerPosition.getSelectedItemPosition(); if (position == Spinner.INVALID_POSITION) return; int positionMoveTo = spinnerMoveTo.getSelectedItemPosition(); if (positionMoveTo == Spinner.INVALID_POSITION) return; if (position == positionMoveTo) return; spinnerPosition.setSelection(positionMoveTo); spinnerMoveTo.setSelection(position); } @OnClick(R.id.btnDelete) public void onDeleteClicked(View view) { int position = spinnerPosition.getSelectedItemPosition(); if (position == Spinner.INVALID_POSITION) return; items.remove(position); Log.i("activity", "delete at " + position); adapter.notifyItemRemoved(position); updateSpinners(); } @OnClick(R.id.btnMove) public void onMoveClicked(View view) { int position = spinnerPosition.getSelectedItemPosition(); if (position == Spinner.INVALID_POSITION) return; int positionMoveTo = spinnerMoveTo.getSelectedItemPosition(); if (positionMoveTo == Spinner.INVALID_POSITION) return; if (position == positionMoveTo) return; Object item = items.remove(position); items.add(positionMoveTo, item); adapter.notifyItemMoved(position, positionMoveTo); } @OnClick(R.id.btnScroll) public void onScrollClicked(View view) { // rvTest.scrollBy(0, 500); rvTest.scrollToPosition(spinnerPosition.getSelectedItemPosition()); } @OnClick(R.id.btnInsert) public void onInsertClicked(View view) { int position = spinnerPosition.getSelectedItemPosition(); if (position == Spinner.INVALID_POSITION) position = 0; items.add(position, itemsFactory.createOneItemForPosition(position)); Log.i("activity", "insert at " + position); adapter.notifyItemInserted(position); updateSpinners(); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/ItemsFragment.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
1,415
```java package com.beloo.chipslayoutmanager.sample.ui; import android.support.v7.widget.RecyclerView; import java.util.LinkedList; import java.util.List; import java.util.Random; import com.beloo.chipslayoutmanager.sample.ui.adapter.RecyclerViewAdapter; public class ItemsFactory implements IItemsFactory<String> { public List<String> getItems() { List<String> list = new LinkedList<>(); list.add("Item0.0"); list.add("Item1.1"); list.add("Item2.2"); list.add("Item3.3"); list.add("Item4.4"); list.add("!Item5.5"); list.add("Item6.6"); list.add("Item7.7"); list.add("Item8.8"); list.add("Item9.9"); list.add("Item10.10"); list.add("!Item11.11"); list.add("Item12.12"); list.add("Item1001.13"); list.add("Item1002.14"); list.add("Item1003.15"); list.add("!Item1004.16"); list.add("!Item10001.17"); list.add("Item10002.18"); list.add("Item19"); list.add("Item20"); list.add("Item21"); list.add("Item22"); list.add("Item23"); list.add("Item24"); list.add("Item25"); list.add("Item26"); list.add("Item27"); return list; } @Override public List<String> getDoubleItems() { throw new UnsupportedOperationException("not implemented"); } public List<String> getFewItems() { List<String> list = new LinkedList<>(); list.add("Item0.0"); list.add("Item1.1"); list.add("Item2.2"); list.add("Item3.3"); return list; } public List<String> getALotOfItems() { List<String> list = new LinkedList<>(); list.add("START item.0"); list.add("!tall item here. 1"); for (int i = 2; i< 1000; i++) { if (i%3 == 0) { list.add("!tall item here." + i); } else if (i % 5 == 0) { list.add("S." + i); } else { list.add("a span." + i); } } return list; } public List<String> getALotOfRandomItems() { List<String> list = new LinkedList<>(); list.add("START item.0"); for (int i =0; i< 1000; i++) { Random random = new Random(); int rand = random.nextInt(3); switch (rand) { case 1: list.add("a span." + (i+1)); break; case 2: list.add("!tall item here." + (i+1)); break; default: list.add("S." + (i+1)); break; } } return list; } @Override public String createOneItemForPosition(int position) { return "inserted item." + position; } @Override public RecyclerView.Adapter<? extends RecyclerView.ViewHolder> createAdapter(List<String> items, OnRemoveListener onRemoveListener) { return new RecyclerViewAdapter(items, onRemoveListener); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/ItemsFactory.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
751
```java package com.beloo.chipslayoutmanager.sample.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager; import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration; import java.util.List; import com.beloo.chipslayoutmanager.sample.R; import butterknife.BindView; import butterknife.ButterKnife; public class BottomSheetDialogFragment extends android.support.design.widget.BottomSheetDialogFragment { @BindView(R.id.rvBottomSheet) RecyclerView rvBottomSheet; private IItemsFactory itemsFactory = new ChipsFactory(); private RecyclerView.Adapter adapter; public static BottomSheetDialogFragment newInstance() { Bundle args = new Bundle(); BottomSheetDialogFragment fragment = new BottomSheetDialogFragment(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_bottom_sheet_modal, container, false); ButterKnife.bind(this, view); return view; } @SuppressWarnings("unchecked") private RecyclerView.Adapter createAdapter() { // List<String> items = itemsFactory.getDoubleItems(); List<String> items = itemsFactory.getItems(); adapter = itemsFactory.createAdapter(items, null); return adapter; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); ChipsLayoutManager layoutManager = ChipsLayoutManager.newBuilder(getContext()).build(); rvBottomSheet.setLayoutManager(layoutManager); rvBottomSheet.setAdapter(createAdapter()); rvBottomSheet.addItemDecoration(new SpacingItemDecoration(getResources().getDimensionPixelOffset(R.dimen.item_space), getResources().getDimensionPixelOffset(R.dimen.item_space))); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/BottomSheetDialogFragment.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
407
```java package com.beloo.chipslayoutmanager.sample.ui; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import com.beloo.chipslayoutmanager.sample.R; import com.beloo.chipslayoutmanager.sample.ui.adapter.ChipsAdapter; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; class ShortChipsFactory implements IItemsFactory<ChipsEntity> { @Override public List<ChipsEntity> getFewItems() { List<ChipsEntity> chipsList = new ArrayList<>(); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.batman) .name("Batman") .build()); chipsList.add(ChipsEntity.newBuilder() .name("V") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl2) .name("Jayne") .description("Everyone want to meet Jayne") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl3) .name("Cat") .build()); chipsList.add(ChipsEntity.newBuilder() .name("J") .build()); chipsList.add(ChipsEntity.newBuilder() .name("A") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.batman) .name("Second Batman") .description("Batman is our friend") .build()); chipsList.add(ChipsEntity.newBuilder() .name("C") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.karl) .name("Karl") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.anonymous) .name("Very Long Name Anonymous") .build()); return chipsList; } @Override public List<ChipsEntity> getItems() { List<ChipsEntity> chipsEntities = getFewItems(); List<ChipsEntity> secondPortion = getFewItems(); Collections.reverse(secondPortion); chipsEntities.addAll(secondPortion); chipsEntities.addAll(getFewItems()); chipsEntities.addAll(getFewItems()); for (int i=0; i< chipsEntities.size(); i++) { ChipsEntity chipsEntity = chipsEntities.get(i); chipsEntity.setName(chipsEntity.getName() + " " + i); } return chipsEntities; } @Override public List<ChipsEntity> getDoubleItems() { List<ChipsEntity> chipsEntities = getFewItems(); List<ChipsEntity> secondPortion = getFewItems(); Collections.reverse(secondPortion); chipsEntities.addAll(secondPortion); return chipsEntities; } @Override public List<ChipsEntity> getALotOfItems() { List<ChipsEntity> entities = new LinkedList<>(); for (int i=0; i < 5; i++){ entities.addAll(getItems()); } return entities; } @Override public List<ChipsEntity> getALotOfRandomItems() { throw new UnsupportedOperationException("not implemented"); } @Override public ChipsEntity createOneItemForPosition(int position) { return ChipsEntity.newBuilder() .name("Newbie " + position) .drawableResId(R.drawable.china_girl) .build(); } @Override public RecyclerView.Adapter<? extends RecyclerView.ViewHolder> createAdapter(List<ChipsEntity> chipsEntities, OnRemoveListener onRemoveListener) { return new ChipsAdapter(chipsEntities, onRemoveListener); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/ShortChipsFactory.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
805
```java package com.beloo.chipslayoutmanager.sample.ui; import android.support.v7.widget.RecyclerView; import java.util.List; public interface IItemsFactory<Item> { List<Item> getFewItems(); List<Item> getItems(); List<Item> getDoubleItems(); List<Item> getALotOfItems(); List<Item> getALotOfRandomItems(); Item createOneItemForPosition(int position); RecyclerView.Adapter<? extends RecyclerView.ViewHolder> createAdapter(List<Item> items, OnRemoveListener onRemoveListener); } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/IItemsFactory.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
110
```java package com.beloo.chipslayoutmanager.sample.ui; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.beloo.chipslayoutmanager.sample.R; import com.beloo.chipslayoutmanager.sample.ui.adapter.ChipsAdapter; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; public class TallChipsFactory implements IItemsFactory<ChipsEntity> { @Override public List<ChipsEntity> getFewItems() { List<ChipsEntity> chipsList = new ArrayList<>(); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.batman) .name("Batman") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl1) .name("Veronic Cloyd") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl2) .name("Jayne") .description("Everyone want to meet Jayne because Jayne is cute. And other long text below\nYep it is") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl3) .name("Cat") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl2) .name("Jess") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl4) .name("Ann Ackerman") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.batman) .name("Second Batman") .description("Batman is our friend. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore ") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl5) .name("Claudette") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.karl) .name("Karl") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.anonymous) .name("Very Long Name Anonymous") .build()); return chipsList; } @Override public List<ChipsEntity> getItems() { List<ChipsEntity> chipsEntities = getFewItems(); List<ChipsEntity> secondPortion = getFewItems(); Collections.reverse(secondPortion); chipsEntities.addAll(secondPortion); chipsEntities.addAll(getFewItems()); chipsEntities.addAll(getFewItems()); // for (int i=0; i< chipsEntities.size(); i++) { // ChipsEntity chipsEntity = chipsEntities.get(i); // chipsEntity.setName(chipsEntity.getName() + " " + i); // } return chipsEntities; } @Override public List<ChipsEntity> getDoubleItems() { List<ChipsEntity> chipsEntities = getFewItems(); List<ChipsEntity> secondPortion = getFewItems(); Collections.reverse(secondPortion); chipsEntities.addAll(secondPortion); return chipsEntities; } @Override public List<ChipsEntity> getALotOfItems() { throw new UnsupportedOperationException("not implemented"); } @Override public List<ChipsEntity> getALotOfRandomItems() { throw new UnsupportedOperationException("not implemented"); } @Override public ChipsEntity createOneItemForPosition(int position) { return ChipsEntity.newBuilder() .name("Newbie " + position) .drawableResId(R.drawable.china_girl) .build(); } @Override public RecyclerView.Adapter<? extends RecyclerView.ViewHolder> createAdapter(List<ChipsEntity> chipsEntities, OnRemoveListener onRemoveListener) { return new ChipsAdapter(chipsEntities, onRemoveListener); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/TallChipsFactory.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
858
```java package com.beloo.chipslayoutmanager.sample.ui.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import java.util.List; import com.beloo.chipslayoutmanager.sample.ui.OnRemoveListener; import com.beloo.chipslayoutmanager.sample.R; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { private static String TAG = RecyclerViewAdapter.class.getSimpleName(); private int viewHolderCount; private final int ITEM_TYPE_DEFAULT = 0; private final int ITEM_TYPE_INCREASED = 1; private List<String> items; private OnRemoveListener onRemoveListener; public RecyclerViewAdapter(List<String> items, OnRemoveListener onRemoveListener) { this.items = items; this.onRemoveListener = onRemoveListener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView; switch (viewType) { case ITEM_TYPE_INCREASED: itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_increased, parent, false); break; default: itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_simple, parent, false); break; } viewHolderCount++; // Timber.w(TAG, "created holders = " + viewHolderCount); return new ViewHolder(itemView); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.bindItem(items.get(position)); } @Override public int getItemViewType(int position) { String item = items.get(position); if (item.startsWith("!")) { return ITEM_TYPE_INCREASED; } return ITEM_TYPE_DEFAULT; } @Override public int getItemCount() { return items.size(); } class ViewHolder extends RecyclerView.ViewHolder { private TextView tvText; private ImageButton ibClose; ViewHolder(View itemView) { super(itemView); tvText = (TextView) itemView.findViewById(R.id.tvText); ibClose = (ImageButton) itemView.findViewById(R.id.ibClose); ibClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = getAdapterPosition(); if (position != -1) { onRemoveListener.onItemRemoved(position); } } }); } void bindItem(String text) { tvText.setText(text); } } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/adapter/RecyclerViewAdapter.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
514
```java package com.beloo.chipslayoutmanager.sample.ui; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import com.beloo.chipslayoutmanager.sample.ui.adapter.ChipsAdapter; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; import com.beloo.chipslayoutmanager.sample.R; class ChipsFactory implements IItemsFactory<ChipsEntity> { @Override public List<ChipsEntity> getFewItems() { List<ChipsEntity> chipsList = new ArrayList<>(); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.batman) .name("Batman") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl1) .name("Veronic Cloyd") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl2) .name("Jayne") .description("Everyone want to meet Jayne") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl3) .name("Cat") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl2) .name("Jess") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl4) .name("Ann Ackerman") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.batman) .name("Second Batman") .description("Batman is our friend") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.girl5) .name("Claudette") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.karl) .name("Karl") .build()); chipsList.add(ChipsEntity.newBuilder() .drawableResId(R.drawable.anonymous) .name("Very Long Name Anonymous") .build()); return chipsList; } @Override public List<ChipsEntity> getItems() { List<ChipsEntity> chipsEntities = getFewItems(); List<ChipsEntity> secondPortion = getFewItems(); Collections.reverse(secondPortion); chipsEntities.addAll(secondPortion); chipsEntities.addAll(getFewItems()); chipsEntities.addAll(getFewItems()); for (int i=0; i< chipsEntities.size(); i++) { ChipsEntity chipsEntity = chipsEntities.get(i); chipsEntity.setName(chipsEntity.getName() + " " + i); } return chipsEntities; } @Override public List<ChipsEntity> getDoubleItems() { List<ChipsEntity> chipsEntities = getFewItems(); List<ChipsEntity> secondPortion = getFewItems(); Collections.reverse(secondPortion); chipsEntities.addAll(secondPortion); return chipsEntities; } @Override public List<ChipsEntity> getALotOfItems() { List<ChipsEntity> entities = new LinkedList<>(); for (int i=0; i < 5; i++){ entities.addAll(getItems()); } return entities; } @Override public List<ChipsEntity> getALotOfRandomItems() { throw new UnsupportedOperationException("not implemented"); } @Override public ChipsEntity createOneItemForPosition(int position) { return ChipsEntity.newBuilder() .name("Newbie " + position) .drawableResId(R.drawable.china_girl) .build(); } @Override public RecyclerView.Adapter<? extends RecyclerView.ViewHolder> createAdapter(List<ChipsEntity> chipsEntities, OnRemoveListener onRemoveListener) { return new ChipsAdapter(chipsEntities, onRemoveListener); } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/ChipsFactory.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
854
```java package com.beloo.chipslayoutmanager.sample.ui.adapter; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.List; import com.beloo.chipslayoutmanager.sample.ui.OnRemoveListener; import com.beloo.chipslayoutmanager.sample.R; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; import com.beloo.chipslayoutmanager.sample.CircleTransform; public class ChipsAdapter extends RecyclerView.Adapter<ChipsAdapter.ViewHolder> { private List<ChipsEntity> chipsEntities; private OnRemoveListener onRemoveListener; private boolean isShowingPosition; public ChipsAdapter(List<ChipsEntity> chipsEntities, OnRemoveListener onRemoveListener) { this.chipsEntities = chipsEntities; this.onRemoveListener = onRemoveListener; } public ChipsAdapter(List<ChipsEntity> chipsEntities, OnRemoveListener onRemoveListener, boolean isShowingPosition) { this.chipsEntities = chipsEntities; this.onRemoveListener = onRemoveListener; this.isShowingPosition = isShowingPosition; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chip, parent, false); return new ViewHolder(itemView); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.bindItem(chipsEntities.get(position)); } @Override public int getItemCount() { return chipsEntities.size(); } class ViewHolder extends RecyclerView.ViewHolder { private TextView tvDescription; private ImageView ivPhoto; private TextView tvName; private ImageButton ibClose; private TextView tvPosition; ViewHolder(View itemView) { super(itemView); tvDescription = (TextView) itemView.findViewById(R.id.tvDescription); ivPhoto = (ImageView) itemView.findViewById(R.id.ivPhoto); tvName = (TextView) itemView.findViewById(R.id.tvName); ibClose = (ImageButton) itemView.findViewById(R.id.ibClose); tvPosition = (TextView) itemView.findViewById(R.id.tvPosition); } void bindItem(ChipsEntity entity) { itemView.setTag(entity.getName()); if (TextUtils.isEmpty(entity.getDescription())) { tvDescription.setVisibility(View.GONE); } else { tvDescription.setVisibility(View.VISIBLE); tvDescription.setText(entity.getDescription()); } if (entity.getDrawableResId() != 0) { ivPhoto.setVisibility(View.VISIBLE); Glide.with(ivPhoto.getContext()).load(entity.getDrawableResId()) .transform(new CircleTransform(ivPhoto.getContext())).into(ivPhoto); } else { ivPhoto.setVisibility(View.GONE); } tvName.setText(entity.getName()); if (isShowingPosition) { tvPosition.setText(String.valueOf(getAdapterPosition())); } ibClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (onRemoveListener != null && getAdapterPosition() != -1) { onRemoveListener.onItemRemoved(getAdapterPosition()); } } }); } } } ```
/content/code_sandbox/sample/src/main/java/com/beloo/chipslayoutmanager/sample/ui/adapter/ChipsAdapter.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
668
```java package com.beloo.chipslayoutmanager.sample.ui; import android.support.v7.widget.RecyclerView; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; import java.util.List; public class FewChipsFacade implements IItemsFacade<ChipsEntity> { private ChipsFactory chipsFactory = new ChipsFactory(); @Override public List<ChipsEntity> getItems() { return chipsFactory.getFewItems(); } @Override public RecyclerView.Adapter<? extends RecyclerView.ViewHolder> createAdapter(List<ChipsEntity> chipsEntities, OnRemoveListener onRemoveListener) { return chipsFactory.createAdapter(chipsEntities, onRemoveListener); } @Override public ChipsEntity createOneItemForPosition(int position) { return chipsFactory.createOneItemForPosition(position); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/chipslayoutmanager/sample/ui/FewChipsFacade.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
171
```java package com.beloo.chipslayoutmanager.sample.ui; import android.content.Context; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v7.widget.RecyclerView; import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager; @VisibleForTesting public class LayoutManagerFactory { @Nullable public RecyclerView.LayoutManager layoutManager(Context context) { return ChipsLayoutManager.newBuilder(context) .setOrientation(ChipsLayoutManager.HORIZONTAL) .build(); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/chipslayoutmanager/sample/ui/LayoutManagerFactory.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
101
```java package com.beloo.chipslayoutmanager.sample.ui; import android.support.v7.widget.RecyclerView; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; import java.util.List; public class ChipsFacade implements IItemsFacade<ChipsEntity> { private ChipsFactory chipsFactory = new ChipsFactory(); @Override public List<ChipsEntity> getItems() { return chipsFactory.getItems(); } @Override public RecyclerView.Adapter<? extends RecyclerView.ViewHolder> createAdapter(List<ChipsEntity> chipsEntities, OnRemoveListener onRemoveListener) { return chipsFactory.createAdapter(chipsEntities, onRemoveListener); } @Override public ChipsEntity createOneItemForPosition(int position) { return chipsFactory.createOneItemForPosition(position); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/chipslayoutmanager/sample/ui/ChipsFacade.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
167
```java package com.beloo.chipslayoutmanager.sample.ui; import android.support.v7.widget.RecyclerView; import java.util.List; public interface IItemsFacade<Item> { List<Item> getItems(); RecyclerView.Adapter<? extends RecyclerView.ViewHolder> createAdapter(List<Item> chipsEntities, OnRemoveListener onRemoveListener); Item createOneItemForPosition(int position); } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/chipslayoutmanager/sample/ui/IItemsFacade.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
74
```java package com.beloo.chipslayoutmanager.sample.ui; import android.support.annotation.UiThread; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.beloo.chipslayoutmanager.sample.R; public class TestActivity extends AppCompatActivity { private static final String EXTRA = "data"; private RecyclerView rvTest; private RecyclerView.Adapter adapter; private Spinner spinnerPosition; private Spinner spinnerMoveTo; private List<String> positions; private List items; /** replace here different data sets */ static IItemsFacade itemsFactory = new FewChipsFacade(); static LayoutManagerFactory lmFactory = new LayoutManagerFactory(); public static boolean isInitializeOutside; private OnRemoveListener onRemoveListener = new OnRemoveListener() { @Override public void onItemRemoved(int position) { items.remove(position); Log.i("activity", "delete at " + position); adapter.notifyItemRemoved(position); updateSpinners(); } }; public static void setLmFactory(LayoutManagerFactory lmFactory) { TestActivity.lmFactory = lmFactory; } public static void setItemsFactory(IItemsFacade itemsFactory) { TestActivity.itemsFactory = itemsFactory; } @SuppressWarnings("unchecked") private RecyclerView.Adapter createAdapter() { if (items == null) { items = itemsFactory.getItems(); } adapter = itemsFactory.createAdapter(items, onRemoveListener); return adapter; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { items = savedInstanceState.getParcelableArrayList(EXTRA); } setContentView(R.layout.activity_test); rvTest = (RecyclerView) findViewById(R.id.rvTest); spinnerPosition = (Spinner) findViewById(R.id.spinnerPosition); spinnerMoveTo = (Spinner) findViewById(R.id.spinnerMoveTo); if (!isInitializeOutside || savedInstanceState != null) { initialize(); } } @UiThread public void initialize() { initRv(); } @UiThread private void initRv() { adapter = createAdapter(); RecyclerView.LayoutManager layoutManager = lmFactory.layoutManager(this); if (layoutManager == null) Log.e("initRv", "lm manager is null"); rvTest.addItemDecoration(new SpacingItemDecoration(getResources().getDimensionPixelOffset(R.dimen.item_space), getResources().getDimensionPixelOffset(R.dimen.item_space))); positions = new LinkedList<>(); for (int i = 0; i< items.size(); i++) { positions.add(String.valueOf(i)); } ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, positions); ArrayAdapter<String> spinnerAdapterMoveTo = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, positions); spinnerPosition.setAdapter(spinnerAdapter); spinnerMoveTo.setAdapter(spinnerAdapterMoveTo); rvTest.setLayoutManager(layoutManager); // rvTest.setLayoutManager(new LinearLayoutManager(this)); rvTest.getRecycledViewPool().setMaxRecycledViews(0, 10); rvTest.getRecycledViewPool().setMaxRecycledViews(1, 10); rvTest.setAdapter(adapter); } @Override @SuppressWarnings("unchecked") protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (items == null) { Log.e("onSaveInstanceState", "possible problem due to rotation test runned before"); } else { outState.putParcelableArrayList(EXTRA, new ArrayList<>(items)); } } private void updateSpinners() { positions = new LinkedList<>(); for (int i = 0; i< items.size(); i++) { positions.add(String.valueOf(i)); } int selectedPosition = Math.min(spinnerPosition.getSelectedItemPosition(), positions.size() - 1); int selectedMoveToPosition = Math.min(spinnerMoveTo.getSelectedItemPosition(), positions.size() -1); ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, positions); spinnerPosition.setAdapter(spinnerAdapter); selectedPosition = Math.min(spinnerAdapter.getCount() -1 , selectedPosition); spinnerPosition.setSelection(selectedPosition); ArrayAdapter<String> spinnerAdapterMoveTo = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, positions); spinnerMoveTo.setAdapter(spinnerAdapterMoveTo); spinnerMoveTo.setSelection(selectedMoveToPosition); } public void onRevertClicked(View view) { int position = spinnerPosition.getSelectedItemPosition(); if (position == Spinner.INVALID_POSITION) return; int positionMoveTo = spinnerMoveTo.getSelectedItemPosition(); if (positionMoveTo == Spinner.INVALID_POSITION) return; if (position == positionMoveTo) return; spinnerPosition.setSelection(positionMoveTo); spinnerMoveTo.setSelection(position); } public void onDeleteClicked(View view) { int position = spinnerPosition.getSelectedItemPosition(); if (position == Spinner.INVALID_POSITION) return; items.remove(position); Log.i("activity", "delete at " + position); adapter.notifyItemRemoved(position); updateSpinners(); } public void onMoveClicked(View view) { int position = spinnerPosition.getSelectedItemPosition(); if (position == Spinner.INVALID_POSITION) return; int positionMoveTo = spinnerMoveTo.getSelectedItemPosition(); if (positionMoveTo == Spinner.INVALID_POSITION) return; if (position == positionMoveTo) return; Object item = items.remove(position); items.add(positionMoveTo, item); adapter.notifyItemMoved(position, positionMoveTo); } public void onScrollClicked(View view) { rvTest.scrollToPosition(spinnerPosition.getSelectedItemPosition()); } public void onInsertClicked(View view) { int position = spinnerPosition.getSelectedItemPosition(); if (position == Spinner.INVALID_POSITION) position = 0; items.add(position, itemsFactory.createOneItemForPosition(position)); Log.i("activity", "insert at " + position); adapter.notifyItemInserted(position); updateSpinners(); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/chipslayoutmanager/sample/ui/TestActivity.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
1,364
```java package com.beloo.widget.chipslayoutmanager; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Rect; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.ViewAction; import android.support.test.espresso.ViewInteraction; import android.support.test.espresso.contrib.RecyclerViewActions; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.v7.widget.RecyclerView; import android.view.View; import com.beloo.chipslayoutmanager.sample.R; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; import com.beloo.chipslayoutmanager.sample.ui.ChipsFacade; import com.beloo.chipslayoutmanager.sample.ui.LayoutManagerFactory; import com.beloo.chipslayoutmanager.sample.ui.TestActivity; import com.beloo.chipslayoutmanager.sample.ui.adapter.ChipsAdapter; import com.beloo.widget.chipslayoutmanager.util.InstrumentalUtil; import com.beloo.test.util.RecyclerViewEspressoFactory; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import java.util.List; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static com.beloo.test.util.RecyclerViewEspressoFactory.*; /** */ @RunWith(AndroidJUnit4.class) public class ColumnTest { static { TestActivity.isInitializeOutside = true; } @Rule public ActivityTestRule<TestActivity> activityTestRule = new ActivityTestRule<>(TestActivity.class); private TestActivity activity; private List<ChipsEntity> items; private ChipsLayoutManager layoutManager; private ViewInteraction recyclerView; @Before public void setUp() throws Throwable { MockitoAnnotations.initMocks(this); activity = activityTestRule.getActivity(); recyclerView = onView(withId(R.id.rvTest)).check(matches(isDisplayed())); layoutManager = getLayoutManager(); LayoutManagerFactory layoutManagerFactory = new LayoutManagerFactory() { @Override public RecyclerView.LayoutManager layoutManager(Context context) { //we need clean layout manager for each request return retrieveLayoutManager(); } }; //set items ChipsFacade chipsFacade = spy(new ChipsFacade()); items = chipsFacade.getItems(); when(chipsFacade.getItems()).thenReturn(items); TestActivity.setItemsFactory(chipsFacade); TestActivity.setLmFactory(layoutManagerFactory); activity.runOnUiThread(() -> activity.initialize()); } private RecyclerView.LayoutManager retrieveLayoutManager() { this.layoutManager = getLayoutManager(); return layoutManager; } private ChipsLayoutManager getLayoutManager() { if (activityTestRule.getActivity() == null) return null; return ChipsLayoutManager.newBuilder(activityTestRule.getActivity()) .setOrientation(ChipsLayoutManager.VERTICAL) .build(); } @Test public void layouting_ScrollForwardAndBackward_VerifyCorrectOrder () throws Exception { //arrange InstrumentalUtil.waitForIdle(); //act recyclerView.perform(scrollBy(1000, 0)); recyclerView.perform(scrollBy(-1000, 0)); //assert recyclerView.check(matches(incrementOrder())); } /////////////////////////////////////////////////////////////////////////// // scrolling /////////////////////////////////////////////////////////////////////////// @Test public void your_sha256_hashVisibleItem() throws Exception { //arrange InstrumentalUtil.waitForIdle(); //act recyclerView.perform(scrollBy(300, 0)); int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); //assert assertEquals(9, actual); } @Test public void your_sha256_hashibleItem() throws Exception { //arrange InstrumentalUtil.waitForIdle(); recyclerView.perform(scrollBy(1000, 0)); //act recyclerView.perform(scrollBy(-1000, 0)); int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); //assert assertEquals(0, actual); } @Test public void your_sha256_hashstItemSize() throws Exception { //arrange //act recyclerView.perform(RecyclerViewActions.scrollToPosition(36), scrollBy(0, -200), scrollBy(0, 200)); //assert recyclerView.check(matches(atPosition(39, rvPaddingMatcher()))); } private ViewHolderMatcher<RecyclerView.ViewHolder> rvPaddingMatcher() { return new RecyclerViewEspressoFactory.ViewHolderMatcher<RecyclerView.ViewHolder>() { @Override public boolean matches(RecyclerView parent, View itemView, RecyclerView.ViewHolder viewHolder) { int expectedPadding = parent.getPaddingRight(); int right = layoutManager.getDecoratedRight(itemView); int parentRight = parent.getRight(); int padding = parentRight - right; assertEquals("padding of RecyclerView item doesn't equal expected padding" ,expectedPadding, padding); return true; } }; } @Test public void your_sha256_hashalsScrollingTarget() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(0)); InstrumentalUtil.waitForIdle(); //act recyclerView.perform(RecyclerViewActions.scrollToPosition(18)); InstrumentalUtil.waitForIdle(); //assert int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); assertEquals(18, actual); } @Test public synchronized void your_sha256_hashonsEqualsScrollingTarget() throws Exception { //arrange InstrumentalUtil.waitForIdle(); //act ViewAction scrollAction = smoothScrollToPosition(18); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (scrollAction) { recyclerView.perform(scrollAction); //wait for completion of SmoothScrollAction scrollAction.wait(); } //assert int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); assertEquals(18, actual); } @Test public synchronized void your_sha256_hashrtBorder() throws Exception { //arrange InstrumentalUtil.waitForIdle(); //act ViewAction scrollAction = smoothScrollToPosition(3); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (scrollAction) { recyclerView.perform(scrollAction); //wait for completion of SmoothScrollAction scrollAction.wait(); } //assert int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); assertEquals(3, actual); } /////////////////////////////////////////////////////////////////////////// // find visible item /////////////////////////////////////////////////////////////////////////// @Test public void your_sha256_hashorrect() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(19)); InstrumentalUtil.waitForIdle(); //act int actual = layoutManager.findFirstVisibleItemPosition(); //assert assertEquals(18, actual); } @Test public void your_sha256_hashrrect() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(18)); InstrumentalUtil.waitForIdle(); //act int actual = layoutManager.findLastVisibleItemPosition(); //assert assertEquals(35, actual); } @Test public void your_sha256_hashe_resultCorrect() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(18)); InstrumentalUtil.waitForIdle(); //act int actual = layoutManager.findLastCompletelyVisibleItemPosition(); //assert assertEquals(26, actual); } private void rotateAndWaitIdle() throws Exception { //arrange final int orientation = InstrumentationRegistry.getTargetContext() .getResources() .getConfiguration() .orientation; //act activityTestRule.getActivity().setRequestedOrientation( orientation == Configuration.ORIENTATION_PORTRAIT ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); InstrumentalUtil.waitForIdle(); //verify no exceptions } /** * verify that orientation change is performed successfully */ @Test public void rotate_LMBuiltFirstTime_NoExceptions() throws Exception { //arrange //act rotateAndWaitIdle(); //assert } @Test public void rotate_LMHasItems_firstItemNotChanged() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(18)); InstrumentalUtil.waitForIdle(); int expected = layoutManager.findFirstVisibleItemPosition(); //act rotateAndWaitIdle(); int actual = layoutManager.findFirstVisibleItemPosition(); //assert assertNotEquals(-1, expected); assertNotEquals(-1, actual); assertEquals("first visible positions before and after rotation doesn't match", expected, actual); System.out.println("first visible position = " + actual); resetToInitialAfterRotate(); } void resetToInitialAfterRotate() throws Exception { activityTestRule.launchActivity(new Intent(activity, TestActivity.class)); InstrumentalUtil.waitForIdle(); } @Test public void your_sha256_hashion() throws Exception { //arrange ChipsFacade chipsFacade = spy(new ChipsFacade()); ChipsAdapter chipsAdapter = new ChipsAdapter(chipsFacade.getItems(), null); //act recyclerView.perform(setAdapter(chipsAdapter)); recyclerView.perform(setAdapter(chipsAdapter)); InstrumentalUtil.waitForIdle(); //assert int pos = layoutManager.findFirstVisibleItemPosition(); assertNotEquals(RecyclerView.NO_POSITION, pos); } @Test public void clipToPadding_IsTrue_paddingStaySame() throws Exception { //arrange RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); ViewAction viewAction = actionDelegate((uiController, view) -> { view.setClipToPadding(true); view.setPadding(150, 150, 150, 150); view.requestLayout(); }); //act recyclerView.perform(viewAction); recyclerView.perform(RecyclerViewActions.scrollToPosition(18)); //assert View view = layoutManager.getChildAt(0); double padding = view.getX() - rvTest.getX(); assertTrue(padding >= 150); } @Test public void clipToPadding_IsFalse_paddingOfScrolledViewIsLowerThanInitial() throws Exception { //arrange ViewAction viewAction = actionDelegate((uiController, view) -> { view.setClipToPadding(false); view.setPadding(150, 150, 150, 150); view.requestLayout(); }); //act recyclerView.perform(viewAction, RecyclerViewActions.scrollToPosition(18), scrollBy(200, 0)); //assert View view = layoutManager.getChildAt(0); int padding = layoutManager.getDecoratedLeft(view); assertTrue(padding < 0); } private View getViewForPosition(RecyclerView recyclerView, int position) { return recyclerView.findViewHolderForAdapterPosition(position).itemView; } @Test public void your_sha256_hashe() throws Exception { InstrumentalUtil.waitForIdle(); //arrange RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); View child = getViewForPosition(rvTest, 7); Rect expectedViewRect = layoutManager.getCanvas().getViewRect(child); //act recyclerView.perform(scrollBy(2000, 0), scrollBy(-2000, 0)); Rect resultViewRect = layoutManager.getCanvas().getViewRect(child); //assert assertEquals(expectedViewRect, resultViewRect); } @Test public void your_sha256_hash() throws Exception { InstrumentalUtil.waitForIdle(); //arrange RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); View child = getViewForPosition(rvTest, 6); Rect expectedViewRect = layoutManager.getCanvas().getViewRect(child); //act recyclerView.perform(scrollBy(500, 0), scrollBy(-500, 0)); Rect resultViewRect = layoutManager.getCanvas().getViewRect(child); //assert assertEquals(expectedViewRect, resultViewRect); } @Test public void gapsNormalization_OnLastRowDeleted_PaddingStaySame() throws Exception { //arrange { items.remove(39); items.remove(38); items.remove(37); activity.runOnUiThread(() -> activity.initialize()); InstrumentalUtil.waitForIdle(); } recyclerView.perform(RecyclerViewActions.scrollToPosition(36)); //act recyclerView.perform(actionDelegate((uiController, recyclerView) -> items.remove(36)), notifyItemRemovedAction(36)); //assert recyclerView.check(matches(atPosition(29, rvPaddingMatcher()))); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/ColumnTest.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
2,743
```java package com.beloo.widget.chipslayoutmanager; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Rect; import android.support.annotation.UiThread; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.ViewAction; import android.support.test.espresso.ViewInteraction; import android.support.test.espresso.contrib.RecyclerViewActions; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; import com.beloo.chipslayoutmanager.sample.ui.LayoutManagerFactory; import com.beloo.chipslayoutmanager.sample.ui.ChipsFacade; import com.beloo.chipslayoutmanager.sample.ui.TestActivity; import com.beloo.chipslayoutmanager.sample.ui.adapter.ChipsAdapter; import com.beloo.widget.chipslayoutmanager.util.InstrumentalUtil; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import com.beloo.chipslayoutmanager.sample.R; import java.util.List; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static com.beloo.test.util.RecyclerViewEspressoFactory.*; /** */ @RunWith(AndroidJUnit4.class) public class RowTest { static { TestActivity.isInitializeOutside = true; } @Rule public ActivityTestRule<TestActivity> activityTestRule = new ActivityTestRule<TestActivity>(TestActivity.class) { @Override protected void afterActivityLaunched() { super.afterActivityLaunched(); } }; private ChipsLayoutManager layoutManager; private TestActivity activity; private List<ChipsEntity> items; private ViewInteraction recyclerView; @Before public final void setUp() throws Throwable { MockitoAnnotations.initMocks(this); activity = activityTestRule.getActivity(); LayoutManagerFactory layoutManagerFactory = new LayoutManagerFactory() { @Override public RecyclerView.LayoutManager layoutManager(Context context) { return retrieveLayoutManager(); } }; RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); //disable all animations rvTest.setItemAnimator(null); //set items ChipsFacade chipsFacade = spy(new ChipsFacade()); items = chipsFacade.getItems(); when(chipsFacade.getItems()).thenReturn(items); TestActivity.setItemsFactory(chipsFacade); TestActivity.setLmFactory(layoutManagerFactory); recyclerView = onView(withId(R.id.rvTest)).check(matches(isDisplayed())); onSetUp(); activity.runOnUiThread(() -> activity.initialize()); } public void onSetUp() throws Exception {} private RecyclerView.LayoutManager retrieveLayoutManager() { layoutManager = getLayoutManager(); return layoutManager; } @UiThread protected ChipsLayoutManager getLayoutManager() { if (activityTestRule.getActivity() == null) return null; return ChipsLayoutManager.newBuilder(activityTestRule.getActivity()) .setOrientation(ChipsLayoutManager.HORIZONTAL) .build(); } /////////////////////////////////////////////////////////////////////////// // layouting, main feature /////////////////////////////////////////////////////////////////////////// @Test public void your_sha256_hashe() throws Exception { InstrumentalUtil.waitForIdle(); //arrange RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); View child = getViewForPosition(rvTest, 7); Rect expectedViewRect = layoutManager.getCanvas().getViewRect(child); //act recyclerView.perform(scrollBy(0, 1000), scrollBy(0, -1000)); Rect resultViewRect = layoutManager.getCanvas().getViewRect(child); //assert assertEquals(expectedViewRect, resultViewRect); } @Test public void your_sha256_hash() throws Exception { InstrumentalUtil.waitForIdle(); //arrange RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); View child = getViewForPosition(rvTest, 6); Rect expectedViewRect = layoutManager.getCanvas().getViewRect(child); //act recyclerView.perform(scrollBy(0, 250), scrollBy(0, -250)); Rect resultViewRect = layoutManager.getCanvas().getViewRect(child); //assert assertEquals(expectedViewRect, resultViewRect); } @Test public void layouting_ScrollForwardAndBackward_VerifyCorrectOrder () throws Exception { //arrange //act recyclerView.perform(scrollBy(0, 300)); recyclerView.perform(scrollBy(0, -300)); InstrumentalUtil.waitForIdle(); //assert recyclerView.check(matches(incrementOrder())); } /////////////////////////////////////////////////////////////////////////// // scroll /////////////////////////////////////////////////////////////////////////// @Test public void your_sha256_hashVisibleItem() throws Exception { //arrange InstrumentalUtil.waitForIdle(); //act recyclerView.perform(scrollBy(0, 300)); int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); //assert assertEquals(4, actual); } @Test public void your_sha256_hashibleItem() throws Exception { //arrange InstrumentalUtil.waitForIdle(); recyclerView.perform(scrollBy(0, 300)); //act recyclerView.perform(scrollBy(0, -300)); int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); //assert assertEquals(0, actual); } @Test public void your_sha256_hashstItemSize() throws Exception { //arrange { items.remove(39); items.remove(37); } activity.runOnUiThread(() -> activity.initialize()); InstrumentalUtil.waitForIdle(); //act recyclerView.perform(RecyclerViewActions.scrollToPosition(37), scrollBy(0, -200), scrollBy(0, 200)); //assert recyclerView.check(matches(atPosition(36, rvPaddingMatcher()))); } @Test public void your_sha256_hashollingTarget() throws Exception { //arrange //act recyclerView.perform(RecyclerViewActions.scrollToPosition(8)); InstrumentalUtil.waitForIdle(); //assert int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); assertEquals(8, actual); } @Test public synchronized void your_sha256_hashalsScrollingTarget() throws Exception { //arrange InstrumentalUtil.waitForIdle(); //act ViewAction scrollAction = smoothScrollToPosition(8); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (scrollAction) { recyclerView.perform(scrollAction); //wait for completion of SmoothScrollAction scrollAction.wait(); } //assert int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); assertEquals(8, actual); } /////////////////////////////////////////////////////////////////////////// // find visible item /////////////////////////////////////////////////////////////////////////// @Test public void your_sha256_hashorrect() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(7), scrollBy(0, 50)); //act int actual = layoutManager.findFirstVisibleItemPosition(); //assert assertEquals(6, actual); } @Test public void your_sha256_hashle_resultCorrect() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(7), scrollBy(0, 50)); //act int actual = layoutManager.findFirstCompletelyVisibleItemPosition(); //assert assertEquals(7, actual); } @Test public void your_sha256_hashrrect() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(7)); InstrumentalUtil.waitForIdle(); //act int actual = layoutManager.findLastVisibleItemPosition(); //assert assertEquals(19, actual); } @Test public void your_sha256_hashe_resultCorrect() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(7)); InstrumentalUtil.waitForIdle(); //act int actual = layoutManager.findLastCompletelyVisibleItemPosition(); //assert assertEquals(17, actual); } /////////////////////////////////////////////////////////////////////////// // rotate /////////////////////////////////////////////////////////////////////////// void rotateAndWaitIdle() throws Exception { //arrange final int orientation = InstrumentationRegistry.getTargetContext() .getResources() .getConfiguration() .orientation; //act activityTestRule.getActivity().setRequestedOrientation( orientation == Configuration.ORIENTATION_PORTRAIT ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); InstrumentalUtil.waitForIdle(); //verify no exceptions } void resetToInitialAfterRotate() throws Exception { activityTestRule.launchActivity(new Intent(activity, TestActivity.class)); InstrumentalUtil.waitForIdle(); } @Test public void rotate_LMHasItems_firstItemNotChanged() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(7)); InstrumentalUtil.waitForIdle(); int expected = layoutManager.findFirstVisibleItemPosition(); //act rotateAndWaitIdle(); int actual = layoutManager.findFirstVisibleItemPosition(); resetToInitialAfterRotate(); //assert assertNotEquals(-1, expected); assertNotEquals(-1, actual); assertEquals("first visible positions before and after rotation doesn't match", expected, actual); System.out.println("first visible position = " + actual); } @Test public void rotate_ScrolledToEndOfItems_BottomPaddingStaySame() throws Exception { InstrumentalUtil.waitForIdle(); //arrange RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); recyclerView.perform(RecyclerViewActions.scrollToPosition(layoutManager.getItemCount() - 1)); InstrumentalUtil.waitForIdle(); Thread.sleep(200); View child = getViewForPosition(rvTest, layoutManager.findLastVisibleItemPosition()); double bottom = (rvTest.getY() + rvTest.getHeight()) - (child.getY() + child.getHeight()); Log.println(Log.ASSERT, "rotateTest", "expected child padding = " + bottom); //act rotateAndWaitIdle(); recyclerView.perform(RecyclerViewActions.scrollToPosition(layoutManager.getItemCount() - 1)); rotateAndWaitIdle(); rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); child = getViewForPosition(rvTest, layoutManager.findLastVisibleItemPosition()); double result = (rvTest.getY() + rvTest.getHeight()) - (child.getY() + child.getHeight()); Log.println(Log.ASSERT, "rotateTest", "result child padding = " + result); //reset resetToInitialAfterRotate(); //assert assertNotEquals(0.0d, bottom, 0.01); assertNotEquals(0.0d, result, 0.01); assertEquals(bottom, result, 0.01); } @Test public void your_sha256_hashion() throws Exception { //arrange ChipsFacade chipsFacade = spy(new ChipsFacade()); ChipsAdapter chipsAdapter = new ChipsAdapter(chipsFacade.getItems(), null); //act recyclerView.perform(setAdapter(chipsAdapter)); recyclerView.perform(setAdapter(chipsAdapter)); InstrumentalUtil.waitForIdle(); //assert int pos = layoutManager.findFirstVisibleItemPosition(); assertNotEquals(RecyclerView.NO_POSITION, pos); } /////////////////////////////////////////////////////////////////////////// // padding /////////////////////////////////////////////////////////////////////////// @Test public void clipToPadding_IsTrue_paddingStaySame() throws Exception { //arrange RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); ViewAction initAction = actionDelegate((uiController, view) -> { view.setClipToPadding(true); view.setPadding(150, 150, 150, 150); view.requestLayout(); }); recyclerView.perform(initAction); //act recyclerView.perform(RecyclerViewActions.scrollToPosition(8)); //assert View view = layoutManager.getChildAt(0); double padding = view.getY() - rvTest.getY(); assertTrue(padding >= 150); } @Test public void clipToPadding_IsFalse_paddingOfScrolledViewIsLowerThanInitial() throws Exception { //arrange ViewAction arrangeAction = actionDelegate((uiController, view) -> { view.setClipToPadding(false); view.setPadding(150, 150, 150, 150); view.requestLayout(); }); recyclerView.perform(arrangeAction); //act recyclerView.perform(RecyclerViewActions.scrollToPosition(8), scrollBy(0, 200)); //assert View view = layoutManager.getChildAt(0); int padding = layoutManager.getDecoratedTop(view); assertTrue(padding < 0); } private ViewHolderMatcher<RecyclerView.ViewHolder> rvPaddingMatcher() { return new ViewHolderMatcher<RecyclerView.ViewHolder>() { @Override public boolean matches(RecyclerView parent, View itemView, RecyclerView.ViewHolder viewHolder) { int expectedPadding = parent.getPaddingBottom(); int bottom = layoutManager.getDecoratedBottom(itemView); int parentBottom = parent.getBottom(); int padding = parentBottom - bottom; assertEquals("padding of RecyclerView item doesn't equal expected padding" ,expectedPadding, padding); return true; } }; } @Test public void gapsNormalization_OnLastRowDeleted_PaddingStaySame() throws Exception { //arrange recyclerView.perform(RecyclerViewActions.scrollToPosition(39)); //act recyclerView.perform(actionDelegate((uiController, recyclerView) -> items.remove(39)), notifyItemRemovedAction(39)); //assert recyclerView.check(matches(atPosition(38, rvPaddingMatcher()))); } private View getViewForPosition(RecyclerView recyclerView, int position) { return recyclerView.findViewHolderForAdapterPosition(position).itemView; } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/RowTest.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
3,031
```java package com.beloo.widget.chipslayoutmanager; import android.support.annotation.UiThread; import android.support.v4.view.ViewCompat; import android.view.View; import com.beloo.chipslayoutmanager.sample.R; public class RTLRowTest extends RowTest { @UiThread @Override protected ChipsLayoutManager getLayoutManager() { ChipsLayoutManager layoutManager = super.getLayoutManager(); if (activityTestRule.getActivity() != null) { View recyclerView = activityTestRule.getActivity().findViewById(R.id.rvTest); ViewCompat.setLayoutDirection(recyclerView, ViewCompat.LAYOUT_DIRECTION_RTL); } return layoutManager; } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/RTLRowTest.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
130
```java package com.beloo.widget.chipslayoutmanager; import android.support.test.espresso.ViewAction; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import com.beloo.chipslayoutmanager.sample.R; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; import com.beloo.chipslayoutmanager.sample.ui.ChipsFacade; import com.beloo.chipslayoutmanager.sample.ui.LayoutManagerFactory; import com.beloo.chipslayoutmanager.sample.ui.TestActivity; import com.beloo.widget.chipslayoutmanager.util.InstrumentalUtil; import com.beloo.widget.chipslayoutmanager.util.testing.ISpy; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.List; import java.util.Locale; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static com.beloo.test.util.RecyclerViewEspressoFactory.actionDelegate; import static com.beloo.test.util.RecyclerViewEspressoFactory.notifyItemRemovedAction; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertNotEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * test for {@link TestActivity} */ @RunWith(AndroidJUnit4.class) public class FewChipsColumnTest { static { TestActivity.isInitializeOutside = true; } @Rule public ActivityTestRule<TestActivity> activityTestRule = new ActivityTestRule<>(TestActivity.class); @Mock ISpy spy; @Mock LayoutManagerFactory layoutManagerFactory; private ChipsLayoutManager layoutManager; private List<ChipsEntity> items; private TestActivity activity; @Before public void setUp() throws Throwable { MockitoAnnotations.initMocks(this); activity = activityTestRule.getActivity(); layoutManager = getLayoutManager(); doReturn(layoutManager).when(layoutManagerFactory).layoutManager(any()); RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); //disable all animations rvTest.setItemAnimator(null); //set items ChipsFacade chipsFacade = spy(new ChipsFacade()); items = chipsFacade.getItems(); when(chipsFacade.getItems()).thenReturn(items); TestActivity.setItemsFactory(chipsFacade); TestActivity.setLmFactory(layoutManagerFactory); } protected ChipsLayoutManager getLayoutManager() { return ChipsLayoutManager.newBuilder(activityTestRule.getActivity()) .setOrientation(ChipsLayoutManager.VERTICAL) .build(); } /** * test, that {@link android.support.v7.widget.LinearLayoutManager#onLayoutChildren} isn't called infinitely */ @Test public void onLayoutChildren_afterActivityStarted_onLayoutCallLimited() throws Exception { //arrange activity.runOnUiThread(() -> activity.initialize()); //act //we can't wait for idle, coz in case of error it won't be achieved. So just approximate time here. Thread.sleep(700); //assert verify(spy, atMost(6)).onLayoutChildren(any(RecyclerView.Recycler.class), any(RecyclerView.State.class)); } @Test public void your_sha256_hashghtToDecrease() throws Exception { //arrange activity.runOnUiThread(() -> activity.initialize()); final RecyclerView[] rvTest = new RecyclerView[1]; ViewInteraction recyclerView = onView(withId(R.id.rvTest)).check(matches(isDisplayed())); ViewAction viewAction = actionDelegate(((uiController, view) -> { rvTest[0] = view; view.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT; view.requestLayout(); })); recyclerView.perform(viewAction); int startWidth = rvTest[0].getHeight(); //act recyclerView.perform( actionDelegate(((uiController, view) -> items.remove(9))), notifyItemRemovedAction(9)); InstrumentalUtil.waitForIdle(); //assert int endWidth = rvTest[0].getWidth(); System.out.println(String.format(Locale.getDefault(), "start height = %d, end height = %d", startWidth, endWidth)); assertTrue(endWidth < startWidth); } @Test public void deleteItemInTheFirstLine_ItemHasMaximumWidth_SameStartPadding() throws Exception { //arrange { //just adapt input items list to required start values items.remove(1); items.remove(9); ChipsEntity longItem = items.remove(8); items.add(1, longItem); } activity.runOnUiThread(() -> activity.initialize()); ViewInteraction recyclerView = onView(withId(R.id.rvTest)).check(matches(isDisplayed())); //just adapt input items list to required start values InstrumentalUtil.waitForIdle(); View second = layoutManager.getChildAt(1); double expectedX = second.getX(); //act recyclerView.perform( actionDelegate(((uiController, view) -> items.remove(1))), notifyItemRemovedAction(1)); InstrumentalUtil.waitForIdle(); second = layoutManager.getChildAt(5); double resultX = second.getX(); //assert assertNotEquals(0, expectedX, 0.01); assertNotEquals(0, resultX, 0.01); assertEquals(resultX, expectedX, 0.01); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/FewChipsColumnTest.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
1,209
```java package com.beloo.widget.chipslayoutmanager; import android.support.test.espresso.ViewAction; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.beloo.chipslayoutmanager.sample.R; import com.beloo.chipslayoutmanager.sample.entity.ChipsEntity; import com.beloo.chipslayoutmanager.sample.ui.FewChipsFacade; import com.beloo.chipslayoutmanager.sample.ui.IItemsFacade; import com.beloo.chipslayoutmanager.sample.ui.LayoutManagerFactory; import com.beloo.chipslayoutmanager.sample.ui.TestActivity; import com.beloo.widget.chipslayoutmanager.util.InstrumentalUtil; import com.beloo.widget.chipslayoutmanager.util.testing.ISpy; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.List; import java.util.Locale; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static com.beloo.test.util.RecyclerViewEspressoFactory.actionDelegate; import static com.beloo.test.util.RecyclerViewEspressoFactory.notifyItemRemovedAction; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertNotEquals; import static org.junit.Assume.assumeTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * test for {@link TestActivity} */ @RunWith(AndroidJUnit4.class) public class FewChipsRowTest { static { TestActivity.isInitializeOutside = true; } @Rule public ActivityTestRule<TestActivity> activityTestRule = new ActivityTestRule<>(TestActivity.class); @Mock ISpy spy; @Mock LayoutManagerFactory layoutManagerFactory; private ChipsLayoutManager layoutManager; private List<ChipsEntity> items; private TestActivity activity; @Before public void setUp() throws Throwable { MockitoAnnotations.initMocks(this); activity = activityTestRule.getActivity(); RecyclerView rvTest = (RecyclerView) activityTestRule.getActivity().findViewById(R.id.rvTest); //disable all animations rvTest.setItemAnimator(null); layoutManager = getLayoutManager(); doReturn(layoutManager).when(layoutManagerFactory).layoutManager(any()); IItemsFacade<ChipsEntity> chipsFacade = spy(new FewChipsFacade()); items = chipsFacade.getItems(); when(chipsFacade.getItems()).thenReturn(items); TestActivity.setItemsFactory(chipsFacade); TestActivity.setLmFactory(layoutManagerFactory); } protected ChipsLayoutManager getLayoutManager() { return ChipsLayoutManager.newBuilder(activityTestRule.getActivity()) .setOrientation(ChipsLayoutManager.HORIZONTAL) .build(); } /** * test, that {@link android.support.v7.widget.LinearLayoutManager#onLayoutChildren} isn't called infinitely */ @Test public void onLayoutChildren_afterActivityStarted_onLayoutCallLimited() throws Exception { //arrange activity.runOnUiThread(() -> activity.initialize()); layoutManager.setSpy(spy); //act //we can't wait for idle, coz in case of error it won't be achieved. So just approximate time here. Thread.sleep(700); //assert verify(spy, atMost(6)).onLayoutChildren(any(RecyclerView.Recycler.class), any(RecyclerView.State.class)); } @Test public void your_sha256_hashghtToDecrease() throws Exception { //arrange activity.runOnUiThread(() -> activity.initialize()); final RecyclerView[] rvTest = new RecyclerView[1]; ViewInteraction recyclerView = onView(withId(R.id.rvTest)).check(matches(isDisplayed())); ViewAction viewAction = actionDelegate((uiController, view) -> { rvTest[0] = view; view.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); view.requestLayout(); }); recyclerView.perform(viewAction); int startHeight = rvTest[0].getHeight(); //act recyclerView.perform( actionDelegate(((uiController, view) -> items.remove(9))), notifyItemRemovedAction(9)); //assert int endHeight = rvTest[0].getHeight(); System.out.println(String.format(Locale.getDefault(), "start height = %d, end height = %d", startHeight, endHeight)); assertTrue(endHeight < startHeight); } @Test public void deleteItemInTheFirstLine_ItemHasMaximumHeight_SameStartPadding() throws Exception { //arrange //just adapt input items list to required start values items.remove(1); activity.runOnUiThread(() -> activity.initialize()); ViewInteraction recyclerView = onView(withId(R.id.rvTest)).check(matches(isDisplayed())); InstrumentalUtil.waitForIdle(); View second = layoutManager.getChildAt(1); int startHeight = second.getHeight(); double expectedY = second.getY(); //act recyclerView.perform( actionDelegate(((uiController, view) -> items.remove(1))), notifyItemRemovedAction(1)); InstrumentalUtil.waitForIdle(); second = layoutManager.getChildAt(1); int endHeight = second.getHeight(); double resultY = second.getY(); //assert //check test behaviour assumeTrue(startHeight > endHeight); assertNotEquals(0, expectedY, 0.01); assertNotEquals(0, resultY, 0.01); assertEquals(resultY, expectedY, 0.01); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/FewChipsRowTest.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
1,236
```java package com.beloo.widget.chipslayoutmanager.support; /** * A class that can supply objects of a single type. Semantically, this could * be a factory, generator, builder, closure, or something else entirely. No * guarantees are implied by this interface. * * @author Harry Heymann * @since 2.0 (imported from Google Collections Library) */ public interface Supplier<T> { /** * Retrieves an instance of the appropriate type. The returned object may or * may not be a new instance, depending on the implementation. * * @return an instance of the appropriate type */ T get(); } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/support/Supplier.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
140
```java /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.beloo.widget.chipslayoutmanager.support; /** * Represents an operation that accepts a single input argument and returns no * result. Unlike most other functional interfaces, {@code Consumer} is expected * to operate via side-effects. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #accept(Object)}. * * @param <T> the type of the input to the operation * * @since 1.8 */ @FunctionalInterface public interface Consumer<T> { /** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t); } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/support/Consumer.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
359
```java package com.beloo.widget.chipslayoutmanager.util; import static android.support.test.InstrumentationRegistry.getInstrumentation; public class InstrumentalUtil { public static void waitForIdle() throws Exception { getInstrumentation().waitForIdleSync(); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/util/InstrumentalUtil.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
53
```java /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.beloo.widget.chipslayoutmanager.support; /** * Represents an operation that accepts two input arguments and returns no * result. This is the two-arity specialization of {@link Consumer}. * Unlike most other functional interfaces, {@code BiConsumer} is expected * to operate via side-effects. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #accept(Object, Object)}. * * @param <T> the type of the first argument to the operation * @param <U> the type of the second argument to the operation * * @see Consumer * @since 1.8 */ @FunctionalInterface public interface BiConsumer<T, U> { /** * Performs this operation on the given arguments. * * @param t the first input argument * @param u the second input argument */ void accept(T t, U u); } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/support/BiConsumer.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
414
```java package com.beloo.widget.chipslayoutmanager.util; import android.support.test.espresso.UiController; import android.support.test.espresso.ViewAction; import android.view.View; import org.hamcrest.Matcher; import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static org.hamcrest.Matchers.allOf; public abstract class Action<T extends View> implements ViewAction { @Override public Matcher<View> getConstraints() { return allOf(isAssignableFrom(View.class), isDisplayed()); } @Override public String getDescription() { return "action " + this.getClass().getSimpleName(); } @Override public final void perform(UiController uiController, View view) { performAction(uiController, (T) view); } public abstract void performAction(UiController uiController, T view); } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/util/Action.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
180
```java package com.beloo.widget.chipslayoutmanager.util; import android.support.test.espresso.UiController; import android.view.View; import com.beloo.widget.chipslayoutmanager.support.BiConsumer; public class ActionDelegate<T extends View> extends Action<T> { private BiConsumer<UiController, T> viewConsumer; public ActionDelegate(BiConsumer<UiController, T> viewConsumer) { this.viewConsumer = viewConsumer; } @Override public final void performAction(UiController uiController, T view) { viewConsumer.accept(uiController, view); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/widget/chipslayoutmanager/util/ActionDelegate.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
124
```qmake # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in C:\Users\Beloo\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # path_to_url # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ## ## Disable logging ## # Disable Android logging for release builds -assumenosideeffects class android.util.Log { public static boolean isLoggable(java.lang.String, int); public static int v(...); public static int i(...); public static int w(...); public static int d(...); public static int e(...); } ```
/content/code_sandbox/ChipsLayoutManager/proguard-rules.pro
qmake
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
218
```java package com.beloo.widget.chipslayoutmanager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.Iterator; public class ChildViewsIterable implements Iterable<View> { private RecyclerView.LayoutManager layoutManager; public ChildViewsIterable(RecyclerView.LayoutManager layoutManager) { this.layoutManager = layoutManager; } @Override public Iterator<View> iterator() { return new Iterator<View>() { int i = 0; @Override public boolean hasNext() { return i < layoutManager.getChildCount(); } @Override public View next() { return layoutManager.getChildAt(i++); } }; } public int size() { return layoutManager.getChildCount(); } } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/ChildViewsIterable.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
150
```java package com.beloo.widget.chipslayoutmanager; import android.support.annotation.IntDef; @IntDef({ChipsLayoutManager.HORIZONTAL, ChipsLayoutManager.VERTICAL}) @interface Orientation { } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/Orientation.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
35
```java package com.beloo.widget.chipslayoutmanager; import android.content.Context; import android.graphics.PointF; import android.support.annotation.NonNull; import android.support.v7.widget.LinearSmoothScroller; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.animation.LinearInterpolator; import com.beloo.widget.chipslayoutmanager.anchor.AnchorViewState; import com.beloo.widget.chipslayoutmanager.layouter.IStateFactory; class HorizontalScrollingController extends ScrollingController implements IScrollingController { private ChipsLayoutManager layoutManager; HorizontalScrollingController(ChipsLayoutManager layoutManager, IStateFactory stateFactory, IScrollerListener scrollerListener) { super(layoutManager, stateFactory, scrollerListener); this.layoutManager = layoutManager; } @Override public RecyclerView.SmoothScroller createSmoothScroller(@NonNull Context context, final int position, final int timeMs, final AnchorViewState anchor) { return new LinearSmoothScroller(context) { /* * LinearSmoothScroller, at a minimum, just need to know the vector * (x/y distance) to travel in order to get from the current positioning * to the target. */ @Override public PointF computeScrollVectorForPosition(int targetPosition) { int visiblePosition = anchor.getPosition(); //determine scroll up or scroll down needed return new PointF(position > visiblePosition ? 1 : -1, 0); } @Override protected void onTargetFound(View targetView, RecyclerView.State state, Action action) { super.onTargetFound(targetView, state, action); int currentLeft = layoutManager.getPaddingLeft(); int desiredLeft = layoutManager.getDecoratedLeft(targetView); int dx = desiredLeft - currentLeft; //perform fit animation to move target view at top of layoutX action.update(dx, 0, timeMs, new LinearInterpolator()); } }; } @Override public boolean canScrollVertically() { return false; } @Override public boolean canScrollHorizontally() { canvas.findBorderViews(); if (layoutManager.getChildCount() > 0) { int left = layoutManager.getDecoratedLeft(canvas.getLeftView()); int right = layoutManager.getDecoratedRight(canvas.getRightView()); if (canvas.getMinPositionOnScreen() == 0 && canvas.getMaxPositionOnScreen() == layoutManager.getItemCount() - 1 && left >= layoutManager.getPaddingLeft() && right <= layoutManager.getWidth() - layoutManager.getPaddingRight()) { return false; } } else { return false; } return layoutManager.isScrollingEnabledContract(); } @Override void offsetChildren(int d) { layoutManager.offsetChildrenHorizontal(d); } } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/HorizontalScrollingController.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
584
```java package com.beloo.widget.chipslayoutmanager; import android.content.res.Configuration; import android.support.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @IntDef({Configuration.ORIENTATION_LANDSCAPE, Configuration.ORIENTATION_PORTRAIT, Configuration.ORIENTATION_UNDEFINED}) @Retention(RetentionPolicy.SOURCE) @interface DeviceOrientation {} ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/DeviceOrientation.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
75
```java package com.beloo.test.util; import android.support.annotation.NonNull; import android.support.test.espresso.UiController; import android.support.test.espresso.ViewAction; import android.support.test.espresso.matcher.BoundedMatcher; import android.support.v7.widget.RecyclerView; import android.view.View; import com.beloo.widget.chipslayoutmanager.ChildViewsIterable; import com.beloo.widget.chipslayoutmanager.support.BiConsumer; import com.beloo.widget.chipslayoutmanager.util.ActionDelegate; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.Locale; import static android.support.test.espresso.core.deps.guava.base.Preconditions.checkNotNull; import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static org.hamcrest.Matchers.allOf; public abstract class RecyclerViewEspressoFactory { /////////////////////////////////////////////////////////////////////////// // Actions factory /////////////////////////////////////////////////////////////////////////// public static ViewAction scrollBy(int x, int y) { return new ScrollByRecyclerViewAction(x, y); } public static ViewAction smoothScrollToPosition(int position) { return new SmoothScrollToPositionRecyclerViewAction(position); } public static ViewAction setAdapter(RecyclerView.Adapter<? extends RecyclerView.ViewHolder> adapter) { return new SetAdapterAction(adapter); } public static ViewAction notifyItemRemovedAction(int removePosition) { return new NotifyItemRemovedAction(removePosition); } public static ViewAction notifyItemRangeRemovedAction(int removePosition, int itemCount) { return new NotifyItemRemovedAction(removePosition, itemCount); } public static ViewAction actionDelegate(BiConsumer<UiController, RecyclerView> performAction) { return new ActionDelegate<>(performAction); } /////////////////////////////////////////////////////////////////////////// // Matcher factory /////////////////////////////////////////////////////////////////////////// public static Matcher<View> incrementOrder() { return orderMatcher(); } public static Matcher<View> atPosition(final int position, @NonNull final Matcher<View> itemMatcher) { checkNotNull(itemMatcher); return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) { @Override public void describeTo(Description description) { description.appendText("has item at position " + position + ":\n"); itemMatcher.describeTo(description); } @Override protected boolean matchesSafely(final RecyclerView view) { RecyclerView.ViewHolder viewHolder = view.findViewHolderForAdapterPosition(position); return viewHolder != null && itemMatcher.matches(viewHolder.itemView); } }; } public static <T extends RecyclerView.ViewHolder> Matcher<View> atPosition(final int position, @NonNull final ViewHolderMatcher<T> itemMatcher) { checkNotNull(itemMatcher); return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) { @Override public void describeTo(Description description) { description.appendText("has item at position " + position + ":\n"); itemMatcher.describeTo(description); } @Override protected boolean matchesSafely(final RecyclerView view) { RecyclerView.ViewHolder viewHolder = view.findViewHolderForAdapterPosition(position); return viewHolder != null && itemMatcher.matches(viewHolder); } }; } /////////////////////////////////////////////////////////////////////////// // Actions /////////////////////////////////////////////////////////////////////////// private static final class NotifyItemRemovedAction extends RecyclerViewAction { private final int removePosition; private final int itemCount; private NotifyItemRemovedAction(int removePosition, int itemCount) { this.removePosition = removePosition; this.itemCount = itemCount; } private NotifyItemRemovedAction(int removePosition) { this.removePosition = removePosition; this.itemCount = 1; } @Override public void performAction(UiController uiController, RecyclerView recyclerView) { recyclerView.getAdapter().notifyItemRangeRemoved(removePosition, itemCount); } } private static final class SetAdapterAction extends RecyclerViewAction { private final RecyclerView.Adapter<? extends RecyclerView.ViewHolder> adapter; private SetAdapterAction(RecyclerView.Adapter<? extends RecyclerView.ViewHolder> adapter) { this.adapter = adapter; } @Override public String getDescription() { return"set adapter to recycler view"; } @Override public void performAction(UiController uiController, RecyclerView recyclerView) { recyclerView.setAdapter(adapter); } } private static final class SmoothScrollToPositionRecyclerViewAction extends RecyclerViewAction { private final int position; private SmoothScrollToPositionRecyclerViewAction(int position) { this.position = position; } @Override public String getDescription() { return String.format(Locale.getDefault(), "smooth scroll RecyclerView to position %d", position); } @Override public void performAction(UiController uiController, RecyclerView recyclerView) { recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); SmoothScrollToPositionRecyclerViewAction.this.onScrollStateChanged(recyclerView, newState); } }); recyclerView.smoothScrollToPosition(position); } private synchronized void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { notify(); } } } private static final class ScrollByRecyclerViewAction extends RecyclerViewAction { private final int x; private final int y; private ScrollByRecyclerViewAction(int x, int y) { this.x = x; this.y = y; } @Override public String getDescription() { return String.format(Locale.getDefault(), "scroll RecyclerView with offsets: x = %d, y = %d ", x, y); } @Override public void performAction(UiController uiController, RecyclerView recyclerView) { recyclerView.scrollBy(x, y); } } private abstract static class RecyclerViewAction implements ViewAction { @Override public Matcher<View> getConstraints() { return allOf(isAssignableFrom(RecyclerView.class), isDisplayed()); } @Override public String getDescription() { return "RecyclerView action " + this.getClass().getSimpleName(); } @Override public final void perform(UiController uiController, View view) { performAction(uiController, (RecyclerView) view); } public void performAction(UiController uiController, RecyclerView recyclerView) { } } /////////////////////////////////////////////////////////////////////////// // Matcher /////////////////////////////////////////////////////////////////////////// private static Matcher<View> orderMatcher() { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("with correct position order"); } @Override public boolean matchesSafely(View v) { RecyclerView view = (RecyclerView) v; if (view.getLayoutManager() == null) return false; ChildViewsIterable childViews = new ChildViewsIterable(view.getLayoutManager()); int pos = view.getChildAdapterPosition(childViews.iterator().next()); for (View child : childViews) { if (pos != view.getChildAdapterPosition(child)) { return false; } pos ++; } return true; } }; } public abstract static class ViewHolderMatcher<VH extends RecyclerView.ViewHolder> extends BaseMatcher<VH> { @Override public boolean matches(Object item) { VH viewHolder = (VH) item; RecyclerView recyclerView = (RecyclerView) viewHolder.itemView.getParent(); return matches(recyclerView, viewHolder.itemView, viewHolder); } @Override public void describeTo(Description description) { } public abstract boolean matches(RecyclerView parent, View itemView, RecyclerView.ViewHolder viewHolder); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/beloo/test/util/RecyclerViewEspressoFactory.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
1,584
```java package com.beloo.widget.chipslayoutmanager; import android.support.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @IntDef({ChipsLayoutManager.STRATEGY_DEFAULT, ChipsLayoutManager.STRATEGY_FILL_SPACE, ChipsLayoutManager.STRATEGY_FILL_VIEW, ChipsLayoutManager.STRATEGY_CENTER, ChipsLayoutManager.STRATEGY_CENTER_DENSE }) @Retention(RetentionPolicy.SOURCE) public @interface RowStrategy {} ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/RowStrategy.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
95
```java package com.beloo.widget.chipslayoutmanager; import android.support.v7.widget.RecyclerView; interface IDisappearingViewsManager { DisappearingViewsManager.DisappearingViewsContainer getDisappearingViews(RecyclerView.Recycler recycler); int calcDisappearingViewsLength(RecyclerView.Recycler recycler); int getDeletingItemsOnScreenCount(); void reset(); } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/IDisappearingViewsManager.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
79
```java package com.beloo.widget.chipslayoutmanager; import android.content.res.Configuration; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.SparseArray; import com.beloo.widget.chipslayoutmanager.anchor.AnchorViewState; import com.beloo.widget.chipslayoutmanager.cache.CacheParcelableContainer; class ParcelableContainer implements Parcelable { private AnchorViewState anchorViewState; private SparseArray<Object> orientationCacheMap = new SparseArray<>(); private SparseArray<Object> cacheNormalizationPositionMap = new SparseArray<>(); //store previous orientation private int orientation; ParcelableContainer() { //initial values. We should normalize cache when scrolled to zero in case first time of changing layoutOrientation state cacheNormalizationPositionMap.put(Configuration.ORIENTATION_PORTRAIT, 0); cacheNormalizationPositionMap.put(Configuration.ORIENTATION_LANDSCAPE, 0); } void putAnchorViewState(AnchorViewState anchorViewState) { this.anchorViewState = anchorViewState; } AnchorViewState getAnchorViewState() { return anchorViewState; } @DeviceOrientation int getOrientation() { return orientation; } void putOrientation(@DeviceOrientation int orientation) { this.orientation = orientation; } @SuppressWarnings("unchecked") private ParcelableContainer(Parcel parcel) { anchorViewState = AnchorViewState.CREATOR.createFromParcel(parcel); orientationCacheMap = parcel.readSparseArray(CacheParcelableContainer.class.getClassLoader()); cacheNormalizationPositionMap = parcel.readSparseArray(Integer.class.getClassLoader()); orientation = parcel.readInt(); } @Override public void writeToParcel(Parcel parcel, int i) { anchorViewState.writeToParcel(parcel, i); parcel.writeSparseArray(orientationCacheMap); parcel.writeSparseArray(cacheNormalizationPositionMap); parcel.writeInt(orientation); } void putPositionsCache(@DeviceOrientation int orientation, Parcelable parcelable) { orientationCacheMap.put(orientation, parcelable); } void putNormalizationPosition(@DeviceOrientation int orientation, @Nullable Integer normalizationPosition) { cacheNormalizationPositionMap.put(orientation, normalizationPosition); } @Nullable Parcelable getPositionsCache(@DeviceOrientation int orientation) { return (Parcelable) orientationCacheMap.get(orientation); } @IntRange(from = 0) @Nullable Integer getNormalizationPosition(@DeviceOrientation int orientation) { return (Integer) cacheNormalizationPositionMap.get(orientation); } public static final Creator<ParcelableContainer> CREATOR = new Creator<ParcelableContainer>() { @Override public ParcelableContainer createFromParcel(Parcel parcel) { return new ParcelableContainer(parcel); } @Override public ParcelableContainer[] newArray(int i) { return new ParcelableContainer[i]; } }; @Override public int describeContents() { return 0; } } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/ParcelableContainer.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
609
```java package com.beloo.widget.chipslayoutmanager; public interface IBorder { int getCanvasRightBorder(); int getCanvasBottomBorder(); int getCanvasLeftBorder(); int getCanvasTopBorder(); } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/IBorder.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
45
```java package com.beloo.widget.chipslayoutmanager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.beloo.widget.chipslayoutmanager.anchor.AnchorViewState; import com.beloo.widget.chipslayoutmanager.layouter.ICanvas; import com.beloo.widget.chipslayoutmanager.layouter.IStateFactory; abstract class ScrollingController implements IScrollingController { private ChipsLayoutManager lm; private IScrollerListener scrollerListener; private IStateFactory stateFactory; ICanvas canvas; interface IScrollerListener { void onScrolled(IScrollingController scrollingController, RecyclerView.Recycler recycler, RecyclerView.State state); } ScrollingController(ChipsLayoutManager layoutManager, IStateFactory stateFactory, IScrollerListener scrollerListener) { this.lm = layoutManager; this.scrollerListener = scrollerListener; this.stateFactory = stateFactory; this.canvas = layoutManager.getCanvas(); } final int calculateEndGap() { if (lm.getChildCount() == 0) return 0; int visibleViewsCount = lm.getCompletelyVisibleViewsCount(); if (visibleViewsCount == lm.getItemCount()) return 0; int currentEnd = stateFactory.getEndViewBound(); int desiredEnd = stateFactory.getEndAfterPadding(); int diff = desiredEnd - currentEnd; if (diff < 0) return 0; return diff; } final int calculateStartGap() { if (lm.getChildCount() == 0) return 0; int currentStart = stateFactory.getStartViewBound(); int desiredStart = stateFactory.getStartAfterPadding(); int diff = currentStart - desiredStart; if (diff < 0) return 0; return diff; } @Override public final boolean normalizeGaps(RecyclerView.Recycler recycler, RecyclerView.State state) { int backwardGap = calculateStartGap(); if (backwardGap > 0) { offsetChildren(-backwardGap); //if we have normalized start gap, normalizing bottom have no sense return true; } int forwardGap = calculateEndGap(); if (forwardGap > 0) { scrollBy(-forwardGap, recycler, state); return true; } return false; } final int calcOffset(int d) { int childCount = lm.getChildCount(); if (childCount == 0) { return 0; } int delta = 0; if (d < 0) { //if content scrolled down delta = onContentScrolledBackward(d); } else if (d > 0) { //if content scrolled up delta = onContentScrolledForward(d); } return delta; } /** * invoked when content scrolled forward (return to older items) * * @param d not processed changing of x or y axis, depending on lm state * @return delta. Calculated changing of x or y axis, depending on lm state */ final int onContentScrolledBackward(int d) { int delta; AnchorViewState anchor = lm.getAnchor(); if (anchor.getAnchorViewRect() == null) { return 0; } if (anchor.getPosition() != 0) { //in case 0 position haven't added in layout yet delta = d; } else { //in case top view is a first view in adapter and wouldn't be any other view above int startBorder = stateFactory.getStartAfterPadding(); int viewStart = stateFactory.getStart(anchor); int distance; distance = viewStart - startBorder; if (distance >= 0) { // in case over scroll on top border delta = distance; } else { //in case first child showed partially delta = Math.max(distance, d); } } return delta; } /** * invoked when content scrolled up (to newer items) * * @param d not processed changing of x or y axis, depending on lm state * @return delta. Calculated changing of x or y axis, depending on lm state */ final int onContentScrolledForward(int d) { int childCount = lm.getChildCount(); int itemCount = lm.getItemCount(); int delta; View lastView = lm.getChildAt(childCount - 1); int lastViewAdapterPos = lm.getPosition(lastView); if (lastViewAdapterPos < itemCount - 1) { //in case lower view isn't the last view in adapter delta = d; } else { //in case lower view is the last view in adapter and wouldn't be any other view below int viewEnd = stateFactory.getEndViewBound(); int parentEnd = stateFactory.getEndAfterPadding(); delta = Math.min(viewEnd - parentEnd, d); } return delta; } abstract void offsetChildren(int d); @Override public final int scrollHorizontallyBy(int d, RecyclerView.Recycler recycler, RecyclerView.State state) { return canScrollHorizontally()? scrollBy(d, recycler, state) : 0; } @Override public final int scrollVerticallyBy(int d, RecyclerView.Recycler recycler, RecyclerView.State state) { return canScrollVertically()? scrollBy(d, recycler, state) : 0; } private int scrollBy(int d, RecyclerView.Recycler recycler, RecyclerView.State state) { d = calcOffset(d); offsetChildren(-d); scrollerListener.onScrolled(this, recycler, state); return d; } private int getLaidOutArea() { return stateFactory.getEndViewBound() - stateFactory.getStartViewBound(); } /** @see ChipsLayoutManager#computeVerticalScrollOffset(RecyclerView.State) * @see ChipsLayoutManager#computeHorizontalScrollOffset(RecyclerView.State) */ private int computeScrollOffset(RecyclerView.State state) { if (lm.getChildCount() == 0 || state.getItemCount() == 0) { return 0; } int firstVisiblePos = lm.findFirstVisibleItemPosition(); int lastVisiblePos = lm.findLastVisibleItemPosition(); final int itemsBefore = Math.max(0, firstVisiblePos); if (!lm.isSmoothScrollbarEnabled()) { return itemsBefore; } final int itemRange = Math.abs(firstVisiblePos - lastVisiblePos) + 1; final float avgSizePerRow = (float) getLaidOutArea() / itemRange; return Math.round(itemsBefore * avgSizePerRow + (stateFactory.getStartAfterPadding() - stateFactory.getStartViewBound())); } /** @see ChipsLayoutManager#computeVerticalScrollExtent(RecyclerView.State) * @see ChipsLayoutManager#computeHorizontalScrollExtent(RecyclerView.State) */ private int computeScrollExtent(RecyclerView.State state) { if (lm.getChildCount() == 0 || state.getItemCount() == 0) { return 0; } int firstVisiblePos = lm.findFirstVisibleItemPosition(); int lastVisiblePos = lm.findLastVisibleItemPosition(); if (!lm.isSmoothScrollbarEnabled()) { return Math.abs(lastVisiblePos - firstVisiblePos) + 1; } return Math.min(stateFactory.getTotalSpace(), getLaidOutArea()); } private int computeScrollRange(RecyclerView.State state) { if (lm.getChildCount() == 0 || state.getItemCount() == 0) { return 0; } if (!lm.isSmoothScrollbarEnabled()) { return state.getItemCount(); } int firstVisiblePos = lm.findFirstVisibleItemPosition(); int lastVisiblePos = lm.findLastVisibleItemPosition(); // smooth scrollbar enabled. try to estimate better. final int laidOutRange = Math.abs(firstVisiblePos - lastVisiblePos) + 1; // estimate a size for full list. return (int) ((float) getLaidOutArea() / laidOutRange * state.getItemCount()); } @Override public final int computeVerticalScrollExtent(RecyclerView.State state) { return canScrollVertically() ? computeScrollExtent(state) : 0; } @Override public final int computeVerticalScrollRange(RecyclerView.State state) { return canScrollVertically() ? computeScrollRange(state) : 0; } @Override public final int computeVerticalScrollOffset(RecyclerView.State state) { return canScrollVertically() ? computeScrollOffset(state) : 0; } @Override public final int computeHorizontalScrollRange(RecyclerView.State state) { return canScrollHorizontally() ? computeScrollRange(state) : 0; } @Override public final int computeHorizontalScrollOffset(RecyclerView.State state) { return canScrollHorizontally() ? computeScrollOffset(state) : 0; } @Override public final int computeHorizontalScrollExtent(RecyclerView.State state) { return canScrollHorizontally() ? computeScrollExtent(state) : 0; } } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/ScrollingController.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
1,946
```java package com.beloo.widget.chipslayoutmanager; import android.support.annotation.IntRange; import com.beloo.widget.chipslayoutmanager.layouter.breaker.IRowBreaker; interface IChipsLayoutManagerContract extends IPositionsContract, IScrollingContract { /** use it to strictly disable scrolling. * If scrolling enabled it would be disabled in case all items fit on the screen */ void setScrollingEnabledContract(boolean isEnabled); /** * change max count of row views in runtime */ void setMaxViewsInRow(@IntRange(from = 1) Integer maxViewsInRow); /** retrieve max views in row settings*/ Integer getMaxViewsInRow(); /** retrieve instantiated row breaker*/ IRowBreaker getRowBreaker(); /** retrieve row strategy type*/ @RowStrategy int getRowStrategyType(); @Orientation /** orientation type of layout manager*/ int layoutOrientation(); /** whether or not scrolling disabled outside*/ boolean isScrollingEnabledContract(); } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/IChipsLayoutManagerContract.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
212
```java package com.beloo.widget.chipslayoutmanager; import android.support.annotation.IntDef; import android.view.Gravity; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @IntDef({Gravity.TOP, Gravity.BOTTOM, Gravity.CENTER, Gravity.CENTER_VERTICAL, Gravity.CENTER_HORIZONTAL, Gravity.LEFT, Gravity.RIGHT, Gravity.FILL }) @Retention(RetentionPolicy.SOURCE) public @interface SpanLayoutChildGravity {} ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/SpanLayoutChildGravity.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
91
```java package com.beloo.widget.chipslayoutmanager; import android.graphics.Rect; import android.support.v7.widget.RecyclerView; import android.view.View; public class SpacingItemDecoration extends RecyclerView.ItemDecoration { private int horizontalSpacing; private int verticalSpacing; public SpacingItemDecoration(int horizontalSpacing, int verticalSpacing) { this.horizontalSpacing = horizontalSpacing; this.verticalSpacing = verticalSpacing; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.left = horizontalSpacing / 2; outRect.right = horizontalSpacing / 2; outRect.top = verticalSpacing / 2; outRect.bottom = verticalSpacing /2; } } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/SpacingItemDecoration.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
155
```java package com.beloo.widget.chipslayoutmanager; interface IScrollingContract { void setScrollingEnabledContract(boolean isEnabled); boolean isScrollingEnabledContract(); void setSmoothScrollbarEnabled(boolean enabled); boolean isSmoothScrollbarEnabled(); } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/IScrollingContract.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
52
```java package com.beloo.widget.chipslayoutmanager; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.View; import com.beloo.widget.chipslayoutmanager.layouter.ICanvas; import com.beloo.widget.chipslayoutmanager.layouter.IStateFactory; import java.util.List; class DisappearingViewsManager implements IDisappearingViewsManager { private ICanvas canvas; private ChildViewsIterable childViews; private IStateFactory stateFactory; /* in pre-layouter drawing we need item count with items will be actually deleted to pre-draw appearing items properly * buf value */ private int deletingItemsOnScreenCount; DisappearingViewsManager(ICanvas canvas, ChildViewsIterable childViews, IStateFactory stateFactory) { this.canvas = canvas; this.childViews = childViews; this.stateFactory = stateFactory; } class DisappearingViewsContainer { private SparseArray<View> backwardViews = new SparseArray<>(); private SparseArray<View> forwardViews = new SparseArray<>(); int size() { return backwardViews.size() + forwardViews.size(); } SparseArray<View> getBackwardViews() { return backwardViews; } SparseArray<View> getForwardViews() { return forwardViews; } } /** @return views which moved from screen, but not deleted*/ @Override public DisappearingViewsContainer getDisappearingViews(RecyclerView.Recycler recycler) { final List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList(); DisappearingViewsContainer container = new DisappearingViewsContainer(); for (RecyclerView.ViewHolder holder : scrapList) { final View child = holder.itemView; final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams(); if (!lp.isItemRemoved()) { if (lp.getViewAdapterPosition() < canvas.getMinPositionOnScreen()) { container.backwardViews.put(lp.getViewAdapterPosition(), child); } else if (lp.getViewAdapterPosition() > canvas.getMaxPositionOnScreen()) { container.forwardViews.put(lp.getViewAdapterPosition(), child); } } } return container; } /** during pre-layout calculate approximate height which will be free after moving items offscreen (removed or moved) * @return approximate height of disappearing views. Could be bigger, than accurate value. */ @Override public int calcDisappearingViewsLength(RecyclerView.Recycler recycler) { int removedLength = 0; Integer minStart = Integer.MAX_VALUE; Integer maxEnd = Integer.MIN_VALUE; for (View view : childViews) { RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams(); boolean probablyMovedFromScreen = false; if (!lp.isItemRemoved()) { //view won't be removed, but maybe it is moved offscreen int pos = lp.getViewLayoutPosition(); pos = recycler.convertPreLayoutPositionToPostLayout(pos); probablyMovedFromScreen = pos < canvas.getMinPositionOnScreen() || pos > canvas.getMaxPositionOnScreen(); } if (lp.isItemRemoved() || probablyMovedFromScreen) { deletingItemsOnScreenCount++; minStart = Math.min(minStart, stateFactory.getStart(view)); maxEnd = Math.max(maxEnd, stateFactory.getEnd(view)); } } if (minStart != Integer.MAX_VALUE) { removedLength = maxEnd - minStart; } return removedLength; } @Override public int getDeletingItemsOnScreenCount() { return deletingItemsOnScreenCount; } @Override public void reset() { deletingItemsOnScreenCount = 0; } } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/DisappearingViewsManager.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
783
```java package com.beloo.widget.chipslayoutmanager; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import com.beloo.widget.chipslayoutmanager.anchor.AnchorViewState; public interface IScrollingController { RecyclerView.SmoothScroller createSmoothScroller(@NonNull Context context, int position, int timeMs, AnchorViewState anchor); boolean canScrollVertically(); boolean canScrollHorizontally(); /** * calculate offset of views while scrolling, layout items on new places */ int scrollVerticallyBy(int d, RecyclerView.Recycler recycler, RecyclerView.State state); int scrollHorizontallyBy(int d, RecyclerView.Recycler recycler, RecyclerView.State state); /** changes may cause gaps on the UI, try to fix them */ boolean normalizeGaps(RecyclerView.Recycler recycler, RecyclerView.State state); /** @see ChipsLayoutManager#computeVerticalScrollOffset(RecyclerView.State) */ int computeVerticalScrollOffset(RecyclerView.State state); /** @see ChipsLayoutManager#computeVerticalScrollExtent(RecyclerView.State) */ int computeVerticalScrollExtent(RecyclerView.State state); /** @see ChipsLayoutManager#computeVerticalScrollRange(RecyclerView.State) */ int computeVerticalScrollRange(RecyclerView.State state); /** @see ChipsLayoutManager#computeHorizontalScrollOffset(RecyclerView.State) */ int computeHorizontalScrollOffset(RecyclerView.State state); /** @see ChipsLayoutManager#computeHorizontalScrollExtent(RecyclerView.State) */ int computeHorizontalScrollExtent(RecyclerView.State state); /** @see ChipsLayoutManager#computeHorizontalScrollRange(RecyclerView.State) */ int computeHorizontalScrollRange(RecyclerView.State state); } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/IScrollingController.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
341
```java package com.beloo.widget.chipslayoutmanager; interface IPositionsContract { int findFirstVisibleItemPosition(); int findFirstCompletelyVisibleItemPosition(); int findLastVisibleItemPosition(); int findLastCompletelyVisibleItemPosition(); } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/IPositionsContract.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
53
```java package com.beloo.widget.chipslayoutmanager; import android.content.Context; import android.graphics.PointF; import android.support.annotation.NonNull; import android.support.v7.widget.LinearSmoothScroller; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.animation.LinearInterpolator; import com.beloo.widget.chipslayoutmanager.anchor.AnchorViewState; import com.beloo.widget.chipslayoutmanager.layouter.IStateFactory; class VerticalScrollingController extends ScrollingController implements IScrollingController { private ChipsLayoutManager lm; VerticalScrollingController(ChipsLayoutManager layoutManager, IStateFactory stateFactory, IScrollerListener scrollerListener) { super(layoutManager, stateFactory, scrollerListener); this.lm = layoutManager; } @Override public RecyclerView.SmoothScroller createSmoothScroller(@NonNull Context context, final int position, final int timeMs, final AnchorViewState anchor) { return new LinearSmoothScroller(context) { /* * LinearSmoothScroller, at a minimum, just need to know the vector * (x/y distance) to travel in order to get from the current positioning * to the target. */ @Override public PointF computeScrollVectorForPosition(int targetPosition) { int visiblePosition = anchor.getPosition(); //determine scroll up or scroll down needed return new PointF(0, position > visiblePosition ? 1 : -1); } @Override protected void onTargetFound(View targetView, RecyclerView.State state, Action action) { super.onTargetFound(targetView, state, action); int desiredTop = lm.getPaddingTop(); int currentTop = lm.getDecoratedTop(targetView); int dy = currentTop - desiredTop; //perform fit animation to move target view at top of layout action.update(0, dy, timeMs, new LinearInterpolator()); } }; } @Override public boolean canScrollVertically() { canvas.findBorderViews(); if (lm.getChildCount() > 0) { int top = lm.getDecoratedTop(canvas.getTopView()); int bottom = lm.getDecoratedBottom(canvas.getBottomView()); if (canvas.getMinPositionOnScreen() == 0 && canvas.getMaxPositionOnScreen() == lm.getItemCount() - 1 && top >= lm.getPaddingTop() && bottom <= lm.getHeight() - lm.getPaddingBottom()) { return false; } } else { return false; } return lm.isScrollingEnabledContract(); } @Override public boolean canScrollHorizontally() { return false; } @Override void offsetChildren(int d) { lm.offsetChildrenVertical(d); } } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/VerticalScrollingController.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
584
```java package com.beloo.widget.chipslayoutmanager; interface IStateHolder { boolean isLayoutRTL(); @Orientation int layoutOrientation(); } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/IStateHolder.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
32
```java package com.beloo.widget.chipslayoutmanager.layouter; import android.graphics.Rect; import android.support.annotation.NonNull; import android.util.Pair; import android.view.View; import java.util.Collections; class LTRUpLayouter extends AbstractLayouter implements ILayouter { private LTRUpLayouter(Builder builder) { super(builder); } public static Builder newBuilder() { return new Builder(); } @Override Rect createViewRect(View view) { int left = viewRight - getCurrentViewWidth(); int viewTop = viewBottom - getCurrentViewHeight(); Rect viewRect = new Rect(left, viewTop, viewRight, viewBottom); viewRight = viewRect.left; return viewRect; } @Override boolean isReverseOrder() { return true; } @Override void onPreLayout() { int leftOffsetOfRow = viewRight - getCanvasLeftBorder(); viewLeft = 0; for (Pair<Rect, View> rowViewRectPair : rowViews) { Rect viewRect = rowViewRectPair.first; viewRect.left = viewRect.left - leftOffsetOfRow; viewRect.right = viewRect.right - leftOffsetOfRow; viewLeft = Math.max(viewRect.right, viewLeft); viewTop = Math.min(viewTop, viewRect.top); viewBottom = Math.max(viewBottom, viewRect.bottom); } } @Override void onAfterLayout() { //go to next row, increase top coordinate, reset left viewRight = getCanvasRightBorder(); viewBottom = viewTop; } @Override boolean isAttachedViewFromNewRow(View view) { int bottomOfCurrentView = getLayoutManager().getDecoratedBottom(view); int rightOfCurrentView = getLayoutManager().getDecoratedRight(view); return viewTop >= bottomOfCurrentView && rightOfCurrentView > viewRight; } @Override public void onInterceptAttachView(View view) { if (viewRight != getCanvasRightBorder() && viewRight - getCurrentViewWidth() < getCanvasLeftBorder()) { //new row viewRight = getCanvasRightBorder(); viewBottom = viewTop; } else { viewRight = getLayoutManager().getDecoratedLeft(view); } viewTop = Math.min(viewTop, getLayoutManager().getDecoratedTop(view)); } @Override public int getStartRowBorder() { return getViewTop(); } @Override public int getEndRowBorder() { return getViewBottom(); } @Override public int getRowLength() { return getCanvasRightBorder() - viewRight; } public static final class Builder extends AbstractLayouter.Builder { private Builder() { } @NonNull public LTRUpLayouter createLayouter() { return new LTRUpLayouter(this); } } } ```
/content/code_sandbox/ChipsLayoutManager/src/main/java/com/beloo/widget/chipslayoutmanager/layouter/LTRUpLayouter.java
java
2016-08-03T19:23:43
2024-08-12T07:26:54
ChipsLayoutManager
BelooS/ChipsLayoutManager
3,247
637