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.arellomobile.mvp.compiler; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import com.arellomobile.mvp.MvpPresenter; import com.arellomobile.mvp.MvpView; import com.arellomobile.mvp.presenter.InjectPresenter; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.tools.Diagnostic; import static com.arellomobile.mvp.compiler.Util.fillGenerics; /** * Date: 17-Feb-16 * Time: 17:00 * * @author esorokin */ public class PresenterInjectorRules extends AnnotationRule { public PresenterInjectorRules(ElementKind validKind, Modifier... validModifiers) { super(validKind, validModifiers); } @SuppressWarnings("StringConcatenationInsideStringBufferAppend") @Override public void checkAnnotation(Element annotatedField) { checkEnvironment(annotatedField); if (annotatedField.getKind() != mValidKind) { mErrorBuilder.append("Field " + annotatedField + " of " + annotatedField.getEnclosingElement().getSimpleName() + " should be " + mValidKind.name() + ", or not mark it as @" + InjectPresenter.class.getSimpleName()).append("\n"); } for (Modifier modifier : annotatedField.getModifiers()) { if (!mValidModifiers.contains(modifier)) { mErrorBuilder.append("Field " + annotatedField + " of " + annotatedField.getEnclosingElement().getSimpleName() + " can't be a " + modifier).append(". Use ").append(validModifiersToString()).append("\n"); } } Element enclosingElement = annotatedField.getEnclosingElement(); while (enclosingElement.getKind() == ElementKind.CLASS) { if (!enclosingElement.getModifiers().contains(Modifier.PUBLIC)) { mErrorBuilder.append(enclosingElement.getSimpleName() + " should be PUBLIC "); break; } enclosingElement = enclosingElement.getEnclosingElement(); } } private void checkEnvironment(final Element annotatedField) { if (!(annotatedField.asType() instanceof DeclaredType)) { return; } TypeElement typeElement = (TypeElement) ((DeclaredType) annotatedField.asType()).asElement(); String viewClassFromGeneric = getViewClassFromGeneric(typeElement, (DeclaredType) annotatedField.asType()); Collection<TypeMirror> viewsType = getViewsType((TypeElement) ((DeclaredType) annotatedField.getEnclosingElement().asType()).asElement()); boolean result = false; for (TypeMirror typeMirror : viewsType) { if (Util.getFullClassName(typeMirror).equals(viewClassFromGeneric) || Util.fillGenerics(Collections.<String, String>emptyMap(), typeMirror).equals(viewClassFromGeneric)) { result = true; break; } } if (!result) { MvpCompiler.getMessager().printMessage(Diagnostic.Kind.ERROR, "You can not use @InjectPresenter in classes that are not View, which is typified target Presenter", annotatedField); } } private String getViewClassFromGeneric(TypeElement typeElement, DeclaredType declaredType) { TypeMirror superclass = declaredType; Map<TypeParameterElement, TypeMirror> mTypedMap = Collections.emptyMap(); if (!typeElement.getTypeParameters().isEmpty()) { mTypedMap = getChildInstanceOfClassFromGeneric(typeElement, MvpView.class); } Map<String, String> parentTypes = Collections.emptyMap(); List<? extends TypeMirror> totalTypeArguments = new ArrayList<>(((DeclaredType) superclass).getTypeArguments()); while (superclass.getKind() != TypeKind.NONE) { TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement(); List<? extends TypeMirror> typeArguments = ((DeclaredType) superclass).getTypeArguments(); totalTypeArguments.retainAll(typeArguments); final List<? extends TypeParameterElement> typeParameters = superclassElement.getTypeParameters(); Map<String, String> types = new HashMap<>(); for (int i = 0; i < typeArguments.size(); i++) { types.put(typeParameters.get(i).toString(), fillGenerics(parentTypes, typeArguments.get(i))); } if (superclassElement.toString().equals(MvpPresenter.class.getCanonicalName())) { if (!typeArguments.isEmpty()) { TypeMirror typeMirror = typeArguments.get(0); if (typeMirror instanceof TypeVariable) { Element key = ((TypeVariable) typeMirror).asElement(); for (Map.Entry<TypeParameterElement, TypeMirror> entry : mTypedMap.entrySet()) { if (entry.getKey().toString().equals(key.toString())) { return Util.getFullClassName(entry.getValue()); } } } } if (typeArguments.isEmpty() && typeParameters.isEmpty()) { return ((DeclaredType) superclass).asElement().getSimpleName().toString(); } // MvpPresenter is typed only on View class return fillGenerics(parentTypes, typeArguments); } parentTypes = types; superclass = superclassElement.getSuperclass(); } return ""; } private Map<TypeParameterElement, TypeMirror> getChildInstanceOfClassFromGeneric(final TypeElement typeElement, final Class<?> aClass) { Map<TypeParameterElement, TypeMirror> result = new HashMap<>(); for (TypeParameterElement element : typeElement.getTypeParameters()) { List<? extends TypeMirror> bounds = element.getBounds(); for (TypeMirror bound : bounds) { if (bound instanceof DeclaredType && ((DeclaredType) bound).asElement() instanceof TypeElement) { Collection<TypeMirror> viewsType = getViewsType((TypeElement) ((DeclaredType) bound).asElement()); boolean isViewType = false; for (TypeMirror viewType : viewsType) { if (((DeclaredType) viewType).asElement().toString().equals(aClass.getCanonicalName())) { isViewType = true; } } if (isViewType) { result.put(element, bound); break; } } } } return result; } private Collection<TypeMirror> getViewsType(TypeElement typeElement) { TypeMirror superclass = typeElement.asType(); List<TypeMirror> result = new ArrayList<>(); while (superclass.getKind() != TypeKind.NONE) { TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement(); Collection<? extends TypeMirror> interfaces = new HashSet<>(superclassElement.getInterfaces()); for (TypeMirror typeMirror : interfaces) { if (typeMirror instanceof DeclaredType) { result.addAll(getViewsType((TypeElement) ((DeclaredType) typeMirror).asElement())); } } result.addAll(interfaces); result.add(superclass); superclass = superclassElement.getSuperclass(); } return result; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/PresenterInjectorRules.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
1,547
```java package com.arellomobile.mvp.compiler; import com.squareup.javapoet.JavaFile; import java.util.List; /** * Date: 27-Jul-17 * Time: 10:26 * * @author Evgeny Kursakov */ public abstract class JavaFilesGenerator<T> { public abstract List<JavaFile> generate(T input); } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/JavaFilesGenerator.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
75
```java /* * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.arellomobile.mvp.compiler; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.IntersectionType; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.type.WildcardType; /** * Utilities for handling types in annotation processors * * @author Yuri Shmakov */ @SuppressWarnings("WeakerAccess") public final class Util { public static String fillGenerics(Map<String, String> types, TypeMirror param) { return fillGenerics(types, Collections.singletonList(param)); } public static String fillGenerics(Map<String, String> types, List<? extends TypeMirror> params) { return fillGenerics(types, params, ", "); } public static String fillGenerics(Map<String, String> types, List<? extends TypeMirror> params, String separator) { String result = ""; for (TypeMirror param : params) { if (result.length() > 0) { result += separator; } /** * "if" block's order is critically! E.g. IntersectionType is TypeVariable. */ if (param instanceof WildcardType) { result += "?"; final TypeMirror extendsBound = ((WildcardType) param).getExtendsBound(); if (extendsBound != null) { result += " extends " + fillGenerics(types, extendsBound); } final TypeMirror superBound = ((WildcardType) param).getSuperBound(); if (superBound != null) { result += " super " + fillGenerics(types, superBound); } } else if (param instanceof IntersectionType) { result += "?"; final List<? extends TypeMirror> bounds = ((IntersectionType) param).getBounds(); if (!bounds.isEmpty()) { result += " extends " + fillGenerics(types, bounds, " & "); } } else if (param instanceof DeclaredType) { result += ((DeclaredType) param).asElement(); final List<? extends TypeMirror> typeArguments = ((DeclaredType) param).getTypeArguments(); if (!typeArguments.isEmpty()) { final String s = fillGenerics(types, typeArguments); result += "<" + s + ">"; } } else if (param instanceof TypeVariable) { String type = types.get(param.toString()); if (type == null) { type = param.toString(); } result += type; } else { result += param; } } return result; } public static String getFullClassName(TypeMirror typeMirror) { if (!(typeMirror instanceof DeclaredType)) { return ""; } TypeElement typeElement = (TypeElement) ((DeclaredType) typeMirror).asElement(); return getFullClassName(typeElement); } public static String getFullClassName(TypeElement typeElement) { String packageName = MvpCompiler.getElementUtils().getPackageOf(typeElement).getQualifiedName().toString(); if (packageName.length() > 0) { packageName += "."; } String className = typeElement.toString().substring(packageName.length()); return packageName + className.replaceAll("\\.", "\\$"); } public static AnnotationMirror getAnnotation(Element element, String annotationClass) { for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { if (annotationMirror.getAnnotationType().asElement().toString().equals(annotationClass)) return annotationMirror; } return null; } public static TypeMirror getAnnotationValueAsTypeMirror(AnnotationMirror annotationMirror, String key) { AnnotationValue av = getAnnotationValue(annotationMirror, key); if (av != null) { return (TypeMirror) av.getValue(); } else { return null; } } public static String getAnnotationValueAsString(AnnotationMirror annotationMirror, String key) { AnnotationValue av = getAnnotationValue(annotationMirror, key); if (av != null) { return av.getValue().toString(); } else { return null; } } public static AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String key) { if (annotationMirror == null) return null; for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { if (entry.getKey().getSimpleName().toString().equals(key)) { return entry.getValue(); } } return null; } public static Map<String, AnnotationValue> getAnnotationValues(AnnotationMirror annotationMirror) { if (annotationMirror == null) return Collections.emptyMap(); Map<String, AnnotationValue> result = new HashMap<>(); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { String key = entry.getKey().getSimpleName().toString(); if (entry.getValue() != null) { result.put(key, entry.getValue()); } } return result; } public static boolean hasEmptyConstructor(TypeElement element) { for (Element enclosedElement : element.getEnclosedElements()) { if (enclosedElement.getKind() == ElementKind.CONSTRUCTOR) { List<? extends VariableElement> parameters = ((ExecutableElement) enclosedElement).getParameters(); if (parameters == null || parameters.isEmpty()) { return true; } } } return false; } public static String decapitalizeString(String string) { return string == null || string.isEmpty() ? "" : string.length() == 1 ? string.toLowerCase() : Character.toLowerCase(string.charAt(0)) + string.substring(1); } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/Util.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
1,320
```java package com.arellomobile.mvp.compiler.viewstate; import com.google.common.collect.Iterables; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeVariableName; import java.util.List; import java.util.stream.Collectors; import javax.lang.model.element.TypeElement; /** * Date: 27-Jul-2017 * Time: 13:04 * * @author Evgeny Kursakov */ class ViewInterfaceInfo { private final ClassName name; private final List<TypeVariableName> typeVariables; private final List<ViewMethod> methods; ViewInterfaceInfo(TypeElement name, List<ViewMethod> methods) { this.name = ClassName.get(name); this.methods = methods; this.typeVariables = name.getTypeParameters().stream() .map(TypeVariableName::get) .collect(Collectors.toList()); } ClassName getName() { return name; } TypeName getNameWithTypeVariables() { if (typeVariables.isEmpty()) { return name; } else { return ParameterizedTypeName.get(name, Iterables.toArray(typeVariables, TypeVariableName.class)); } } List<TypeVariableName> getTypeVariables() { return typeVariables; } List<ViewMethod> getMethods() { return methods; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/viewstate/ViewInterfaceInfo.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
282
```java package com.arellomobile.mvp.compiler.reflector; import com.arellomobile.mvp.MvpProcessor; import com.arellomobile.mvp.ViewStateProvider; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import static com.arellomobile.mvp.compiler.MvpCompiler.MOXY_REFLECTOR_DEFAULT_PACKAGE; /** * Date: 07.12.2016 * Time: 19:05 * * @author Yuri Shmakov */ public class MoxyReflectorGenerator { private static final Comparator<TypeElement> TYPE_ELEMENT_COMPARATOR = Comparator.comparing(Object::toString); private static final TypeName CLASS_WILDCARD_TYPE_NAME // Class<*> = ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(TypeName.OBJECT)); private static final TypeName LIST_OF_OBJECT_TYPE_NAME // List<Object> = ParameterizedTypeName.get(ClassName.get(List.class), TypeName.OBJECT); private static final TypeName MAP_CLASS_TO_OBJECT_TYPE_NAME // Map<Class<*>, Object> = ParameterizedTypeName.get(ClassName.get(Map.class), CLASS_WILDCARD_TYPE_NAME, TypeName.OBJECT); private static final TypeName MAP_CLASS_TO_LIST_OF_OBJECT_TYPE_NAME // Map<Class<*>, List<Object>> = ParameterizedTypeName.get(ClassName.get(Map.class), CLASS_WILDCARD_TYPE_NAME, LIST_OF_OBJECT_TYPE_NAME); public static JavaFile generate(String destinationPackage, List<TypeElement> presenterClassNames, List<TypeElement> presentersContainers, List<TypeElement> strategyClasses, List<String> additionalMoxyReflectorsPackages) { TypeSpec.Builder classBuilder = TypeSpec.classBuilder("MoxyReflector") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addField(MAP_CLASS_TO_OBJECT_TYPE_NAME, "sViewStateProviders", Modifier.PRIVATE, Modifier.STATIC) .addField(MAP_CLASS_TO_LIST_OF_OBJECT_TYPE_NAME, "sPresenterBinders", Modifier.PRIVATE, Modifier.STATIC) .addField(MAP_CLASS_TO_OBJECT_TYPE_NAME, "sStrategies", Modifier.PRIVATE, Modifier.STATIC); classBuilder.addStaticBlock(generateStaticInitializer(presenterClassNames, presentersContainers, strategyClasses, additionalMoxyReflectorsPackages)); if (destinationPackage.equals(MOXY_REFLECTOR_DEFAULT_PACKAGE)) { classBuilder.addMethod(MethodSpec.methodBuilder("getViewState") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(Object.class) .addParameter(CLASS_WILDCARD_TYPE_NAME, "presenterClass") .addStatement("$1T viewStateProvider = ($1T) sViewStateProviders.get(presenterClass)", ViewStateProvider.class) .beginControlFlow("if (viewStateProvider == null)") .addStatement("return null") .endControlFlow() .addCode("\n") .addStatement("return viewStateProvider.getViewState()") .build()); classBuilder.addMethod(MethodSpec.methodBuilder("getPresenterBinders") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(ParameterizedTypeName.get(List.class, Object.class)) .addParameter(CLASS_WILDCARD_TYPE_NAME, "delegated") .addStatement("return sPresenterBinders.get(delegated)") .build()); classBuilder.addMethod(MethodSpec.methodBuilder("getStrategy") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(Object.class) .addParameter(CLASS_WILDCARD_TYPE_NAME, "strategyClass") .addStatement("return sStrategies.get(strategyClass)") .build()); } else { classBuilder.addMethod(MethodSpec.methodBuilder("getViewStateProviders") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(MAP_CLASS_TO_OBJECT_TYPE_NAME) .addStatement("return viewStateProvider.getViewState()") .build()); classBuilder.addMethod(MethodSpec.methodBuilder("getPresenterBinders") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(MAP_CLASS_TO_LIST_OF_OBJECT_TYPE_NAME) .addStatement("return sViewStateProviders") .build()); classBuilder.addMethod(MethodSpec.methodBuilder("getStrategies") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(MAP_CLASS_TO_OBJECT_TYPE_NAME) .addStatement("return sStrategies") .build()); } return JavaFile.builder(destinationPackage, classBuilder.build()) .indent("\t") .build(); } private static CodeBlock generateStaticInitializer(List<TypeElement> presenterClassNames, List<TypeElement> presentersContainers, List<TypeElement> strategyClasses, List<String> additionalMoxyReflectorsPackages) { // sort to preserve order of statements between compilations Map<TypeElement, List<TypeElement>> presenterBinders = getPresenterBinders(presentersContainers); presenterClassNames.sort(TYPE_ELEMENT_COMPARATOR); strategyClasses.sort(TYPE_ELEMENT_COMPARATOR); additionalMoxyReflectorsPackages.sort(Comparator.naturalOrder()); CodeBlock.Builder builder = CodeBlock.builder(); builder.addStatement("sViewStateProviders = new $T<>()", HashMap.class); for (TypeElement presenter : presenterClassNames) { ClassName presenterClassName = ClassName.get(presenter); ClassName viewStateProvider = ClassName.get(presenterClassName.packageName(), String.join("$", presenterClassName.simpleNames()) + MvpProcessor.VIEW_STATE_PROVIDER_SUFFIX); builder.addStatement("sViewStateProviders.put($T.class, new $T())", presenterClassName, viewStateProvider); } builder.add("\n"); builder.addStatement("sPresenterBinders = new $T<>()", HashMap.class); for (Map.Entry<TypeElement, List<TypeElement>> keyValue : presenterBinders.entrySet()) { builder.add("sPresenterBinders.put($T.class, $T.<Object>asList(", keyValue.getKey(), Arrays.class); boolean isFirst = true; for (TypeElement typeElement : keyValue.getValue()) { ClassName className = ClassName.get(typeElement); String presenterBinderName = String.join("$", className.simpleNames()) + MvpProcessor.PRESENTER_BINDER_SUFFIX; if (isFirst) { isFirst = false; } else { builder.add(", "); } builder.add("new $T()", ClassName.get(className.packageName(), presenterBinderName)); } builder.add("));\n"); } builder.add("\n"); builder.addStatement("sStrategies = new $T<>()", HashMap.class); for (TypeElement strategyClass : strategyClasses) { builder.addStatement("sStrategies.put($1T.class, new $1T())", strategyClass); } for (String pkg : additionalMoxyReflectorsPackages) { ClassName moxyReflector = ClassName.get(pkg, "MoxyReflector"); builder.add("\n"); builder.addStatement("sViewStateProviders.putAll($T.getViewStateProviders())", moxyReflector); builder.addStatement("sPresenterBinders.putAll($T.getPresenterBinders())", moxyReflector); builder.addStatement("sStrategies.putAll($T.getStrategies())", moxyReflector); } return builder.build(); } /** * Collects presenter binders from superclasses that are also presenter containers. * * @return sorted map between presenter container and list of corresponding binders */ private static SortedMap<TypeElement, List<TypeElement>> getPresenterBinders(List<TypeElement> presentersContainers) { Map<TypeElement, TypeElement> extendingMap = new HashMap<>(); for (TypeElement presentersContainer : presentersContainers) { TypeMirror superclass = presentersContainer.getSuperclass(); TypeElement parent = null; while (superclass.getKind() == TypeKind.DECLARED) { TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement(); if (presentersContainers.contains(superclassElement)) { parent = superclassElement; break; } superclass = superclassElement.getSuperclass(); } extendingMap.put(presentersContainer, parent); } // TreeMap for sorting SortedMap<TypeElement, List<TypeElement>> elementListMap = new TreeMap<>(TYPE_ELEMENT_COMPARATOR); for (TypeElement presentersContainer : presentersContainers) { ArrayList<TypeElement> typeElements = new ArrayList<>(); typeElements.add(presentersContainer); TypeElement key = presentersContainer; while ((key = extendingMap.get(key)) != null) { typeElements.add(key); } elementListMap.put(presentersContainer, typeElements); } return elementListMap; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/reflector/MoxyReflectorGenerator.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
2,016
```java package com.arellomobile.mvp.compiler.viewstate; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeVariableName; import java.util.List; import java.util.stream.Collectors; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; /** * Date: 27-Jul-2017 * Time: 12:58 * * @author Evgeny Kursakov */ class ViewMethod { private final ExecutableElement element; private final String name; private final TypeElement strategy; private final String tag; private final List<ParameterSpec> parameterSpecs; private final List<TypeName> exceptions; private final List<TypeVariableName> typeVariables; private final String argumentsString; private String uniqueSuffix; ViewMethod(ExecutableElement methodElement, TypeElement strategy, String tag) { this.element = methodElement; this.name = methodElement.getSimpleName().toString(); this.strategy = strategy; this.tag = tag; this.parameterSpecs = methodElement.getParameters() .stream() .map(ParameterSpec::get) .collect(Collectors.toList()); this.exceptions = methodElement.getThrownTypes().stream() .map(TypeName::get) .collect(Collectors.toList()); this.typeVariables = methodElement.getTypeParameters() .stream() .map(TypeVariableName::get) .collect(Collectors.toList()); this.argumentsString = parameterSpecs.stream() .map(parameterSpec -> parameterSpec.name) .collect(Collectors.joining(", ")); this.uniqueSuffix = ""; } ExecutableElement getElement() { return element; } String getName() { return name; } TypeElement getStrategy() { return strategy; } String getTag() { return tag; } List<ParameterSpec> getParameterSpecs() { return parameterSpecs; } List<TypeName> getExceptions() { return exceptions; } List<TypeVariableName> getTypeVariables() { return typeVariables; } String getArgumentsString() { return argumentsString; } String getCommandClassName() { return name.substring(0, 1).toUpperCase() + name.substring(1) + uniqueSuffix + "Command"; } String getEnclosedClassName() { TypeElement typeElement = (TypeElement) element.getEnclosingElement(); return typeElement.getQualifiedName().toString(); } String getUniqueSuffix() { return uniqueSuffix; } void setUniqueSuffix(String uniqueSuffix) { this.uniqueSuffix = uniqueSuffix; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ViewMethod that = (ViewMethod) o; return name.equals(that.name) && parameterSpecs.equals(that.parameterSpecs); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + parameterSpecs.hashCode(); return result; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/viewstate/ViewMethod.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
640
```java package com.arellomobile.mvp.compiler.viewstate; import com.arellomobile.mvp.MvpProcessor; import com.arellomobile.mvp.compiler.JavaFilesGenerator; import com.arellomobile.mvp.viewstate.MvpViewState; import com.arellomobile.mvp.viewstate.ViewCommand; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.Collections; import java.util.List; import java.util.Random; import javax.lang.model.element.Modifier; import static com.arellomobile.mvp.compiler.Util.decapitalizeString; /** * Date: 18.12.2015 * Time: 13:24 * * @author Yuri Shmakov */ public final class ViewStateClassGenerator extends JavaFilesGenerator<ViewInterfaceInfo> { @Override public List<JavaFile> generate(ViewInterfaceInfo viewInterfaceInfo) { ClassName viewName = viewInterfaceInfo.getName(); TypeName nameWithTypeVariables = viewInterfaceInfo.getNameWithTypeVariables(); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(viewName.simpleName() + MvpProcessor.VIEW_STATE_SUFFIX) .addModifiers(Modifier.PUBLIC) .superclass(ParameterizedTypeName.get(ClassName.get(MvpViewState.class), nameWithTypeVariables)) .addSuperinterface(nameWithTypeVariables) .addTypeVariables(viewInterfaceInfo.getTypeVariables()); for (ViewMethod method : viewInterfaceInfo.getMethods()) { TypeSpec commandClass = generateCommandClass(method, nameWithTypeVariables); classBuilder.addType(commandClass); classBuilder.addMethod(generateMethod(method, nameWithTypeVariables, commandClass)); } JavaFile javaFile = JavaFile.builder(viewName.packageName(), classBuilder.build()) .indent("\t") .build(); return Collections.singletonList(javaFile); } private TypeSpec generateCommandClass(ViewMethod method, TypeName viewTypeName) { MethodSpec applyMethod = MethodSpec.methodBuilder("apply") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(viewTypeName, "mvpView") .addExceptions(method.getExceptions()) .addStatement("mvpView.$L($L)", method.getName(), method.getArgumentsString()) .build(); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(method.getCommandClassName()) .addModifiers(Modifier.PUBLIC) // TODO: private and static .addTypeVariables(method.getTypeVariables()) .superclass(ParameterizedTypeName.get(ClassName.get(ViewCommand.class), viewTypeName)) .addMethod(generateCommandConstructor(method)) .addMethod(applyMethod); for (ParameterSpec parameter : method.getParameterSpecs()) { // TODO: private field classBuilder.addField(parameter.type, parameter.name, Modifier.PUBLIC, Modifier.FINAL); } return classBuilder.build(); } private MethodSpec generateMethod(ViewMethod method, TypeName viewTypeName, TypeSpec commandClass) { // TODO: String commandFieldName = "$cmd"; String commandFieldName = decapitalizeString(method.getCommandClassName()); // Add salt if contains argument with same name Random random = new Random(); while (method.getArgumentsString().contains(commandFieldName)) { commandFieldName += random.nextInt(10); } return MethodSpec.overriding(method.getElement()) .addStatement("$1N $2L = new $1N($3L)", commandClass, commandFieldName, method.getArgumentsString()) .addStatement("mViewCommands.beforeApply($L)", commandFieldName) .addCode("\n") .beginControlFlow("if (mViews == null || mViews.isEmpty())") .addStatement("return") .endControlFlow() .addCode("\n") .beginControlFlow("for ($T view : mViews)", viewTypeName) .addStatement("view.$L($L)", method.getName(), method.getArgumentsString()) .endControlFlow() .addCode("\n") .addStatement("mViewCommands.afterApply($L)", commandFieldName) .build(); } private MethodSpec generateCommandConstructor(ViewMethod method) { List<ParameterSpec> parameters = method.getParameterSpecs(); MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addParameters(parameters) .addStatement("super($S, $T.class)", method.getTag(), method.getStrategy()); if (parameters.size() > 0) { builder.addCode("\n"); } for (ParameterSpec parameter : parameters) { builder.addStatement("this.$1N = $1N", parameter); } return builder.build(); } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/viewstate/ViewStateClassGenerator.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
1,014
```java package com.arellomobile.mvp.compiler.presenterbinder; import com.arellomobile.mvp.presenter.PresenterType; import javax.lang.model.type.DeclaredType; class PresenterProviderMethod { private final DeclaredType clazz; private final String name; private final PresenterType presenterType; private final String tag; private final String presenterId; PresenterProviderMethod(DeclaredType clazz, String name, String type, String tag, String presenterId) { this.clazz = clazz; this.name = name; if (type == null) { presenterType = PresenterType.LOCAL; } else { presenterType = PresenterType.valueOf(type); } this.tag = tag; this.presenterId = presenterId; } DeclaredType getClazz() { return clazz; } String getName() { return name; } PresenterType getPresenterType() { return presenterType; } String getTag() { return tag; } String getPresenterId() { return presenterId; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/presenterbinder/PresenterProviderMethod.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
220
```java package com.arellomobile.mvp.compiler.presenterbinder; import com.arellomobile.mvp.MvpProcessor; import com.arellomobile.mvp.presenter.PresenterType; import com.squareup.javapoet.TypeName; import javax.lang.model.type.TypeMirror; class TargetPresenterField { private final TypeMirror clazz; private final TypeName typeName; private final String name; private final PresenterType presenterType; private final String tag; private final String presenterId; private String presenterProviderMethodName; private String presenterTagProviderMethodName; TargetPresenterField(TypeMirror clazz, String name, String presenterType, String tag, String presenterId) { this.clazz = clazz; this.typeName = TypeName.get(clazz); this.name = name; this.tag = tag; if (presenterType == null) { this.presenterType = PresenterType.LOCAL; } else { this.presenterType = PresenterType.valueOf(presenterType); } this.presenterId = presenterId; } TypeMirror getClazz() { return clazz; } TypeName getTypeName() { return typeName; } String getGeneratedClassName() { return name + MvpProcessor.PRESENTER_BINDER_INNER_SUFFIX; } String getTag() { return tag; } String getName() { return name; } PresenterType getPresenterType() { return presenterType; } String getPresenterId() { return presenterId; } String getPresenterProviderMethodName() { return presenterProviderMethodName; } void setPresenterProviderMethodName(String presenterProviderMethodName) { this.presenterProviderMethodName = presenterProviderMethodName; } String getPresenterTagProviderMethodName() { return presenterTagProviderMethodName; } void setPresenterTagProviderMethodName(String presenterTagProviderMethodName) { this.presenterTagProviderMethodName = presenterTagProviderMethodName; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/presenterbinder/TargetPresenterField.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
395
```java package com.arellomobile.mvp.compiler.viewstate; import com.arellomobile.mvp.compiler.ElementProcessor; import com.arellomobile.mvp.compiler.MvpCompiler; import com.arellomobile.mvp.compiler.Util; import com.arellomobile.mvp.viewstate.strategy.AddToEndStrategy; import com.arellomobile.mvp.viewstate.strategy.StateStrategyType; import com.squareup.javapoet.ParameterSpec; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic; /** * Date: 27-Jul-2017 * Time: 13:09 * * @author Evgeny Kursakov */ public class ViewInterfaceProcessor extends ElementProcessor<TypeElement, ViewInterfaceInfo> { private static final String STATE_STRATEGY_TYPE_ANNOTATION = StateStrategyType.class.getName(); private static final TypeElement DEFAULT_STATE_STRATEGY = MvpCompiler.getElementUtils().getTypeElement(AddToEndStrategy.class.getCanonicalName()); private String viewClassName; private Set<TypeElement> usedStrategies = new HashSet<>(); public List<TypeElement> getUsedStrategies() { return new ArrayList<>(usedStrategies); } @Override public ViewInterfaceInfo process(TypeElement element) { viewClassName = element.getSimpleName().toString(); List<ViewMethod> methods = new ArrayList<>(); TypeElement interfaceStateStrategyType = getInterfaceStateStrategyType(element); // Get methods for input class getMethods(element, interfaceStateStrategyType, new ArrayList<>(), methods); // Add methods from super interfaces methods.addAll(iterateInterfaces(0, element, interfaceStateStrategyType, methods, new ArrayList<>())); // Allow methods be with same names Map<String, Integer> methodsCounter = new HashMap<>(); for (ViewMethod method : methods) { Integer counter = methodsCounter.get(method.getName()); if (counter != null && counter > 0) { method.setUniqueSuffix(String.valueOf(counter)); } else { counter = 0; } counter++; methodsCounter.put(method.getName(), counter); } return new ViewInterfaceInfo(element, methods); } private void getMethods(TypeElement typeElement, TypeElement defaultStrategy, List<ViewMethod> rootMethods, List<ViewMethod> superinterfacesMethods) { for (Element element : typeElement.getEnclosedElements()) { // ignore all but non-static methods if (element.getKind() != ElementKind.METHOD || element.getModifiers().contains(Modifier.STATIC)) { continue; } final ExecutableElement methodElement = (ExecutableElement) element; if (methodElement.getReturnType().getKind() != TypeKind.VOID) { String message = String.format("You are trying generate ViewState for %s. " + "But %s contains non-void method \"%s\" that return type is %s. " + "See more here: path_to_url", typeElement.getSimpleName(), typeElement.getSimpleName(), methodElement.getSimpleName(), methodElement.getReturnType() ); MvpCompiler.getMessager().printMessage(Diagnostic.Kind.ERROR, message); } AnnotationMirror annotation = Util.getAnnotation(methodElement, STATE_STRATEGY_TYPE_ANNOTATION); // get strategy from annotation TypeMirror strategyClassFromAnnotation = Util.getAnnotationValueAsTypeMirror(annotation, "value"); TypeElement strategyClass; if (strategyClassFromAnnotation != null) { strategyClass = (TypeElement) ((DeclaredType) strategyClassFromAnnotation).asElement(); } else { strategyClass = defaultStrategy != null ? defaultStrategy : DEFAULT_STATE_STRATEGY; } // get tag from annotation String tagFromAnnotation = Util.getAnnotationValueAsString(annotation, "tag"); String methodTag; if (tagFromAnnotation != null) { methodTag = tagFromAnnotation; } else { methodTag = methodElement.getSimpleName().toString(); } // add strategy to list usedStrategies.add(strategyClass); final ViewMethod method = new ViewMethod(methodElement, strategyClass, methodTag); if (rootMethods.contains(method)) { continue; } if (superinterfacesMethods.contains(method)) { checkStrategyAndTagEquals(method, superinterfacesMethods.get(superinterfacesMethods.indexOf(method))); continue; } superinterfacesMethods.add(method); } } private void checkStrategyAndTagEquals(ViewMethod method, ViewMethod existingMethod) { List<String> differentParts = new ArrayList<>(); if (!existingMethod.getStrategy().equals(method.getStrategy())) { differentParts.add("strategies"); } if (!existingMethod.getTag().equals(method.getTag())) { differentParts.add("tags"); } if (!differentParts.isEmpty()) { String arguments = method.getParameterSpecs().stream() .map(ParameterSpec::toString) .collect(Collectors.joining(", ")); String parts = differentParts.stream().collect(Collectors.joining(" and ")); throw new IllegalStateException("Both " + existingMethod.getEnclosedClassName() + " and " + method.getEnclosedClassName() + " has method " + method.getName() + "(" + arguments + ")" + " with different " + parts + "." + " Override this method in " + viewClassName + " or make " + parts + " equals"); } } private List<ViewMethod> iterateInterfaces(int level, TypeElement parentElement, TypeElement parentDefaultStrategy, List<ViewMethod> rootMethods, List<ViewMethod> superinterfacesMethods) { for (TypeMirror typeMirror : parentElement.getInterfaces()) { final TypeElement anInterface = (TypeElement) ((DeclaredType) typeMirror).asElement(); final List<? extends TypeMirror> typeArguments = ((DeclaredType) typeMirror).getTypeArguments(); final List<? extends TypeParameterElement> typeParameters = anInterface.getTypeParameters(); if (typeArguments.size() > typeParameters.size()) { throw new IllegalArgumentException("Code generation for interface " + anInterface.getSimpleName() + " failed. Simplify your generics."); } TypeElement defaultStrategy = parentDefaultStrategy != null ? parentDefaultStrategy : getInterfaceStateStrategyType(anInterface); getMethods(anInterface, defaultStrategy, rootMethods, superinterfacesMethods); iterateInterfaces(level + 1, anInterface, defaultStrategy, rootMethods, superinterfacesMethods); } return superinterfacesMethods; } private TypeElement getInterfaceStateStrategyType(TypeElement typeElement) { AnnotationMirror annotation = Util.getAnnotation(typeElement, STATE_STRATEGY_TYPE_ANNOTATION); TypeMirror value = Util.getAnnotationValueAsTypeMirror(annotation, "value"); if (value != null && value.getKind() == TypeKind.DECLARED) { return (TypeElement) ((DeclaredType) value).asElement(); } else { return null; } } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/viewstate/ViewInterfaceProcessor.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
1,579
```java package com.arellomobile.mvp.compiler.presenterbinder; import com.arellomobile.mvp.MvpPresenter; import com.arellomobile.mvp.MvpProcessor; import com.arellomobile.mvp.PresenterBinder; import com.arellomobile.mvp.compiler.JavaFilesGenerator; import com.arellomobile.mvp.compiler.Util; import com.arellomobile.mvp.presenter.PresenterField; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; /** * 18.12.2015 * <p> * Generates PresenterBinder for class annotated with &#64;InjectPresenters * <p> * for Sample class with single injected presenter * <pre> * {@code * * &#64;InjectPresenters * public class Sample extends MvpActivity implements MyView * { * * &#64;InjectPresenter(type = PresenterType.LOCAL, tag = "SOME_TAG") * com.arellomobile.example.MyPresenter mMyPresenter; * * } * * } * </pre> * <p> * PresenterBinderClassGenerator generates PresenterBinder * <p> * * @author Yuri Shmakov * @author Alexander Blinov */ public final class PresenterBinderClassGenerator extends JavaFilesGenerator<TargetClassInfo> { @Override public List<JavaFile> generate(TargetClassInfo targetClassInfo) { ClassName targetClassName = targetClassInfo.getName(); List<TargetPresenterField> fields = targetClassInfo.getFields(); final String containerSimpleName = String.join("$", targetClassName.simpleNames()); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(containerSimpleName + MvpProcessor.PRESENTER_BINDER_SUFFIX) .addModifiers(Modifier.PUBLIC) .superclass(ParameterizedTypeName.get(ClassName.get(PresenterBinder.class), targetClassName)); for (TargetPresenterField field : fields) { classBuilder.addType(generatePresenterBinderClass(field, targetClassName)); } classBuilder.addMethod(generateGetPresentersMethod(fields, targetClassName)); JavaFile javaFile = JavaFile.builder(targetClassName.packageName(), classBuilder.build()) .indent("\t") .build(); return Collections.singletonList(javaFile); } private static MethodSpec generateGetPresentersMethod(List<TargetPresenterField> fields, ClassName containerClassName) { MethodSpec.Builder builder = MethodSpec.methodBuilder("getPresenterFields") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ParameterizedTypeName.get( ClassName.get(List.class), ParameterizedTypeName.get( ClassName.get(PresenterField.class), containerClassName))); builder.addStatement("$T<$T<$T>> presenters = new $T<>($L)", List.class, PresenterField.class, containerClassName, ArrayList.class, fields.size()); for (TargetPresenterField field : fields) { builder.addStatement("presenters.add(new $L())", field.getGeneratedClassName()); } builder.addStatement("return presenters"); return builder.build(); } private static TypeSpec generatePresenterBinderClass(TargetPresenterField field, ClassName targetClassName) { String tag = field.getTag(); if (tag == null) tag = field.getName(); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(field.getGeneratedClassName()) .addModifiers(Modifier.PUBLIC) .superclass(ParameterizedTypeName.get( ClassName.get(PresenterField.class), targetClassName)) .addMethod(generatePresenterBinderConstructor(field, tag)) .addMethod(generateBindMethod(field, targetClassName)) .addMethod(generateProvidePresenterMethod(field, targetClassName)); String tagProviderMethodName = field.getPresenterTagProviderMethodName(); if (tagProviderMethodName != null) { classBuilder.addMethod(generateGetTagMethod(tagProviderMethodName, targetClassName)); } return classBuilder.build(); } private static MethodSpec generatePresenterBinderConstructor(TargetPresenterField field, String tag) { return MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addStatement("super($S, $T.$L, $S, $T.class)", tag, field.getPresenterType().getDeclaringClass(), field.getPresenterType().name(), field.getPresenterId(), field.getTypeName()) .build(); } private static MethodSpec generateBindMethod(TargetPresenterField field, ClassName targetClassName) { return MethodSpec.methodBuilder("bind") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(targetClassName, "target") .addParameter(MvpPresenter.class, "presenter") .addStatement("target.$L = ($T) presenter", field.getName(), field.getTypeName()) .build(); } private static MethodSpec generateProvidePresenterMethod(TargetPresenterField field, ClassName targetClassName) { MethodSpec.Builder builder = MethodSpec.methodBuilder("providePresenter") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ParameterizedTypeName.get( ClassName.get(MvpPresenter.class), WildcardTypeName.subtypeOf(Object.class))) .addParameter(targetClassName, "delegated"); if (field.getPresenterProviderMethodName() != null) { builder.addStatement("return delegated.$L()", field.getPresenterProviderMethodName()); } else { boolean hasEmptyConstructor = Util.hasEmptyConstructor((TypeElement) ((DeclaredType) field.getClazz()).asElement()); if (hasEmptyConstructor) { builder.addStatement("return new $T()", field.getTypeName()); } else { builder.addStatement( "throw new $T($S + $S)", IllegalStateException.class, field.getClazz(), " has not default constructor. You can apply @ProvidePresenter to some method which will construct Presenter. Also you can make it default constructor"); } } return builder.build(); } private static MethodSpec generateGetTagMethod(String tagProviderMethodName, ClassName targetClassName) { return MethodSpec.methodBuilder("getTag") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addParameter(targetClassName, "delegated") .addStatement("return String.valueOf(delegated.$L())", tagProviderMethodName) .build(); } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/presenterbinder/PresenterBinderClassGenerator.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
1,416
```java package com.arellomobile.mvp.compiler.presenterbinder; import com.arellomobile.mvp.presenter.PresenterType; import javax.lang.model.type.TypeMirror; class TagProviderMethod { private final TypeMirror presenterClass; private final String methodName; private final PresenterType type; private final String presenterId; TagProviderMethod(TypeMirror presenterClass, String methodName, String type, String presenterId) { this.presenterClass = presenterClass; this.methodName = methodName; if (type == null) { this.type = PresenterType.LOCAL; } else { this.type = PresenterType.valueOf(type); } this.presenterId = presenterId; } TypeMirror getPresenterClass() { return presenterClass; } String getMethodName() { return methodName; } PresenterType getType() { return type; } String getPresenterId() { return presenterId; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/presenterbinder/TagProviderMethod.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
192
```java package com.arellomobile.mvp.compiler.presenterbinder; import com.arellomobile.mvp.compiler.ElementProcessor; import com.arellomobile.mvp.compiler.Util; import com.arellomobile.mvp.presenter.InjectPresenter; import com.arellomobile.mvp.presenter.ProvidePresenter; import com.arellomobile.mvp.presenter.ProvidePresenterTag; import java.util.ArrayList; import java.util.List; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; public class InjectPresenterProcessor extends ElementProcessor<VariableElement, TargetClassInfo> { private static final String PRESENTER_FIELD_ANNOTATION = InjectPresenter.class.getName(); private static final String PROVIDE_PRESENTER_ANNOTATION = ProvidePresenter.class.getName(); private static final String PROVIDE_PRESENTER_TAG_ANNOTATION = ProvidePresenterTag.class.getName(); private final List<TypeElement> presentersContainers = new ArrayList<>(); public List<TypeElement> getPresentersContainers() { return new ArrayList<>(presentersContainers); } @Override public TargetClassInfo process(VariableElement variableElement) { final Element enclosingElement = variableElement.getEnclosingElement(); if (!(enclosingElement instanceof TypeElement)) { throw new RuntimeException("Only class fields could be annotated as @InjectPresenter: " + variableElement + " at " + enclosingElement); } if (presentersContainers.contains(enclosingElement)) { return null; } final TypeElement presentersContainer = (TypeElement) enclosingElement; presentersContainers.add(presentersContainer); // gather presenter fields info List<TargetPresenterField> fields = collectFields(presentersContainer); bindProvidersToFields(fields, collectPresenterProviders(presentersContainer)); bindTagProvidersToFields(fields, collectTagProviders(presentersContainer)); return new TargetClassInfo(presentersContainer, fields); } private static List<TargetPresenterField> collectFields(TypeElement presentersContainer) { List<TargetPresenterField> fields = new ArrayList<>(); for (Element element : presentersContainer.getEnclosedElements()) { if (element.getKind() != ElementKind.FIELD) { continue; } AnnotationMirror annotation = Util.getAnnotation(element, PRESENTER_FIELD_ANNOTATION); if (annotation == null) { continue; } // TODO: simplify? TypeMirror clazz = ((DeclaredType) element.asType()).asElement().asType(); String name = element.toString(); String type = Util.getAnnotationValueAsString(annotation, "type"); String tag = Util.getAnnotationValueAsString(annotation, "tag"); String presenterId = Util.getAnnotationValueAsString(annotation, "presenterId"); TargetPresenterField field = new TargetPresenterField(clazz, name, type, tag, presenterId); fields.add(field); } return fields; } private static List<PresenterProviderMethod> collectPresenterProviders(TypeElement presentersContainer) { List<PresenterProviderMethod> providers = new ArrayList<>(); for (Element element : presentersContainer.getEnclosedElements()) { if (element.getKind() != ElementKind.METHOD) { continue; } final ExecutableElement providerMethod = (ExecutableElement) element; final AnnotationMirror annotation = Util.getAnnotation(element, PROVIDE_PRESENTER_ANNOTATION); if (annotation == null) { continue; } final String name = providerMethod.getSimpleName().toString(); final DeclaredType kind = ((DeclaredType) providerMethod.getReturnType()); String type = Util.getAnnotationValueAsString(annotation, "type"); String tag = Util.getAnnotationValueAsString(annotation, "tag"); String presenterId = Util.getAnnotationValueAsString(annotation, "presenterId"); providers.add(new PresenterProviderMethod(kind, name, type, tag, presenterId)); } return providers; } private static List<TagProviderMethod> collectTagProviders(TypeElement presentersContainer) { List<TagProviderMethod> providers = new ArrayList<>(); for (Element element : presentersContainer.getEnclosedElements()) { if (element.getKind() != ElementKind.METHOD) { continue; } final ExecutableElement providerMethod = (ExecutableElement) element; final AnnotationMirror annotation = Util.getAnnotation(element, PROVIDE_PRESENTER_TAG_ANNOTATION); if (annotation == null) { continue; } final String name = providerMethod.getSimpleName().toString(); TypeMirror presenterClass = Util.getAnnotationValueAsTypeMirror(annotation, "presenterClass"); String type = Util.getAnnotationValueAsString(annotation, "type"); String presenterId = Util.getAnnotationValueAsString(annotation, "presenterId"); providers.add(new TagProviderMethod(presenterClass, name, type, presenterId)); } return providers; } private static void bindProvidersToFields(List<TargetPresenterField> fields, List<PresenterProviderMethod> presenterProviders) { if (fields.isEmpty() || presenterProviders.isEmpty()) { return; } for (PresenterProviderMethod presenterProvider : presenterProviders) { TypeMirror providerTypeMirror = presenterProvider.getClazz().asElement().asType(); for (TargetPresenterField field : fields) { if ((field.getClazz()).equals(providerTypeMirror)) { if (field.getPresenterType() != presenterProvider.getPresenterType()) { continue; } if (field.getTag() == null && presenterProvider.getTag() != null) { continue; } if (field.getTag() != null && !field.getTag().equals(presenterProvider.getTag())) { continue; } if (field.getPresenterId() == null && presenterProvider.getPresenterId() != null) { continue; } if (field.getPresenterId() != null && !field.getPresenterId().equals(presenterProvider.getPresenterId())) { continue; } field.setPresenterProviderMethodName(presenterProvider.getName()); } } } } private static void bindTagProvidersToFields(List<TargetPresenterField> fields, List<TagProviderMethod> tagProviders) { if (fields.isEmpty() || tagProviders.isEmpty()) { return; } for (TagProviderMethod tagProvider : tagProviders) { for (TargetPresenterField field : fields) { if ((field.getClazz()).equals(tagProvider.getPresenterClass())) { if (field.getPresenterType() != tagProvider.getType()) { continue; } if (field.getPresenterId() == null && tagProvider.getPresenterId() != null) { continue; } if (field.getPresenterId() != null && !field.getPresenterId().equals(tagProvider.getPresenterId())) { continue; } field.setPresenterTagProviderMethodName(tagProvider.getMethodName()); } } } } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/presenterbinder/InjectPresenterProcessor.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
1,504
```java package com.arellomobile.mvp.compiler.presenterbinder; import com.squareup.javapoet.ClassName; import java.util.List; import javax.lang.model.element.TypeElement; class TargetClassInfo { private final ClassName name; private final List<TargetPresenterField> fields; TargetClassInfo(TypeElement name, List<TargetPresenterField> fields) { this.name = ClassName.get(name); this.fields = fields; } ClassName getName() { return name; } List<TargetPresenterField> getFields() { return fields; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/presenterbinder/TargetClassInfo.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
116
```java package com.arellomobile.mvp.compiler.viewstateprovider; import com.arellomobile.mvp.MvpProcessor; import com.arellomobile.mvp.MvpView; import com.arellomobile.mvp.ViewStateProvider; import com.arellomobile.mvp.compiler.JavaFilesGenerator; import com.arellomobile.mvp.viewstate.MvpViewState; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.Collections; import java.util.List; import javax.lang.model.element.Modifier; /** * Date: 19-Jan-16 * Time: 19:51 * * @author Alexander Blinov */ public final class ViewStateProviderClassGenerator extends JavaFilesGenerator<PresenterInfo> { @Override public List<JavaFile> generate(PresenterInfo presenterInfo) { TypeSpec typeSpec = TypeSpec.classBuilder(presenterInfo.getName().simpleName() + MvpProcessor.VIEW_STATE_PROVIDER_SUFFIX) .addModifiers(Modifier.PUBLIC) .superclass(ViewStateProvider.class) .addMethod(generateGetViewStateMethod(presenterInfo.getName(), presenterInfo.getViewStateName())) .build(); JavaFile javaFile = JavaFile.builder(presenterInfo.getName().packageName(), typeSpec) .indent("\t") .build(); return Collections.singletonList(javaFile); } private MethodSpec generateGetViewStateMethod(ClassName presenter, ClassName viewState) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getViewState") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(ParameterizedTypeName.get(ClassName.get(MvpViewState.class), WildcardTypeName.subtypeOf(MvpView.class))); if (viewState == null) { methodBuilder.addStatement("throw new RuntimeException($S)", presenter.reflectionName() + " should has view"); } else { methodBuilder.addStatement("return new $T()", viewState); } return methodBuilder.build(); } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/viewstateprovider/ViewStateProviderClassGenerator.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
454
```java package com.arellomobile.mvp.compiler.viewstateprovider; import com.squareup.javapoet.ClassName; import javax.lang.model.element.TypeElement; /** * Date: 27-Jul-2017 * Time: 11:55 * * @author Evgeny Kursakov */ class PresenterInfo { private final ClassName name; private final ClassName viewStateName; PresenterInfo(TypeElement name, String viewStateName) { this.name = ClassName.get(name); this.viewStateName = ClassName.bestGuess(viewStateName); } ClassName getName() { return name; } ClassName getViewStateName() { return viewStateName; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/viewstateprovider/PresenterInfo.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
140
```java package com.arellomobile.mvp.compiler.viewstateprovider; import com.arellomobile.mvp.DefaultView; import com.arellomobile.mvp.DefaultViewState; import com.arellomobile.mvp.InjectViewState; import com.arellomobile.mvp.MvpPresenter; import com.arellomobile.mvp.MvpProcessor; import com.arellomobile.mvp.compiler.ElementProcessor; import com.arellomobile.mvp.compiler.MvpCompiler; import com.arellomobile.mvp.compiler.Util; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic; import static com.arellomobile.mvp.compiler.Util.fillGenerics; public class InjectViewStateProcessor extends ElementProcessor<TypeElement, PresenterInfo> { private static final String MVP_PRESENTER_CLASS = MvpPresenter.class.getCanonicalName(); private final Set<TypeElement> usedViews = new HashSet<>(); private final List<TypeElement> presenterClassNames = new ArrayList<>(); public Set<TypeElement> getUsedViews() { return usedViews; } public List<TypeElement> getPresenterClassNames() { return presenterClassNames; } @Override public PresenterInfo process(TypeElement element) { presenterClassNames.add(element); return new PresenterInfo(element, getViewStateClassName(element)); } private String getViewStateClassName(TypeElement typeElement) { String viewState = getViewStateClassFromAnnotationParams(typeElement); if (viewState == null) { String view = getViewClassFromAnnotationParams(typeElement); if (view == null) { view = getViewClassFromGeneric(typeElement); } if (view != null) { // Remove generic from view class name if (view.contains("<")) { view = view.substring(0, view.indexOf("<")); } TypeElement viewTypeElement = MvpCompiler.getElementUtils().getTypeElement(view); if (viewTypeElement == null) { throw new IllegalArgumentException("View \"" + view + "\" for " + typeElement + " cannot be found"); } usedViews.add(viewTypeElement); viewState = Util.getFullClassName(viewTypeElement) + MvpProcessor.VIEW_STATE_SUFFIX; } } if (viewState != null) { return viewState; } else { return null; } } private String getViewClassFromAnnotationParams(TypeElement typeElement) { InjectViewState annotation = typeElement.getAnnotation(InjectViewState.class); String mvpViewClassName = ""; if (annotation != null) { TypeMirror value = null; try { annotation.view(); } catch (MirroredTypeException mte) { value = mte.getTypeMirror(); } mvpViewClassName = Util.getFullClassName(value); } if (mvpViewClassName.isEmpty() || DefaultView.class.getName().equals(mvpViewClassName)) { return null; } return mvpViewClassName; } private String getViewStateClassFromAnnotationParams(TypeElement typeElement) { InjectViewState annotation = typeElement.getAnnotation(InjectViewState.class); String mvpViewStateClassName = ""; if (annotation != null) { TypeMirror value; try { annotation.value(); } catch (MirroredTypeException mte) { value = mte.getTypeMirror(); mvpViewStateClassName = value.toString(); } } if (mvpViewStateClassName.isEmpty() || DefaultViewState.class.getName().equals(mvpViewStateClassName)) { return null; } return mvpViewStateClassName; } private String getViewClassFromGeneric(TypeElement typeElement) { TypeMirror superclass = typeElement.asType(); Map<String, String> parentTypes = Collections.emptyMap(); if (!typeElement.getTypeParameters().isEmpty()) { MvpCompiler.getMessager().printMessage(Diagnostic.Kind.WARNING, "Your " + typeElement.getSimpleName() + " is typed. @InjectViewState may generate wrong code. Your can set view/view state class manually."); } while (superclass.getKind() != TypeKind.NONE) { TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement(); final List<? extends TypeMirror> typeArguments = ((DeclaredType) superclass).getTypeArguments(); final List<? extends TypeParameterElement> typeParameters = superclassElement.getTypeParameters(); if (typeArguments.size() > typeParameters.size()) { throw new IllegalArgumentException("Code generation for interface " + typeElement.getSimpleName() + " failed. Simplify your generics. (" + typeArguments + " vs " + typeParameters + ")"); } Map<String, String> types = new HashMap<>(); for (int i = 0; i < typeArguments.size(); i++) { types.put(typeParameters.get(i).toString(), fillGenerics(parentTypes, typeArguments.get(i))); } if (superclassElement.toString().equals(MVP_PRESENTER_CLASS)) { // MvpPresenter is typed only on View class return fillGenerics(parentTypes, typeArguments); } parentTypes = types; superclass = superclassElement.getSuperclass(); } return ""; } } ```
/content/code_sandbox/moxy-compiler/src/main/java/com/arellomobile/mvp/compiler/viewstateprovider/InjectViewStateProcessor.java
java
2016-02-12T08:35:25
2024-07-28T20:03:03
Moxy
Arello-Mobile/Moxy
1,609
1,165
```javascript var Please = require('pleasejs') var div = document.getElementById('color') var button = document.getElementById('button') function changeColor() { div.style.backgroundColor = Please.make_color() console.log('pls do work') } button.addEventListener('click', changeColor) ```
/content/code_sandbox/ko-arahansa/part1/css-extract/src/changeColor.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
56
```javascript /* eslint no-var: 0 */ var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { devtool: 'source-map', entry: ['./src/index'], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, }, }), new webpack.optimize.OccurrenceOrderPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }) ], module: { loaders: [{ test: /\.css$/, loaders: ['style', 'css'] }, { test: /\.js$/, loaders: ['babel'], include: path.join(__dirname, 'src') }] } } ```
/content/code_sandbox/ko-arahansa/part2/example1/webpack.config.prod.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
203
```javascript var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { devtool: 'cheap-eval-source-map', entry: [ 'webpack-dev-server/client?path_to_url 'webpack/hot/dev-server', './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }) ], module: { loaders: [{ test: /\.css$/, loaders: ['style', 'css'] }] }, devServer: { contentBase: './dist', hot: true } } ```
/content/code_sandbox/ko-arahansa/part1/css-extract/webpack.config.dev.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
169
```javascript import Please from 'pleasejs' // use es6 module import require('./styles.css') // The page is now styled // Accept hot module reloading during development if (process.env.NODE_ENV !== 'production') { if (module.hot) { module.hot.accept() } } const div = document.getElementById('color') const button = document.getElementById('button') const changeColor = () => div.style.backgroundColor = Please.make_color() button.addEventListener('click', changeColor) ```
/content/code_sandbox/ko-arahansa/part2/example1/src/index.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
99
```javascript /* eslint no-var: 0 */ var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { devtool: 'cheap-eval-source-map', entry: [ 'webpack-dev-server/client?path_to_url 'webpack/hot/dev-server', './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }) ], module: { loaders: [{ test: /\.css$/, loaders: ['style', 'css'] }, { test: /\.js$/, loaders: ['babel'], include: path.join(__dirname, 'src') }] }, devServer: { contentBase: './dist', hot: true } } ```
/content/code_sandbox/ko-arahansa/part2/example1/webpack.config.dev.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
203
```html <html> <head> <title>Webpack Tutorial</title> </head> <body> <h1>Very Website</h1> <section id="color"></section> <button id="button">Such Button</button> </body> </html> ```
/content/code_sandbox/ko-arahansa/part1/css-extract/src/index.html
html
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
58
```css h1 { color: rgb(114, 191, 190); text-align: center; } #color { width: 300px; height: 300px; margin: 0 auto; } button { cursor: pointer; display: block; width: 100px; outline: 0; border: 0; margin: 20px auto; } ```
/content/code_sandbox/ko-arahansa/part1/css-extract/src/styles.css
css
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
89
```javascript var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { devtool: 'source-map', entry: ['./src/index'], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, }, }), new webpack.optimize.OccurrenceOrderPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }), new ExtractTextPlugin("styles.css") ], module: { loaders: [{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }] } } ```
/content/code_sandbox/ko-arahansa/part1/css-extract/webpack.config.prod.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
175
```javascript require('./styles.css') require('./changeColor.js') ```
/content/code_sandbox/ko-arahansa/part1/css-extract/src/index.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
12
```javascript var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { devtool: 'cheap-eval-source-map', entry: [ 'webpack-dev-server/client?path_to_url 'webpack/hot/dev-server', './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }) ], module: { loaders: [{ test: /\.css$/, loaders: ['style', 'css'] }, { test: /\.html$/, loader: "raw-loader" // loaders: ['raw-loader'] is also perfectly acceptable. }] }, devServer: { contentBase: './dist', hot: true } } ```
/content/code_sandbox/ko-arahansa/part1/html-reload/webpack.config.dev.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
197
```javascript if (process.env.NODE_ENV !== 'production') { require('./index.html') } ```
/content/code_sandbox/ko-arahansa/part1/html-reload/src/index.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
19
```css h1 { color: rgb(114, 191, 190); } #color { width: 300px; height: 300px; margin: 0 auto; } button { cursor: pointer; display: inline-block; height: 20px; background-color: rgb(123, 109, 198); color: rgb(255, 255, 255); padding: 10px 5px; border-radius: 4px; border-bottom: 2px solid rgb(143, 132, 200); } ```
/content/code_sandbox/ko-arahansa/part1/html-reload/src/styles.css
css
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
127
```html <html> <head> <title>Webpack Tutorial</title> </head> <body> <h1>Very Website</h1> <section id="color"></section> <button id="button">Such Button</button> </body> </html> ```
/content/code_sandbox/ko-arahansa/part1/html-reload/src/index.html
html
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
57
```javascript var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { devtool: 'source-map', entry: ['./src/index'], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, }, }), new webpack.optimize.OccurrenceOrderPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }) ], module: { loaders: [{ test: /\.css$/, loaders: ['style', 'css'] }] } } ```
/content/code_sandbox/ko-arahansa/part1/example7/webpack.config.prod.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
148
```javascript var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { devtool: 'source-map', entry: ['./src/index'], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, }, }), new webpack.optimize.OccurrenceOrderPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }) ], module: { loaders: [{ test: /\.css$/, loaders: ['style', 'css'] }] } } ```
/content/code_sandbox/ko-arahansa/part1/html-reload/webpack.config.prod.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
169
```javascript // Accept hot module reloading if (module.hot) { module.hot.accept() } require('./styles.css') // The page is now styled var Please = require('pleasejs') var div = document.getElementById('color') var button = document.getElementById('button') function changeColor() { div.style.backgroundColor = Please.make_color() console.log('HMR works no') } button.addEventListener('click', changeColor) ```
/content/code_sandbox/ko-arahansa/part1/example7/src/index.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
87
```javascript require('./styles.css') require('./UIStuff.js') require('./APIStuff.js') ```
/content/code_sandbox/ko-arahansa/part1/example1/src/index.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
18
```javascript var path = require('path') var webpack = require('webpack') module.exports = { entry: ['./src/index'], // .js after index is optional output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, }, }), new webpack.optimize.OccurrenceOrderPlugin() ], module: { loaders: [{ test: /\.css$/, loaders: ['style', 'css'] }] } } ```
/content/code_sandbox/ko-arahansa/part1/example1/webpack.config.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
125
```css body { background-color: rgb(200, 56, 97); } ```
/content/code_sandbox/ko-arahansa/part1/example1/src/styles.css
css
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
18
```javascript var React = require('React') React.createClass({ // stuff }) ```
/content/code_sandbox/ko-arahansa/part1/example1/src/UIStuff.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
16
```javascript console.log('No one likes me') ```
/content/code_sandbox/ko-arahansa/part1/example1/src/extraFile.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
9
```javascript var fetch = require('fetch') // fetch polyfill fetch('path_to_url ```
/content/code_sandbox/ko-arahansa/part1/example1/src/APIStuff.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
19
```javascript console.log('It works!') ```
/content/code_sandbox/ko-arahansa/part1/example3/src/index.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
7
```javascript var path = require('path') var webpack = require('webpack') module.exports = { entry: ['./src/index'], // .js after index is optional output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, }, }), new webpack.optimize.OccurrenceOrderPlugin() ] } ```
/content/code_sandbox/ko-arahansa/part1/example3/webpack.config.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
98
```javascript var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: ['./src/index'], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, }, }), new webpack.optimize.OccurrenceOrderPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }) ], module: { loaders: [{ test: /\.css$/, loaders: ['style', 'css'] }] } } ```
/content/code_sandbox/ko-arahansa/part1/example5/webpack.config.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
140
```javascript var path = require('path') module.exports = { entry: ['./src/index'], // .js after index is optional output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' } } ```
/content/code_sandbox/ko-arahansa/part1/example2/webpack.config.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
52
```html <html> <head> <title>Webpack Tutorial</title> </head> <body> <h1>Very Website</h1> <section id="color"></section> <button id="button">Such Button</button> </body> </html> ```
/content/code_sandbox/ko-arahansa/part1/example5/src/index.html
html
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
58
```javascript console.log('hello there my friends') ```
/content/code_sandbox/ko-arahansa/part1/example6/src/index.js
javascript
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
9
```css ```
/content/code_sandbox/ko-arahansa/part1/example4/src/styles.css
css
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
1
```html ```
/content/code_sandbox/ko-arahansa/part1/example4/src/index.html
html
2016-02-03T19:46:42
2024-08-12T10:51:48
WebpackTutorial
AriaFallah/WebpackTutorial
2,231
1
```qmake # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/ashokvarma/Library/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 *; #} ```
/content/code_sandbox/bottom-navigation-bar/proguard-rules.pro
qmake
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
143
```gradle apply plugin: 'com.jfrog.bintray' // from path_to_url version = libraryVersion if (project.hasProperty("android")) { // Android libraries task sourcesJar(type: Jar) { classifier = 'sources' from android.sourceSets.main.java.srcDirs } task javadoc(type: Javadoc) { source = android.sourceSets.main.java.srcDirs classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) } } else { // Java libraries task sourcesJar(type: Jar, dependsOn: classes) { classifier = 'sources' from sourceSets.main.allSource } } task javadocJar(type: Jar, dependsOn: javadoc) { classifier = 'javadoc' from javadoc.destinationDir } artifacts { archives javadocJar archives sourcesJar } // Bintray Properties properties = new Properties() def defUser = System.env.gradlePublishUser def defKey = System.env.gradlePublishKey def defSecret = System.env.gradlePublishSecret if (!defKey || !defUser || !defSecret) { // This is for local build properties.load(project.rootProject.file('local.properties').newDataInputStream()) } else { // This is for remote build set System Properties in travis system properties.setProperty("bintray.user", defUser) properties.setProperty("bintray.apikey", defKey) properties.setProperty("bintray.gpg.password", defSecret) } bintray { // Properties properties = new Properties() // properties.load(project.rootProject.file('local.properties').newDataInputStream()) user = properties.getProperty("bintray.user") key = properties.getProperty("bintray.apikey") configurations = ['archives'] pkg { repo = bintrayRepo name = bintrayName desc = libraryDescription websiteUrl = siteUrl vcsUrl = gitUrl publish = true publicDownloadNumbers = true version { desc = libraryDescription gpg { sign = true //Determines whether to GPG sign the files. The default is false passphrase = properties.getProperty("bintray.gpg.password") //Optional. The passphrase for GPG signing' } } } } ```
/content/code_sandbox/bottom-navigation-bar/bintray_lib.gradle
gradle
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
498
```gradle apply plugin: 'com.github.dcendents.android-maven' // from path_to_url group = publishedGroupId // Maven Group ID for the artifact install { repositories.mavenInstaller { // This generates POM.xml with proper parameters pom { project { packaging 'aar' groupId publishedGroupId artifactId artifact // Add your description here name libraryName description libraryDescription url siteUrl // Set your license licenses { license { name licenseName url licenseUrl } } developers { developer { id developerId name developerName email developerEmail } } scm { connection gitUrl developerConnection gitUrl url siteUrl } } } } } ```
/content/code_sandbox/bottom-navigation-bar/install_lib.gradle
gradle
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
173
```java package com.ashokvarma.bottomnavigation; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.view.ViewAnimationUtils; import com.ashokvarma.bottomnavigation.utils.Utils; /** * Class description : This is utils class specific for this library, most the common code goes here. * * @author ashokvarma * @version 1.0 * @since 19 Mar 2016 */ class BottomNavigationHelper { private BottomNavigationHelper() { } /** * Used to get Measurements for MODE_FIXED * * @param context to fetch measurements * @param screenWidth total screen width * @param noOfTabs no of bottom bar tabs * @param scrollable is bottom bar scrollable * @return width of each tab */ static int[] getMeasurementsForFixedMode(Context context, int screenWidth, int noOfTabs, boolean scrollable) { int[] result = new int[2]; int minWidth = (int) context.getResources().getDimension(R.dimen.fixed_min_width_small_views); int maxWidth = (int) context.getResources().getDimension(R.dimen.fixed_min_width); int itemWidth = screenWidth / noOfTabs; if (itemWidth < minWidth && scrollable) { itemWidth = (int) context.getResources().getDimension(R.dimen.fixed_min_width); } else if (itemWidth > maxWidth) { itemWidth = maxWidth; } result[0] = itemWidth; return result; } /** * Used to get Measurements for MODE_SHIFTING * * @param context to fetch measurements * @param screenWidth total screen width * @param noOfTabs no of bottom bar tabs * @param scrollable is bottom bar scrollable * @return min and max width of each tab */ static int[] getMeasurementsForShiftingMode(Context context, int screenWidth, int noOfTabs, boolean scrollable) { int[] result = new int[2]; int minWidth = (int) context.getResources().getDimension(R.dimen.shifting_min_width_inactive); int maxWidth = (int) context.getResources().getDimension(R.dimen.shifting_max_width_inactive); double minPossibleWidth = minWidth * (noOfTabs + 0.5); double maxPossibleWidth = maxWidth * (noOfTabs + 0.75); int itemWidth; int itemActiveWidth; if (screenWidth < minPossibleWidth) { if (scrollable) { itemWidth = minWidth; itemActiveWidth = (int) (minWidth * 1.5); } else { itemWidth = (int) (screenWidth / (noOfTabs + 0.5)); itemActiveWidth = (int) (itemWidth * 1.5); } } else if (screenWidth > maxPossibleWidth) { itemWidth = maxWidth; itemActiveWidth = (int) (itemWidth * 1.75); } else { double minPossibleWidth1 = minWidth * (noOfTabs + 0.625); double minPossibleWidth2 = minWidth * (noOfTabs + 0.75); itemWidth = (int) (screenWidth / (noOfTabs + 0.5)); itemActiveWidth = (int) (itemWidth * 1.5); if (screenWidth > minPossibleWidth1) { itemWidth = (int) (screenWidth / (noOfTabs + 0.625)); itemActiveWidth = (int) (itemWidth * 1.625); if (screenWidth > minPossibleWidth2) { itemWidth = (int) (screenWidth / (noOfTabs + 0.75)); itemActiveWidth = (int) (itemWidth * 1.75); } } } result[0] = itemWidth; result[1] = itemActiveWidth; return result; } /** * Used to get set data to the Tab views from navigation items * * @param bottomNavigationItem holds all the data * @param bottomNavigationTab view to which data need to be set * @param bottomNavigationBar view which holds all the tabs */ static void bindTabWithData(BottomNavigationItem bottomNavigationItem, BottomNavigationTab bottomNavigationTab, BottomNavigationBar bottomNavigationBar) { Context context = bottomNavigationBar.getContext(); bottomNavigationTab.setLabel(bottomNavigationItem.getTitle(context)); bottomNavigationTab.setIcon(bottomNavigationItem.getIcon(context)); int activeColor = bottomNavigationItem.getActiveColor(context); int inActiveColor = bottomNavigationItem.getInActiveColor(context); if (activeColor != Utils.NO_COLOR) { bottomNavigationTab.setActiveColor(activeColor); } else { bottomNavigationTab.setActiveColor(bottomNavigationBar.getActiveColor()); } if (inActiveColor != Utils.NO_COLOR) { bottomNavigationTab.setInactiveColor(inActiveColor); } else { bottomNavigationTab.setInactiveColor(bottomNavigationBar.getInActiveColor()); } if (bottomNavigationItem.isInActiveIconAvailable()) { Drawable inactiveDrawable = bottomNavigationItem.getInactiveIcon(context); if (inactiveDrawable != null) { bottomNavigationTab.setInactiveIcon(inactiveDrawable); } } bottomNavigationTab.setItemBackgroundColor(bottomNavigationBar.getBackgroundColor()); BadgeItem badgeItem = bottomNavigationItem.getBadgeItem(); if (badgeItem != null) { badgeItem.bindToBottomTab(bottomNavigationTab); } } /** * Used to set the ripple animation when a tab is selected * * @param clickedView the view that is clicked (to get dimens where ripple starts) * @param backgroundView temporary view to which final background color is set * @param bgOverlay temporary view which is animated to get ripple effect * @param newColor the new color i.e ripple color * @param animationDuration duration for which animation runs */ static void setBackgroundWithRipple(View clickedView, final View backgroundView, final View bgOverlay, final int newColor, int animationDuration) { int centerX = (int) (clickedView.getX() + (clickedView.getMeasuredWidth() / 2)); int centerY = clickedView.getMeasuredHeight() / 2; int finalRadius = backgroundView.getWidth(); backgroundView.clearAnimation(); bgOverlay.clearAnimation(); Animator circularReveal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { circularReveal = ViewAnimationUtils .createCircularReveal(bgOverlay, centerX, centerY, 0, finalRadius); } else { bgOverlay.setAlpha(0); circularReveal = ObjectAnimator.ofFloat(bgOverlay, "alpha", 0, 1); } circularReveal.setDuration(animationDuration); circularReveal.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { onCancel(); } @Override public void onAnimationCancel(Animator animation) { onCancel(); } private void onCancel() { backgroundView.setBackgroundColor(newColor); bgOverlay.setVisibility(View.GONE); } }); bgOverlay.setBackgroundColor(newColor); bgOverlay.setVisibility(View.VISIBLE); circularReveal.start(); } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BottomNavigationHelper.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
1,602
```java package com.ashokvarma.bottomnavigation; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import androidx.appcompat.widget.AppCompatTextView; /** * Class description * * @author ashokvarma * @version 1.0 * @since 23 Jun 2017 */ @SuppressLint("Instantiatable") class BadgeTextView extends AppCompatTextView { private ShapeBadgeItem mShapeBadgeItem; private boolean mAreDimensOverridden; private int mDesiredWidth = 100; private int mDesiredHeight = 100; public BadgeTextView(Context context) { this(context, null); } public BadgeTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BadgeTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { // method stub } /** * clear's all previous set values */ void clearPrevious() { mAreDimensOverridden = false; mShapeBadgeItem = null; } /** * @param shapeBadgeItem that can draw on top of the this view */ void setShapeBadgeItem(ShapeBadgeItem shapeBadgeItem) { mShapeBadgeItem = shapeBadgeItem; } /** * if width and height of the view needs to be changed * * @param width new width that needs to be set * @param height new height that needs to be set */ void setDimens(int width, int height) { mAreDimensOverridden = true; mDesiredWidth = width; mDesiredHeight = height; requestLayout(); } /** * invalidate's view so badgeItem can draw again */ void recallOnDraw() { invalidate(); } /** * {@inheritDoc} */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mShapeBadgeItem != null) { mShapeBadgeItem.draw(canvas); } } /** * {@inheritDoc} */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mAreDimensOverridden) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height; //Measure Width switch (widthMode) { case MeasureSpec.EXACTLY: //Must be this size width = widthSize; break; case MeasureSpec.AT_MOST: //Can't be bigger than... width = Math.min(mDesiredWidth, widthSize); break; case MeasureSpec.UNSPECIFIED: default: //Be whatever you want width = mDesiredWidth; break; } //Measure Height switch (heightMode) { case MeasureSpec.EXACTLY: //Must be this size height = heightSize; break; case MeasureSpec.AT_MOST: //Can't be bigger than... height = Math.min(mDesiredHeight, heightSize); break; case MeasureSpec.UNSPECIFIED: default: //Be whatever you want height = mDesiredHeight; break; } //MUST CALL THIS setMeasuredDimension(width, height); } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BadgeTextView.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
789
```java package com.ashokvarma.bottomnavigation; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.os.Build; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.CallSuper; import androidx.core.graphics.drawable.DrawableCompat; /** * Class description * * @author ashokvarma * @version 1.0 * @see FrameLayout * @since 19 Mar 2016 */ abstract class BottomNavigationTab extends FrameLayout { protected boolean isNoTitleMode; protected int paddingTopActive; protected int paddingTopInActive; protected int mPosition; protected int mActiveColor; protected int mInActiveColor; protected int mBackgroundColor; protected int mActiveWidth; protected int mInActiveWidth; protected Drawable mCompactIcon; protected Drawable mCompactInActiveIcon; protected boolean isInActiveIconSet = false; protected String mLabel; protected BadgeItem badgeItem; boolean isActive = false; View containerView; TextView labelView; ImageView iconView; FrameLayout iconContainerView; BadgeTextView badgeView; public BottomNavigationTab(Context context) { this(context, null); } public BottomNavigationTab(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BottomNavigationTab(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public BottomNavigationTab(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } void init() { setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); } public void setIsNoTitleMode(boolean isNoTitleMode) { this.isNoTitleMode = isNoTitleMode; } public boolean getIsNoTitleMode() { return isNoTitleMode; } public void setActiveWidth(int activeWidth) { mActiveWidth = activeWidth; } public void setInactiveWidth(int inactiveWidth) { mInActiveWidth = inactiveWidth; ViewGroup.LayoutParams params = getLayoutParams(); params.width = mInActiveWidth; setLayoutParams(params); } public void setIcon(Drawable icon) { mCompactIcon = DrawableCompat.wrap(icon); } public void setInactiveIcon(Drawable icon) { mCompactInActiveIcon = DrawableCompat.wrap(icon); isInActiveIconSet = true; } public void setLabel(String label) { mLabel = label; labelView.setText(label); } public void setActiveColor(int activeColor) { mActiveColor = activeColor; } public int getActiveColor() { return mActiveColor; } public void setInactiveColor(int inActiveColor) { mInActiveColor = inActiveColor; labelView.setTextColor(inActiveColor); } public void setItemBackgroundColor(int backgroundColor) { mBackgroundColor = backgroundColor; } public void setPosition(int position) { mPosition = position; } public void setBadgeItem(BadgeItem badgeItem) { this.badgeItem = badgeItem; } public int getPosition() { return mPosition; } public void select(boolean setActiveColor, int animationDuration) { isActive = true; ValueAnimator animator = ValueAnimator.ofInt(containerView.getPaddingTop(), paddingTopActive); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { containerView.setPadding(containerView.getPaddingLeft(), (Integer) valueAnimator.getAnimatedValue(), containerView.getPaddingRight(), containerView.getPaddingBottom()); } }); animator.setDuration(animationDuration); animator.start(); iconView.setSelected(true); if (setActiveColor) { labelView.setTextColor(mActiveColor); } else { labelView.setTextColor(mBackgroundColor); } if (badgeItem != null) { badgeItem.select(); } } public void unSelect(boolean setActiveColor, int animationDuration) { isActive = false; ValueAnimator animator = ValueAnimator.ofInt(containerView.getPaddingTop(), paddingTopInActive); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { containerView.setPadding(containerView.getPaddingLeft(), (Integer) valueAnimator.getAnimatedValue(), containerView.getPaddingRight(), containerView.getPaddingBottom()); } }); animator.setDuration(animationDuration); animator.start(); labelView.setTextColor(mInActiveColor); iconView.setSelected(false); if (badgeItem != null) { badgeItem.unSelect(); } } @CallSuper public void initialise(boolean setActiveColor) { iconView.setSelected(false); if (isInActiveIconSet) { StateListDrawable states = new StateListDrawable(); states.addState(new int[]{android.R.attr.state_selected}, mCompactIcon); states.addState(new int[]{-android.R.attr.state_selected}, mCompactInActiveIcon); states.addState(new int[]{}, mCompactInActiveIcon); iconView.setImageDrawable(states); } else { if (setActiveColor) { DrawableCompat.setTintList(mCompactIcon, new ColorStateList( new int[][]{ new int[]{android.R.attr.state_selected}, //1 new int[]{-android.R.attr.state_selected}, //2 new int[]{} }, new int[]{ mActiveColor, //1 mInActiveColor, //2 mInActiveColor //3 } )); } else { DrawableCompat.setTintList(mCompactIcon, new ColorStateList( new int[][]{ new int[]{android.R.attr.state_selected}, //1 new int[]{-android.R.attr.state_selected}, //2 new int[]{} }, new int[]{ mBackgroundColor, //1 mInActiveColor, //2 mInActiveColor //3 } )); } iconView.setImageDrawable(mCompactIcon); } if (isNoTitleMode) { labelView.setVisibility(GONE); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) iconContainerView.getLayoutParams(); layoutParams.gravity = Gravity.CENTER; setNoTitleIconContainerParams(layoutParams); iconContainerView.setLayoutParams(layoutParams); FrameLayout.LayoutParams iconLayoutParams = (FrameLayout.LayoutParams) iconView.getLayoutParams(); setNoTitleIconParams(iconLayoutParams); iconView.setLayoutParams(iconLayoutParams); } } protected abstract void setNoTitleIconContainerParams(FrameLayout.LayoutParams layoutParams); protected abstract void setNoTitleIconParams(FrameLayout.LayoutParams layoutParams); } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BottomNavigationTab.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
1,500
```java package com.ashokvarma.bottomnavigation; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import androidx.core.view.ViewCompat; import androidx.core.view.ViewPropertyAnimatorCompat; import androidx.core.view.ViewPropertyAnimatorListener; import java.lang.ref.WeakReference; /** * Class description : Holds and manages data for badges * (i.e data structure which holds all data to paint a badge and updates badges when changes are made) * * @author ashokvarma * @version 1.0 * @since 21 Apr 2016 */ abstract class BadgeItem<T extends BadgeItem<T>> { private int mGravity = Gravity.TOP | Gravity.END; private boolean mHideOnSelect; private WeakReference<BadgeTextView> mTextViewRef; private boolean mIsHidden = false; private int mAnimationDuration = 200; /** * @return subClass to allow Builder pattern */ abstract T getSubInstance(); /** * if any extra binding is required binds all badgeItem, BottomNavigationTab and BadgeTextView * * @param bottomNavigationTab to which badgeItem needs to be attached */ abstract void bindToBottomTabInternal(BottomNavigationTab bottomNavigationTab); /////////////////////////////////////////////////////////////////////////// // Public setter methods /////////////////////////////////////////////////////////////////////////// /** * @param gravity gravity of badge (TOP|LEFT ..etc) * @return this, to allow builder pattern */ public T setGravity(int gravity) { this.mGravity = gravity; if (isWeakReferenceValid()) { TextView textView = mTextViewRef.get(); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) textView.getLayoutParams(); layoutParams.gravity = gravity; textView.setLayoutParams(layoutParams); } return getSubInstance(); } /** * @param hideOnSelect if true hides badge on tab selection * @return this, to allow builder pattern */ public T setHideOnSelect(boolean hideOnSelect) { this.mHideOnSelect = hideOnSelect; return getSubInstance(); } /** * @param animationDuration hide and show animation time * @return this, to allow builder pattern */ public T setAnimationDuration(int animationDuration) { this.mAnimationDuration = animationDuration; return getSubInstance(); } /////////////////////////////////////////////////////////////////////////// // Library only access method /////////////////////////////////////////////////////////////////////////// /** * binds all badgeItem, BottomNavigationTab and BadgeTextView * * @param bottomNavigationTab to which badgeItem needs to be attached */ void bindToBottomTab(BottomNavigationTab bottomNavigationTab) { // set initial bindings bottomNavigationTab.badgeView.clearPrevious(); if (bottomNavigationTab.badgeItem != null) { // removing old reference bottomNavigationTab.badgeItem.setTextView(null); } bottomNavigationTab.setBadgeItem(this); setTextView(bottomNavigationTab.badgeView); // allow sub class to modify the things bindToBottomTabInternal(bottomNavigationTab); // make view visible because gone by default bottomNavigationTab.badgeView.setVisibility(View.VISIBLE); // set layout params based on gravity FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) bottomNavigationTab.badgeView.getLayoutParams(); layoutParams.gravity = getGravity(); bottomNavigationTab.badgeView.setLayoutParams(layoutParams); // if hidden hide if (isHidden()) { // if hide is called before the initialisation of bottom-bar this will handle that // by hiding it. hide(); } } /** * Internal method used to update view when ever changes are made * * @param mTextView badge textView * @return this, to allow builder pattern */ private T setTextView(BadgeTextView mTextView) { this.mTextViewRef = new WeakReference<>(mTextView); return getSubInstance(); } /** * @return gravity of badge */ int getGravity() { return mGravity; } /** * @return should hide on selection ? */ boolean isHideOnSelect() { return mHideOnSelect; } /** * @return reference to text-view */ WeakReference<BadgeTextView> getTextView() { return mTextViewRef; } /////////////////////////////////////////////////////////////////////////// // Internal Methods /////////////////////////////////////////////////////////////////////////// /** * @return returns if BadgeTextView's reference is valid */ boolean isWeakReferenceValid() { return mTextViewRef != null && mTextViewRef.get() != null; } /////////////////////////////////////////////////////////////////////////// // Internal call back methods /////////////////////////////////////////////////////////////////////////// /** * callback from bottom navigation tab when it is selected */ void select() { if (mHideOnSelect) { hide(true); } } /** * callback from bottom navigation tab when it is un-selected */ void unSelect() { if (mHideOnSelect) { show(true); } } /////////////////////////////////////////////////////////////////////////// // Public functionality methods /////////////////////////////////////////////////////////////////////////// /** * @return this, to allow builder pattern */ public T toggle() { return toggle(true); } /** * @param animate whether to animate the change * @return this, to allow builder pattern */ public T toggle(boolean animate) { if (mIsHidden) { return show(animate); } else { return hide(animate); } } /** * @return this, to allow builder pattern */ public T show() { return show(true); } /** * @param animate whether to animate the change * @return this, to allow builder pattern */ public T show(boolean animate) { mIsHidden = false; if (isWeakReferenceValid()) { TextView textView = mTextViewRef.get(); if (animate) { textView.setScaleX(0); textView.setScaleY(0); textView.setVisibility(View.VISIBLE); ViewPropertyAnimatorCompat animatorCompat = ViewCompat.animate(textView); animatorCompat.cancel(); animatorCompat.setDuration(mAnimationDuration); animatorCompat.scaleX(1).scaleY(1); animatorCompat.setListener(null); animatorCompat.start(); } else { textView.setScaleX(1); textView.setScaleY(1); textView.setVisibility(View.VISIBLE); } } return getSubInstance(); } /** * @return this, to allow builder pattern */ public T hide() { return hide(true); } /** * @param animate whether to animate the change * @return this, to allow builder pattern */ public T hide(boolean animate) { mIsHidden = true; if (isWeakReferenceValid()) { TextView textView = mTextViewRef.get(); if (animate) { ViewPropertyAnimatorCompat animatorCompat = ViewCompat.animate(textView); animatorCompat.cancel(); animatorCompat.setDuration(mAnimationDuration); animatorCompat.scaleX(0).scaleY(0); animatorCompat.setListener(new ViewPropertyAnimatorListener() { @Override public void onAnimationStart(View view) { // Empty body } @Override public void onAnimationEnd(View view) { view.setVisibility(View.GONE); } @Override public void onAnimationCancel(View view) { view.setVisibility(View.GONE); } }); animatorCompat.start(); } else { textView.setVisibility(View.GONE); } } return getSubInstance(); } /** * @return if the badge is hidden */ public boolean isHidden() { return mIsHidden; } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BadgeItem.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
1,638
```java package com.ashokvarma.bottomnavigation; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; /** * Class description * * @author ashokvarma * @version 1.0 * @see BottomNavigationTab * @since 19 Mar 2016 */ class FixedBottomNavigationTab extends BottomNavigationTab { float labelScale; public FixedBottomNavigationTab(Context context) { super(context); } public FixedBottomNavigationTab(Context context, AttributeSet attrs) { super(context, attrs); } public FixedBottomNavigationTab(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public FixedBottomNavigationTab(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override void init() { paddingTopActive = (int) getResources().getDimension(R.dimen.fixed_height_top_padding_active); paddingTopInActive = (int) getResources().getDimension(R.dimen.fixed_height_top_padding_inactive); LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.fixed_bottom_navigation_item, this, true); containerView = view.findViewById(R.id.fixed_bottom_navigation_container); labelView = view.findViewById(R.id.fixed_bottom_navigation_title); iconView = view.findViewById(R.id.fixed_bottom_navigation_icon); iconContainerView = view.findViewById(R.id.fixed_bottom_navigation_icon_container); badgeView = view.findViewById(R.id.fixed_bottom_navigation_badge); labelScale = getResources().getDimension(R.dimen.fixed_label_inactive) / getResources().getDimension(R.dimen.fixed_label_active); super.init(); } @Override public void select(boolean setActiveColor, int animationDuration) { labelView.animate().scaleX(1).scaleY(1).setDuration(animationDuration).start(); // labelView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.fixed_label_active)); super.select(setActiveColor, animationDuration); } @Override public void unSelect(boolean setActiveColor, int animationDuration) { labelView.animate().scaleX(labelScale).scaleY(labelScale).setDuration(animationDuration).start(); // labelView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.fixed_label_inactive)); super.unSelect(setActiveColor, animationDuration); } @Override protected void setNoTitleIconContainerParams(FrameLayout.LayoutParams layoutParams) { layoutParams.height = getContext().getResources().getDimensionPixelSize(R.dimen.fixed_no_title_icon_container_height); layoutParams.width = getContext().getResources().getDimensionPixelSize(R.dimen.fixed_no_title_icon_container_width); } @Override protected void setNoTitleIconParams(LayoutParams layoutParams) { layoutParams.height = getContext().getResources().getDimensionPixelSize(R.dimen.fixed_no_title_icon_height); layoutParams.width = getContext().getResources().getDimensionPixelSize(R.dimen.fixed_no_title_icon_width); } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/FixedBottomNavigationTab.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
671
```java package com.ashokvarma.bottomnavigation; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.text.TextUtils; import android.widget.TextView; import androidx.annotation.ColorRes; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; /** * Class description * * @author ashokvarma * @version 1.0 * @see BadgeItem * @since 23 Jun 2017 */ public class TextBadgeItem extends BadgeItem<TextBadgeItem> { private int mBackgroundColorResource; private String mBackgroundColorCode; private int mBackgroundColor = Color.RED; private int mTextColorResource; private String mTextColorCode; private int mTextColor = Color.WHITE; private CharSequence mText; private int mBorderColorResource; private String mBorderColorCode; private int mBorderColor = Color.WHITE; private int mBorderWidthInPixels = 0; private int radius = -1; /////////////////////////////////////////////////////////////////////////// // Public setter methods /////////////////////////////////////////////////////////////////////////// /** * @param colorResource resource for background color * @return this, to allow builder pattern */ public TextBadgeItem setBackgroundColorResource(@ColorRes int colorResource) { this.mBackgroundColorResource = colorResource; refreshDrawable(); return this; } /** * @param colorCode color code for background color * @return this, to allow builder pattern */ public TextBadgeItem setBackgroundColor(@Nullable String colorCode) { this.mBackgroundColorCode = colorCode; refreshDrawable(); return this; } /** * @param color background color * @return this, to allow builder pattern */ public TextBadgeItem setBackgroundColor(int color) { this.mBackgroundColor = color; refreshDrawable(); return this; } /** * @param colorResource resource for text color * @return this, to allow builder pattern */ public TextBadgeItem setTextColorResource(@ColorRes int colorResource) { this.mTextColorResource = colorResource; setTextColor(); return this; } /** * @param colorCode color code for text color * @return this, to allow builder pattern */ public TextBadgeItem setTextColor(@Nullable String colorCode) { this.mTextColorCode = colorCode; setTextColor(); return this; } /** * @param color text color * @return this, to allow builder pattern */ public TextBadgeItem setTextColor(int color) { this.mTextColor = color; setTextColor(); return this; } /** * @param text text to be set in badge (this shouldn't be empty text) * @return this, to allow builder pattern */ public TextBadgeItem setText(@Nullable CharSequence text) { this.mText = text; if (isWeakReferenceValid()) { TextView textView = getTextView().get(); if (!TextUtils.isEmpty(text)) { textView.setText(text); } } return this; } /** * @param colorResource resource for border color * @return this, to allow builder pattern */ public TextBadgeItem setBorderColorResource(@ColorRes int colorResource) { this.mBorderColorResource = colorResource; refreshDrawable(); return this; } /** * @param radius corner radius * @return this, to allow builder pattern * */ public TextBadgeItem setCornerRadius(int radius) { this.radius = radius; refreshDrawable(); return this; } /** * @param colorCode color code for border color * @return this, to allow builder pattern */ public TextBadgeItem setBorderColor(@Nullable String colorCode) { this.mBorderColorCode = colorCode; refreshDrawable(); return this; } /** * @param color border color * @return this, to allow builder pattern */ public TextBadgeItem setBorderColor(int color) { this.mBorderColor = color; refreshDrawable(); return this; } /** * @param borderWidthInPixels border width in pixels * @return this, to allow builder pattern */ public TextBadgeItem setBorderWidth(int borderWidthInPixels) { this.mBorderWidthInPixels = borderWidthInPixels; refreshDrawable(); return this; } /////////////////////////////////////////////////////////////////////////// // Library only access method /////////////////////////////////////////////////////////////////////////// /** * {@inheritDoc} */ @Override TextBadgeItem getSubInstance() { return this; } /** * {@inheritDoc} */ @Override void bindToBottomTabInternal(BottomNavigationTab bottomNavigationTab) { Context context = bottomNavigationTab.getContext(); GradientDrawable shape = getBadgeDrawable(context); bottomNavigationTab.badgeView.setBackgroundDrawable(shape); bottomNavigationTab.badgeView.setTextColor(getTextColor(context)); bottomNavigationTab.badgeView.setText(getText()); } /////////////////////////////////////////////////////////////////////////// // Class only access methods /////////////////////////////////////////////////////////////////////////// /** * @param context to fetch color * @return background color */ private int getBackgroundColor(Context context) { if (this.mBackgroundColorResource != 0) { return ContextCompat.getColor(context, mBackgroundColorResource); } else if (!TextUtils.isEmpty(mBackgroundColorCode)) { return Color.parseColor(mBackgroundColorCode); } else { return mBackgroundColor; } } /** * @param context to fetch color * @return text color */ private int getTextColor(Context context) { if (this.mTextColorResource != 0) { return ContextCompat.getColor(context, mTextColorResource); } else if (!TextUtils.isEmpty(mTextColorCode)) { return Color.parseColor(mTextColorCode); } else { return mTextColor; } } /** * @return text that needs to be set in badge */ private CharSequence getText() { return mText; } /** * @param context to fetch color * @return border color */ private int getBorderColor(Context context) { if (this.mBorderColorResource != 0) { return ContextCompat.getColor(context, mBorderColorResource); } else if (!TextUtils.isEmpty(mBorderColorCode)) { return Color.parseColor(mBorderColorCode); } else { return mBorderColor; } } /** * @return border width */ private int getBorderWidth() { return mBorderWidthInPixels; } /** * @param context to fetch color * @return radius */ private int getRadius(Context context) { if (radius < 0) { return context.getResources().getDimensionPixelSize(R.dimen.badge_corner_radius); } else { return radius; } } /////////////////////////////////////////////////////////////////////////// // Internal Methods /////////////////////////////////////////////////////////////////////////// /** * refresh's background drawable */ private void refreshDrawable() { if (isWeakReferenceValid()) { TextView textView = getTextView().get(); textView.setBackgroundDrawable(getBadgeDrawable(textView.getContext())); } } /** * set's new text color */ private void setTextColor() { if (isWeakReferenceValid()) { TextView textView = getTextView().get(); textView.setTextColor(getTextColor(textView.getContext())); } } /** * @param context to fetch color * @return return the background drawable */ private GradientDrawable getBadgeDrawable(Context context) { GradientDrawable shape = new GradientDrawable(); shape.setShape(GradientDrawable.RECTANGLE); shape.setCornerRadius(getRadius(context)); shape.setColor(getBackgroundColor(context)); shape.setStroke(getBorderWidth(), getBorderColor(context)); return shape; } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/TextBadgeItem.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
1,653
```java package com.ashokvarma.bottomnavigation; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; import android.widget.FrameLayout; /** * Class description * * @author ashokvarma * @version 1.0 * @see BottomNavigationTab * @since 19 Mar 2016 */ class ShiftingBottomNavigationTab extends BottomNavigationTab { public ShiftingBottomNavigationTab(Context context) { super(context); } public ShiftingBottomNavigationTab(Context context, AttributeSet attrs) { super(context, attrs); } public ShiftingBottomNavigationTab(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public ShiftingBottomNavigationTab(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override void init() { paddingTopActive = (int) getResources().getDimension(R.dimen.shifting_height_top_padding_active); paddingTopInActive = (int) getResources().getDimension(R.dimen.shifting_height_top_padding_inactive); LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.shifting_bottom_navigation_item, this, true); containerView = view.findViewById(R.id.shifting_bottom_navigation_container); labelView = view.findViewById(R.id.shifting_bottom_navigation_title); iconView = view.findViewById(R.id.shifting_bottom_navigation_icon); iconContainerView = view.findViewById(R.id.shifting_bottom_navigation_icon_container); badgeView = view.findViewById(R.id.shifting_bottom_navigation_badge); super.init(); } @Override public void select(boolean setActiveColor, int animationDuration) { super.select(setActiveColor, animationDuration); ResizeWidthAnimation anim = new ResizeWidthAnimation(this, mActiveWidth); anim.setDuration(animationDuration); this.startAnimation(anim); labelView.animate().scaleY(1).scaleX(1).setDuration(animationDuration).start(); } @Override public void unSelect(boolean setActiveColor, int animationDuration) { super.unSelect(setActiveColor, animationDuration); ResizeWidthAnimation anim = new ResizeWidthAnimation(this, mInActiveWidth); anim.setDuration(animationDuration); this.startAnimation(anim); labelView.animate().scaleY(0).scaleX(0).setDuration(0).start(); } @Override protected void setNoTitleIconContainerParams(FrameLayout.LayoutParams layoutParams) { layoutParams.height = getContext().getResources().getDimensionPixelSize(R.dimen.shifting_no_title_icon_container_height); layoutParams.width = getContext().getResources().getDimensionPixelSize(R.dimen.shifting_no_title_icon_container_width); } @Override protected void setNoTitleIconParams(LayoutParams layoutParams) { layoutParams.height = getContext().getResources().getDimensionPixelSize(R.dimen.shifting_no_title_icon_height); layoutParams.width = getContext().getResources().getDimensionPixelSize(R.dimen.shifting_no_title_icon_width); } private class ResizeWidthAnimation extends Animation { private int mWidth; private int mStartWidth; private View mView; ResizeWidthAnimation(View view, int width) { mView = view; mWidth = width; mStartWidth = view.getWidth(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { mView.getLayoutParams().width = mStartWidth + (int) ((mWidth - mStartWidth) * interpolatedTime); mView.requestLayout(); } @Override public boolean willChangeBounds() { return true; } } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/ShiftingBottomNavigationTab.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
809
```java package com.ashokvarma.bottomnavigation; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.os.Build; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.animation.Interpolator; import android.widget.FrameLayout; import android.widget.LinearLayout; import androidx.annotation.ColorRes; import androidx.annotation.IntDef; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.content.ContextCompat; import androidx.core.view.ViewCompat; import androidx.core.view.ViewPropertyAnimatorCompat; import androidx.interpolator.view.animation.LinearOutSlowInInterpolator; import com.ashokvarma.bottomnavigation.behaviour.BottomNavBarFabBehaviour; import com.ashokvarma.bottomnavigation.behaviour.BottomVerticalScrollBehavior; import com.ashokvarma.bottomnavigation.utils.Utils; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; /** * Class description : This class is used to draw the layout and this acts like a bridge between * library and app, all details can be modified via this class. * * @author ashokvarma * @version 1.0 * @see FrameLayout * @see <a href="path_to_url">Google Bottom Navigation Component</a> * @since 19 Mar 2016 */ @CoordinatorLayout.DefaultBehavior(BottomVerticalScrollBehavior.class) public class BottomNavigationBar extends FrameLayout { public static final int MODE_DEFAULT = 0; public static final int MODE_FIXED = 1; public static final int MODE_SHIFTING = 2; public static final int MODE_FIXED_NO_TITLE = 3; public static final int MODE_SHIFTING_NO_TITLE = 4; @IntDef({MODE_DEFAULT, MODE_FIXED, MODE_SHIFTING, MODE_FIXED_NO_TITLE, MODE_SHIFTING_NO_TITLE}) @Retention(RetentionPolicy.SOURCE) @interface Mode { } public static final int BACKGROUND_STYLE_DEFAULT = 0; public static final int BACKGROUND_STYLE_STATIC = 1; public static final int BACKGROUND_STYLE_RIPPLE = 2; @IntDef({BACKGROUND_STYLE_DEFAULT, BACKGROUND_STYLE_STATIC, BACKGROUND_STYLE_RIPPLE}) @Retention(RetentionPolicy.SOURCE) @interface BackgroundStyle { } private static final int FAB_BEHAVIOUR_TRANSLATE_AND_STICK = 0; private static final int FAB_BEHAVIOUR_DISAPPEAR = 1; private static final int FAB_BEHAVIOUR_TRANSLATE_OUT = 2; @IntDef({FAB_BEHAVIOUR_TRANSLATE_AND_STICK, FAB_BEHAVIOUR_DISAPPEAR, FAB_BEHAVIOUR_TRANSLATE_OUT}) @Retention(RetentionPolicy.SOURCE) @interface FabBehaviour { } @Mode private int mMode = MODE_DEFAULT; @BackgroundStyle private int mBackgroundStyle = BACKGROUND_STYLE_DEFAULT; private static final Interpolator INTERPOLATOR = new LinearOutSlowInInterpolator(); private ViewPropertyAnimatorCompat mTranslationAnimator; private boolean mScrollable = false; private static final int MIN_SIZE = 3; private static final int MAX_SIZE = 5; ArrayList<BottomNavigationItem> mBottomNavigationItems = new ArrayList<>(); ArrayList<BottomNavigationTab> mBottomNavigationTabs = new ArrayList<>(); private static final int DEFAULT_SELECTED_POSITION = -1; private int mSelectedPosition = DEFAULT_SELECTED_POSITION; private int mFirstSelectedPosition = 0; private OnTabSelectedListener mTabSelectedListener; private int mActiveColor; private int mInActiveColor; private int mBackgroundColor; private FrameLayout mBackgroundOverlay; private FrameLayout mContainer; private LinearLayout mTabContainer; private static final int DEFAULT_ANIMATION_DURATION = 200; private int mAnimationDuration = DEFAULT_ANIMATION_DURATION; private int mRippleAnimationDuration = (int) (DEFAULT_ANIMATION_DURATION * 2.5); private float mElevation; private boolean mAutoHideEnabled; private boolean mIsHidden = false; /////////////////////////////////////////////////////////////////////////// // View Default Constructors and Methods /////////////////////////////////////////////////////////////////////////// public BottomNavigationBar(Context context) { this(context, null); } public BottomNavigationBar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BottomNavigationBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); parseAttrs(context, attrs); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public BottomNavigationBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); parseAttrs(context, attrs); init(); } /** * This method initiates the bottomNavigationBar properties, * Tries to get them form XML if not preset sets them to their default values. * * @param context context of the bottomNavigationBar * @param attrs attributes mentioned in the layout XML by user */ private void parseAttrs(Context context, AttributeSet attrs) { if (attrs != null) { TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.BottomNavigationBar, 0, 0); mActiveColor = typedArray.getColor(R.styleable.BottomNavigationBar_bnbActiveColor, Utils.fetchContextColor(context, R.attr.colorAccent)); mInActiveColor = typedArray.getColor(R.styleable.BottomNavigationBar_bnbInactiveColor, Color.LTGRAY); mBackgroundColor = typedArray.getColor(R.styleable.BottomNavigationBar_bnbBackgroundColor, Color.WHITE); mAutoHideEnabled = typedArray.getBoolean(R.styleable.BottomNavigationBar_bnbAutoHideEnabled, true); mElevation = typedArray.getDimension(R.styleable.BottomNavigationBar_bnbElevation, getResources().getDimension(R.dimen.bottom_navigation_elevation)); setAnimationDuration(typedArray.getInt(R.styleable.BottomNavigationBar_bnbAnimationDuration, DEFAULT_ANIMATION_DURATION)); switch (typedArray.getInt(R.styleable.BottomNavigationBar_bnbMode, MODE_DEFAULT)) { case MODE_FIXED: mMode = MODE_FIXED; break; case MODE_SHIFTING: mMode = MODE_SHIFTING; break; case MODE_FIXED_NO_TITLE: mMode = MODE_FIXED_NO_TITLE; break; case MODE_SHIFTING_NO_TITLE: mMode = MODE_SHIFTING_NO_TITLE; break; case MODE_DEFAULT: default: mMode = MODE_DEFAULT; break; } switch (typedArray.getInt(R.styleable.BottomNavigationBar_bnbBackgroundStyle, BACKGROUND_STYLE_DEFAULT)) { case BACKGROUND_STYLE_STATIC: mBackgroundStyle = BACKGROUND_STYLE_STATIC; break; case BACKGROUND_STYLE_RIPPLE: mBackgroundStyle = BACKGROUND_STYLE_RIPPLE; break; case BACKGROUND_STYLE_DEFAULT: default: mBackgroundStyle = BACKGROUND_STYLE_DEFAULT; break; } typedArray.recycle(); } else { mActiveColor = Utils.fetchContextColor(context, R.attr.colorAccent); mInActiveColor = Color.LTGRAY; mBackgroundColor = Color.WHITE; mElevation = getResources().getDimension(R.dimen.bottom_navigation_elevation); } } /** * This method initiates the bottomNavigationBar and handles layout related values */ private void init() { // MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) getContext().getResources().getDimension(R.dimen.bottom_navigation_padded_height))); // marginParams.setMargins(0, (int) getContext().getResources().getDimension(R.dimen.bottom_navigation_top_margin_correction), 0, 0); setLayoutParams(new ViewGroup.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))); LayoutInflater inflater = LayoutInflater.from(getContext()); View parentView = inflater.inflate(R.layout.bottom_navigation_bar_container, this, true); mBackgroundOverlay = parentView.findViewById(R.id.bottom_navigation_bar_overLay); mContainer = parentView.findViewById(R.id.bottom_navigation_bar_container); mTabContainer = parentView.findViewById(R.id.bottom_navigation_bar_item_container); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { this.setOutlineProvider(ViewOutlineProvider.BOUNDS); } else { //to do } ViewCompat.setElevation(this, mElevation); setClipToPadding(false); } // @Override // protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); // } /////////////////////////////////////////////////////////////////////////// // View Data Setter methods, Called before Initialize method /////////////////////////////////////////////////////////////////////////// /** * Used to add a new tab. * * @param item bottom navigation tab details * @return this, to allow builder pattern */ public BottomNavigationBar addItem(BottomNavigationItem item) { mBottomNavigationItems.add(item); return this; } /** * Used to remove a tab. * you should call initialise() after this to see the results effected. * * @param item bottom navigation tab details * @return this, to allow builder pattern */ public BottomNavigationBar removeItem(BottomNavigationItem item) { mBottomNavigationItems.remove(item); return this; } /** * @param mode any of the three Modes supported by library * @return this, to allow builder pattern */ public BottomNavigationBar setMode(@Mode int mode) { this.mMode = mode; return this; } /** * @param backgroundStyle any of the three Background Styles supported by library * @return this, to allow builder pattern */ public BottomNavigationBar setBackgroundStyle(@BackgroundStyle int backgroundStyle) { this.mBackgroundStyle = backgroundStyle; return this; } /** * @param activeColor res code for the default active color * @return this, to allow builder pattern */ public BottomNavigationBar setActiveColor(@ColorRes int activeColor) { this.mActiveColor = ContextCompat.getColor(getContext(), activeColor); return this; } /** * @param activeColorCode color code in string format for the default active color * @return this, to allow builder pattern */ public BottomNavigationBar setActiveColor(String activeColorCode) { this.mActiveColor = Color.parseColor(activeColorCode); return this; } /** * @param inActiveColor res code for the default in-active color * @return this, to allow builder pattern */ public BottomNavigationBar setInActiveColor(@ColorRes int inActiveColor) { this.mInActiveColor = ContextCompat.getColor(getContext(), inActiveColor); return this; } /** * @param inActiveColorCode color code in string format for the default in-active color * @return this, to allow builder pattern */ public BottomNavigationBar setInActiveColor(String inActiveColorCode) { this.mInActiveColor = Color.parseColor(inActiveColorCode); return this; } /** * @param backgroundColor res code for the default background color * @return this, to allow builder pattern */ public BottomNavigationBar setBarBackgroundColor(@ColorRes int backgroundColor) { this.mBackgroundColor = ContextCompat.getColor(getContext(), backgroundColor); return this; } /** * @param backgroundColorCode color code in string format for the default background color * @return this, to allow builder pattern */ public BottomNavigationBar setBarBackgroundColor(String backgroundColorCode) { this.mBackgroundColor = Color.parseColor(backgroundColorCode); return this; } /** * @param firstSelectedPosition position of tab that needs to be selected by default * @return this, to allow builder pattern */ public BottomNavigationBar setFirstSelectedPosition(int firstSelectedPosition) { this.mFirstSelectedPosition = firstSelectedPosition; return this; } /** * will be public once all bugs are resolved. */ private BottomNavigationBar setScrollable(boolean scrollable) { mScrollable = scrollable; return this; } /////////////////////////////////////////////////////////////////////////// // Initialise Method /////////////////////////////////////////////////////////////////////////// /** * This method should be called at the end of all customisation method. * This method will take all changes in to consideration and redraws tabs. */ public void initialise() { mSelectedPosition = DEFAULT_SELECTED_POSITION; mBottomNavigationTabs.clear(); if (!mBottomNavigationItems.isEmpty()) { mTabContainer.removeAllViews(); if (mMode == MODE_DEFAULT) { if (mBottomNavigationItems.size() <= MIN_SIZE) { mMode = MODE_FIXED; } else { mMode = MODE_SHIFTING; } } if (mBackgroundStyle == BACKGROUND_STYLE_DEFAULT) { if (mMode == MODE_FIXED) { mBackgroundStyle = BACKGROUND_STYLE_STATIC; } else { mBackgroundStyle = BACKGROUND_STYLE_RIPPLE; } } if (mBackgroundStyle == BACKGROUND_STYLE_STATIC) { mBackgroundOverlay.setVisibility(View.GONE); mContainer.setBackgroundColor(mBackgroundColor); } int screenWidth = Utils.getScreenWidth(getContext()); if (mMode == MODE_FIXED || mMode == MODE_FIXED_NO_TITLE) { int[] widths = BottomNavigationHelper.getMeasurementsForFixedMode(getContext(), screenWidth, mBottomNavigationItems.size(), mScrollable); int itemWidth = widths[0]; for (BottomNavigationItem currentItem : mBottomNavigationItems) { FixedBottomNavigationTab bottomNavigationTab = new FixedBottomNavigationTab(getContext()); setUpTab(mMode == MODE_FIXED_NO_TITLE, bottomNavigationTab, currentItem, itemWidth, itemWidth); } } else if (mMode == MODE_SHIFTING || mMode == MODE_SHIFTING_NO_TITLE) { int[] widths = BottomNavigationHelper.getMeasurementsForShiftingMode(getContext(), screenWidth, mBottomNavigationItems.size(), mScrollable); int itemWidth = widths[0]; int itemActiveWidth = widths[1]; for (BottomNavigationItem currentItem : mBottomNavigationItems) { ShiftingBottomNavigationTab bottomNavigationTab = new ShiftingBottomNavigationTab(getContext()); setUpTab(mMode == MODE_SHIFTING_NO_TITLE, bottomNavigationTab, currentItem, itemWidth, itemActiveWidth); } } if (mBottomNavigationTabs.size() > mFirstSelectedPosition) { selectTabInternal(mFirstSelectedPosition, true, false, false); } else if (!mBottomNavigationTabs.isEmpty()) { selectTabInternal(0, true, false, false); } } } //////////////////////////////////////////////////////////////////////////////////////////////// // Anytime Setter methods that can be called irrespective of whether we call initialise or not //////////////////////////////////////////////////////////////////////////////////////////////// /** * @param tabSelectedListener callback listener for tabs * @return this, to allow builder pattern */ public BottomNavigationBar setTabSelectedListener(OnTabSelectedListener tabSelectedListener) { this.mTabSelectedListener = tabSelectedListener; return this; } /** * ripple animation will be 2.5 times this animation duration. * * @param animationDuration animation duration for tab animations * @return this, to allow builder pattern */ public BottomNavigationBar setAnimationDuration(int animationDuration) { this.mAnimationDuration = animationDuration; this.mRippleAnimationDuration = (int) (animationDuration * 2.5); return this; } /** * Clears all stored data and this helps to re-initialise tabs from scratch */ public void clearAll() { mTabContainer.removeAllViews(); mBottomNavigationTabs.clear(); mBottomNavigationItems.clear(); mBackgroundOverlay.setVisibility(View.GONE); mContainer.setBackgroundColor(Color.TRANSPARENT); mSelectedPosition = DEFAULT_SELECTED_POSITION; } /////////////////////////////////////////////////////////////////////////// // Setter methods that should called only after initialise is called /////////////////////////////////////////////////////////////////////////// /** * Should be called only after initialization of BottomBar(i.e after calling initialize method) * * @param newPosition to select a tab after bottom navigation bar is initialised */ public void selectTab(int newPosition) { selectTab(newPosition, true); } /** * Should be called only after initialization of BottomBar(i.e after calling initialize method) * * @param newPosition to select a tab after bottom navigation bar is initialised * @param callListener should this change call listener callbacks */ public void selectTab(int newPosition, boolean callListener) { selectTabInternal(newPosition, false, callListener, callListener); } /////////////////////////////////////////////////////////////////////////// // Internal Methods of the class /////////////////////////////////////////////////////////////////////////// /** * Internal method to setup tabs * * @param isNoTitleMode if no title mode is required * @param bottomNavigationTab Tab item * @param currentItem data structure for tab item * @param itemWidth tab item in-active width * @param itemActiveWidth tab item active width */ private void setUpTab(boolean isNoTitleMode, BottomNavigationTab bottomNavigationTab, BottomNavigationItem currentItem, int itemWidth, int itemActiveWidth) { bottomNavigationTab.setIsNoTitleMode(isNoTitleMode); bottomNavigationTab.setInactiveWidth(itemWidth); bottomNavigationTab.setActiveWidth(itemActiveWidth); bottomNavigationTab.setPosition(mBottomNavigationItems.indexOf(currentItem)); bottomNavigationTab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { BottomNavigationTab bottomNavigationTabView = (BottomNavigationTab) v; selectTabInternal(bottomNavigationTabView.getPosition(), false, true, false); } }); mBottomNavigationTabs.add(bottomNavigationTab); BottomNavigationHelper.bindTabWithData(currentItem, bottomNavigationTab, this); bottomNavigationTab.initialise(mBackgroundStyle == BACKGROUND_STYLE_STATIC); mTabContainer.addView(bottomNavigationTab); } /** * Internal Method to select a tab * * @param newPosition to select a tab after bottom navigation bar is initialised * @param firstTab if firstTab the no ripple animation will be done * @param callListener is listener callbacks enabled for this change * @param forcedSelection if bottom navigation bar forced to select tab (in this case call on selected irrespective of previous state */ private void selectTabInternal(int newPosition, boolean firstTab, boolean callListener, boolean forcedSelection) { int oldPosition = mSelectedPosition; if (mSelectedPosition != newPosition) { if (mBackgroundStyle == BACKGROUND_STYLE_STATIC) { if (mSelectedPosition != -1) mBottomNavigationTabs.get(mSelectedPosition).unSelect(true, mAnimationDuration); mBottomNavigationTabs.get(newPosition).select(true, mAnimationDuration); } else if (mBackgroundStyle == BACKGROUND_STYLE_RIPPLE) { if (mSelectedPosition != -1) mBottomNavigationTabs.get(mSelectedPosition).unSelect(false, mAnimationDuration); mBottomNavigationTabs.get(newPosition).select(false, mAnimationDuration); final BottomNavigationTab clickedView = mBottomNavigationTabs.get(newPosition); if (firstTab) { // Running a ripple on the opening app won't be good so on firstTab this won't run. mContainer.setBackgroundColor(clickedView.getActiveColor()); mBackgroundOverlay.setVisibility(View.GONE); } else { mBackgroundOverlay.post(new Runnable() { @Override public void run() { // try { BottomNavigationHelper.setBackgroundWithRipple(clickedView, mContainer, mBackgroundOverlay, clickedView.getActiveColor(), mRippleAnimationDuration); // } catch (Exception e) { // mContainer.setBackgroundColor(clickedView.getActiveColor()); // mBackgroundOverlay.setVisibility(View.GONE); // } } }); } } mSelectedPosition = newPosition; } if (callListener) { sendListenerCall(oldPosition, newPosition, forcedSelection); } } /** * Internal method used to send callbacks to listener * * @param oldPosition old selected tab position, -1 if this is first call * @param newPosition newly selected tab position * @param forcedSelection if bottom navigation bar forced to select tab (in this case call on selected irrespective of previous state */ private void sendListenerCall(int oldPosition, int newPosition, boolean forcedSelection) { if (mTabSelectedListener != null) { // && oldPosition != -1) { if (forcedSelection) { mTabSelectedListener.onTabSelected(newPosition); } else { if (oldPosition == newPosition) { mTabSelectedListener.onTabReselected(newPosition); } else { mTabSelectedListener.onTabSelected(newPosition); if (oldPosition != -1) { mTabSelectedListener.onTabUnselected(oldPosition); } } } } } /////////////////////////////////////////////////////////////////////////// // Animating methods /////////////////////////////////////////////////////////////////////////// /** * show BottomNavigationBar if it is hidden and hide if it is shown */ public void toggle() { toggle(true); } /** * show BottomNavigationBar if it is hidden and hide if it is shown * * @param animate is animation enabled for toggle */ public void toggle(boolean animate) { if (mIsHidden) { show(animate); } else { hide(animate); } } /** * hide with animation */ public void hide() { hide(true); } /** * @param animate is animation enabled for hide */ public void hide(boolean animate) { mIsHidden = true; setTranslationY(this.getHeight(), animate); } /** * show with animation */ public void show() { show(true); } /** * @param animate is animation enabled for show */ public void show(boolean animate) { mIsHidden = false; setTranslationY(0, animate); } /** * @param offset offset needs to be set * @param animate is animation enabled for translation */ private void setTranslationY(int offset, boolean animate) { if (animate) { animateOffset(offset); } else { if (mTranslationAnimator != null) { mTranslationAnimator.cancel(); } this.setTranslationY(offset); } } /** * Internal Method * <p> * used to set animation and * takes care of cancelling current animation * and sets duration and interpolator for animation * * @param offset translation offset that needs to set with animation */ private void animateOffset(final int offset) { if (mTranslationAnimator == null) { mTranslationAnimator = ViewCompat.animate(this); mTranslationAnimator.setDuration(mRippleAnimationDuration); mTranslationAnimator.setInterpolator(INTERPOLATOR); } else { mTranslationAnimator.cancel(); } mTranslationAnimator.translationY(offset).start(); } public boolean isHidden() { return mIsHidden; } /////////////////////////////////////////////////////////////////////////// // Behaviour Handing Handling /////////////////////////////////////////////////////////////////////////// public boolean isAutoHideEnabled() { return mAutoHideEnabled; } public void setAutoHideEnabled(boolean mAutoHideEnabled) { this.mAutoHideEnabled = mAutoHideEnabled; } public void setFab(FloatingActionButton fab) { ViewGroup.LayoutParams layoutParams = fab.getLayoutParams(); if (layoutParams != null && layoutParams instanceof CoordinatorLayout.LayoutParams) { CoordinatorLayout.LayoutParams coLayoutParams = (CoordinatorLayout.LayoutParams) layoutParams; BottomNavBarFabBehaviour bottomNavBarFabBehaviour = new BottomNavBarFabBehaviour(); coLayoutParams.setBehavior(bottomNavBarFabBehaviour); } } // scheduled for next private void setFab(FloatingActionButton fab, @FabBehaviour int fabBehaviour) { ViewGroup.LayoutParams layoutParams = fab.getLayoutParams(); if (layoutParams != null && layoutParams instanceof CoordinatorLayout.LayoutParams) { CoordinatorLayout.LayoutParams coLayoutParams = (CoordinatorLayout.LayoutParams) layoutParams; BottomNavBarFabBehaviour bottomNavBarFabBehaviour = new BottomNavBarFabBehaviour(); coLayoutParams.setBehavior(bottomNavBarFabBehaviour); } } /////////////////////////////////////////////////////////////////////////// // Getters /////////////////////////////////////////////////////////////////////////// /** * @return activeColor */ public int getActiveColor() { return mActiveColor; } /** * @return in-active color */ public int getInActiveColor() { return mInActiveColor; } /** * @return background color */ public int getBackgroundColor() { return mBackgroundColor; } /** * @return current selected position */ public int getCurrentSelectedPosition() { return mSelectedPosition; } /** * @return animation duration */ public int getAnimationDuration() { return mAnimationDuration; } /////////////////////////////////////////////////////////////////////////// // Listener interfaces /////////////////////////////////////////////////////////////////////////// /** * Callback interface invoked when a tab's selection state changes. */ public interface OnTabSelectedListener { /** * Called when a tab enters the selected state. * * @param position The position of the tab that was selected */ void onTabSelected(int position); /** * Called when a tab exits the selected state. * * @param position The position of the tab that was unselected */ void onTabUnselected(int position); /** * Called when a tab that is already selected is chosen again by the user. Some applications * may use this action to return to the top level of a category. * * @param position The position of the tab that was reselected. */ void onTabReselected(int position); } /** * Simple implementation of the OnTabSelectedListener interface with stub implementations of each method. * Extend this if you do not intend to override every method of OnTabSelectedListener. */ public static class SimpleOnTabSelectedListener implements OnTabSelectedListener { @Override public void onTabSelected(int position) { } @Override public void onTabUnselected(int position) { } @Override public void onTabReselected(int position) { } } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BottomNavigationBar.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
5,590
```java package com.ashokvarma.bottomnavigation; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.text.TextUtils; import android.view.ViewGroup; import androidx.annotation.ColorRes; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import com.ashokvarma.bottomnavigation.utils.Utils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Class description * * @author ashokvarma * @version 1.0 * @see BadgeItem * @since 23 Jun 2017 */ public class ShapeBadgeItem extends BadgeItem<ShapeBadgeItem> { public static final int SHAPE_OVAL = 0; public static final int SHAPE_RECTANGLE = 1; public static final int SHAPE_HEART = 2; public static final int SHAPE_STAR_3_VERTICES = 3; public static final int SHAPE_STAR_4_VERTICES = 4; public static final int SHAPE_STAR_5_VERTICES = 5; public static final int SHAPE_STAR_6_VERTICES = 6; @IntDef({SHAPE_OVAL, SHAPE_RECTANGLE, SHAPE_HEART, SHAPE_STAR_3_VERTICES, SHAPE_STAR_4_VERTICES, SHAPE_STAR_5_VERTICES, SHAPE_STAR_6_VERTICES}) @Retention(RetentionPolicy.SOURCE) @interface Shape { } private @Shape int mShape = SHAPE_STAR_5_VERTICES; private String mShapeColorCode; private int mShapeColorResource; private int mShapeColor = Color.RED; // init values set at bindToBottomTabInternal private int mHeightInPixels; private int mWidthInPixels; private int mEdgeMarginInPx; private RectF mCanvasRect = new RectF(); private Paint mCanvasPaint; private Path mPath = new Path();// used for pathDrawables public ShapeBadgeItem() { mCanvasPaint = new Paint(); mCanvasPaint.setColor(mShapeColor); // If stroke needed // paint.setStrokeWidth(widthInPx); // paint.setStyle(Paint.Style.STROKE); mCanvasPaint.setAntiAlias(true); mCanvasPaint.setStyle(Paint.Style.FILL); } /////////////////////////////////////////////////////////////////////////// // public methods /////////////////////////////////////////////////////////////////////////// /** * @param shape new shape that needs to be drawn * @return this, to allow builder pattern */ public ShapeBadgeItem setShape(@Shape int shape) { this.mShape = shape; refreshDraw(); return this; } /** * @param colorResource resource for background color * @return this, to allow builder pattern */ public ShapeBadgeItem setShapeColorResource(@ColorRes int colorResource) { this.mShapeColorResource = colorResource; refreshColor(); return this; } /** * @param colorCode color code for background color * @return this, to allow builder pattern */ public ShapeBadgeItem setShapeColor(@Nullable String colorCode) { this.mShapeColorCode = colorCode; refreshColor(); return this; } /** * @param color background color * @return this, to allow builder pattern */ public ShapeBadgeItem setShapeColor(int color) { this.mShapeColor = color; refreshColor(); return this; } /** * @param context to convert dp to pixel * @param heightInDp dp size for height of badge item * @param widthInDp dp size for width of badge item * @return this, to allow builder pattern */ public ShapeBadgeItem setSizeInDp(Context context, int heightInDp, int widthInDp) { mHeightInPixels = Utils.dp2px(context, heightInDp); mWidthInPixels = Utils.dp2px(context, widthInDp); if (isWeakReferenceValid()) { getTextView().get().setDimens(mWidthInPixels, mHeightInPixels); } return this; } /** * @param heightInPx pixel size for height of badge item * @param widthInPx pixel size for width of badge item * @return this, to allow builder pattern */ public ShapeBadgeItem setSizeInPixels(int heightInPx, int widthInPx) { mHeightInPixels = heightInPx; mWidthInPixels = widthInPx; if (isWeakReferenceValid()) { getTextView().get().setDimens(mWidthInPixels, mHeightInPixels); } return this; } /** * @param context to convert dp to pixel * @param edgeMarginInDp dp size for margin of badge item * @return this, to allow builder pattern */ public ShapeBadgeItem setEdgeMarginInDp(Context context, int edgeMarginInDp) { mEdgeMarginInPx = Utils.dp2px(context, edgeMarginInDp); refreshMargin(); return this; } /** * @param edgeMarginInPx pixel size for margin of badge item * @return this, to allow builder pattern */ public ShapeBadgeItem setEdgeMarginInPixels(int edgeMarginInPx) { mEdgeMarginInPx = edgeMarginInPx; refreshMargin(); return this; } /////////////////////////////////////////////////////////////////////////// // Library internal methods /////////////////////////////////////////////////////////////////////////// /** * draw's specified shape * * @param canvas on which shape has to be drawn */ void draw(Canvas canvas) { mCanvasRect.set(0.0f, 0.0f, canvas.getWidth(), canvas.getHeight()); switch (mShape) { case SHAPE_RECTANGLE: canvas.drawRect(mCanvasRect, mCanvasPaint); break; case SHAPE_OVAL: canvas.drawOval(mCanvasRect, mCanvasPaint); break; case SHAPE_STAR_3_VERTICES: case SHAPE_STAR_4_VERTICES: case SHAPE_STAR_5_VERTICES: case SHAPE_STAR_6_VERTICES: drawStar(canvas, mShape); break; case SHAPE_HEART: drawHeart(canvas); break; } } /** * {@inheritDoc} */ @Override ShapeBadgeItem getSubInstance() { return this; } /** * {@inheritDoc} */ @Override void bindToBottomTabInternal(BottomNavigationTab bottomNavigationTab) { if (mHeightInPixels == 0) mHeightInPixels = Utils.dp2px(bottomNavigationTab.getContext(), 12); if (mWidthInPixels == 0) mWidthInPixels = Utils.dp2px(bottomNavigationTab.getContext(), 12); if (mEdgeMarginInPx == 0) mEdgeMarginInPx = Utils.dp2px(bottomNavigationTab.getContext(), 4); refreshMargin(); refreshColor();// so that user set color will be updated bottomNavigationTab.badgeView.setShapeBadgeItem(this); bottomNavigationTab.badgeView.setDimens(mWidthInPixels, mHeightInPixels); } /////////////////////////////////////////////////////////////////////////// // Class only access methods /////////////////////////////////////////////////////////////////////////// /** * @return shape color */ private int getShapeColor(Context context) { if (this.mShapeColorResource != 0) { return ContextCompat.getColor(context, mShapeColorResource); } else if (!TextUtils.isEmpty(mShapeColorCode)) { return Color.parseColor(mShapeColorCode); } else { return mShapeColor; } } /////////////////////////////////////////////////////////////////////////// // Internal Methods /////////////////////////////////////////////////////////////////////////// /** * refresh's paint color if set and redraw's shape with new color */ private void refreshColor() { if (isWeakReferenceValid()) { mCanvasPaint.setColor(getShapeColor(getTextView().get().getContext())); } refreshDraw(); } /** * notifies BadgeTextView to invalidate so it will draw again and redraws shape */ private void refreshDraw() { if (isWeakReferenceValid()) { getTextView().get().recallOnDraw(); } } /** * refresh's margin if set */ private void refreshMargin() { if (isWeakReferenceValid()) { ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getTextView().get().getLayoutParams(); layoutParams.bottomMargin = mEdgeMarginInPx; layoutParams.topMargin = mEdgeMarginInPx; layoutParams.rightMargin = mEdgeMarginInPx; layoutParams.leftMargin = mEdgeMarginInPx; getTextView().get().setLayoutParams(layoutParams); } } /** * @param canvas on which star needs to be drawn * @param numOfPt no of points a star should have */ private void drawStar(Canvas canvas, int numOfPt) { double section = 2.0 * Math.PI / numOfPt; double halfSection = section / 2.0d; double antiClockRotation = getStarAntiClockRotationOffset(numOfPt); float x = (float) canvas.getWidth() / 2.0f; float y = (float) canvas.getHeight() / 2.0f; float radius, innerRadius; if (canvas.getWidth() > canvas.getHeight()) { radius = canvas.getHeight() * 0.5f; innerRadius = canvas.getHeight() * 0.25f; } else { radius = canvas.getWidth() * 0.5f; innerRadius = canvas.getWidth() * 0.25f; } mPath.reset(); mPath.moveTo( (float) (x + radius * Math.cos(0 - antiClockRotation)), (float) (y + radius * Math.sin(0 - antiClockRotation))); mPath.lineTo( (float) (x + innerRadius * Math.cos(0 + halfSection - antiClockRotation)), (float) (y + innerRadius * Math.sin(0 + halfSection - antiClockRotation))); for (int i = 1; i < numOfPt; i++) { mPath.lineTo( (float) (x + radius * Math.cos(section * i - antiClockRotation)), (float) (y + radius * Math.sin(section * i - antiClockRotation))); mPath.lineTo( (float) (x + innerRadius * Math.cos(section * i + halfSection - antiClockRotation)), (float) (y + innerRadius * Math.sin(section * i + halfSection - antiClockRotation))); } mPath.close(); canvas.drawPath(mPath, mCanvasPaint); } /** * offset to make star shape look straight * * @param numOfPt no of points a star should have */ private double getStarAntiClockRotationOffset(int numOfPt) { if (numOfPt == 5) { return 2.0 * Math.PI / 20.0d; // quarter of (section angle for 5 point star) = 36 degrees } else if (numOfPt == 6) { return 2.0 * Math.PI / 12.0d; // half the (section angle for 6 point star) = 60 degrees } return 0; } private void drawHeart(Canvas canvas) { mPath.reset(); float width = canvas.getWidth(); float height = canvas.getHeight(); // Starting point mPath.moveTo(width / 2, height / 5); // Upper left path mPath.cubicTo(5 * width / 14, 0, 0, height / 15, width / 28, 2 * height / 5); // Lower left path mPath.cubicTo(width / 14, 2 * height / 3, 3 * width / 7, 5 * height / 6, width / 2, height); // Lower right path mPath.cubicTo(4 * width / 7, 5 * height / 6, 13 * width / 14, 2 * height / 3, 27 * width / 28, 2 * height / 5); // Upper right path mPath.cubicTo(width, height / 15, 9 * width / 14, 0, width / 2, height / 5); mPath.close(); canvas.drawPath(mPath, mCanvasPaint); } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/ShapeBadgeItem.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
2,757
```java package com.ashokvarma.bottomnavigation.behaviour; import android.view.View; import android.view.animation.Interpolator; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.view.ViewCompat; import androidx.core.view.ViewPropertyAnimatorCompat; import androidx.interpolator.view.animation.FastOutSlowInInterpolator; import com.ashokvarma.bottomnavigation.BottomNavigationBar; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import java.util.List; /** * Class description * * @author ashokvarma * @version 1.0 * @since 06 Jun 2016 */ public class BottomNavBarFabBehaviour extends CoordinatorLayout.Behavior<FloatingActionButton> { ViewPropertyAnimatorCompat mFabTranslationYAnimator; // @BottomNavigationBar.FabBehaviour // private int mFabBehaviour; static final Interpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new FastOutSlowInInterpolator(); /////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////// // public BottomNavBarFabBehaviour() { // mFabBehaviour = BottomNavigationBar.FAB_BEHAVIOUR_TRANSLATE_AND_STICK; // } /////////////////////////////////////////////////////////////////////////// // Dependencies setup /////////////////////////////////////////////////////////////////////////// @Override public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) { return isDependent(dependency) || super.layoutDependsOn(parent, child, dependency); } @Override public boolean onLayoutChild(CoordinatorLayout parent, FloatingActionButton child, int layoutDirection) { // First let the parent lay it out parent.onLayoutChild(child, layoutDirection); updateFabTranslationForBottomNavigationBar(parent, child, null); return super.onLayoutChild(parent, child, layoutDirection); } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) { if (isDependent(dependency)) { updateFabTranslationForBottomNavigationBar(parent, child, dependency); return false; } return super.onDependentViewChanged(parent, child, dependency); } @Override public void onDependentViewRemoved(CoordinatorLayout parent, FloatingActionButton child, View dependency) { if (isDependent(dependency)) { updateFabTranslationForBottomNavigationBar(parent, child, dependency); } } private boolean isDependent(View dependency) { return dependency instanceof BottomNavigationBar || dependency instanceof Snackbar.SnackbarLayout; } /////////////////////////////////////////////////////////////////////////// // Animating Fab based on Changes /////////////////////////////////////////////////////////////////////////// private void updateFabTranslationForBottomNavigationBar(CoordinatorLayout parent, FloatingActionButton fab, View dependency) { float snackBarTranslation = getFabTranslationYForSnackBar(parent, fab); float[] bottomBarParameters = getFabTranslationYForBottomNavigationBar(parent, fab); float bottomBarTranslation = bottomBarParameters[0]; float bottomBarHeight = bottomBarParameters[1]; float targetTransY; if (snackBarTranslation >= bottomBarTranslation) { // when snackBar is below BottomBar in translation present. targetTransY = bottomBarTranslation; } else { targetTransY = snackBarTranslation; } // if (mFabBehaviour == BottomNavigationBar.FAB_BEHAVIOUR_DISAPPEAR) { // if (targetTransY == 0) { // fab.hide(); // } else { // fab.show(); // } // } final float currentTransY = fab.getTranslationY(); // Make sure that any current animation is cancelled ensureOrCancelAnimator(fab); if (fab.isShown() && Math.abs(currentTransY - targetTransY) > (fab.getHeight() * 0.667f)) { // If the FAB will be travelling by more than 2/3 of it's height, let's animate it instead mFabTranslationYAnimator.translationY(targetTransY).start(); } else { // Now update the translation Y fab.setTranslationY(targetTransY); } } /////////////////////////////////////////////////////////////////////////// // Fab Translation due to SnackBar and Due to BottomBar /////////////////////////////////////////////////////////////////////////// private float[] getFabTranslationYForBottomNavigationBar(CoordinatorLayout parent, FloatingActionButton fab) { float minOffset = 0; float viewHeight = 0; final List<View> dependencies = parent.getDependencies(fab); for (int i = 0, z = dependencies.size(); i < z; i++) { final View view = dependencies.get(i); if (view instanceof BottomNavigationBar) { viewHeight = view.getHeight(); minOffset = Math.min(minOffset, view.getTranslationY() - viewHeight); } } return new float[]{minOffset, viewHeight}; } private float getFabTranslationYForSnackBar(CoordinatorLayout parent, FloatingActionButton fab) { float minOffset = 0; final List<View> dependencies = parent.getDependencies(fab); for (int i = 0, z = dependencies.size(); i < z; i++) { final View view = dependencies.get(i); if (view instanceof Snackbar.SnackbarLayout && parent.doViewsOverlap(fab, view)) { minOffset = Math.min(minOffset, view.getTranslationY() - view.getHeight()); } } return minOffset; } // public void setmFabBehaviour(int mFabBehaviour) { // this.mFabBehaviour = mFabBehaviour; // } /////////////////////////////////////////////////////////////////////////// // Animator Initializer /////////////////////////////////////////////////////////////////////////// private void ensureOrCancelAnimator(FloatingActionButton fab) { if (mFabTranslationYAnimator == null) { mFabTranslationYAnimator = ViewCompat.animate(fab); mFabTranslationYAnimator.setDuration(400); mFabTranslationYAnimator.setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR); } else { mFabTranslationYAnimator.cancel(); } } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/behaviour/BottomNavBarFabBehaviour.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
1,254
```java package com.ashokvarma.bottomnavigation; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.text.TextUtils; import androidx.annotation.ColorRes; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.core.content.ContextCompat; import com.ashokvarma.bottomnavigation.utils.Utils; /** * Class description : Holds data for tabs (i.e data structure which holds all data to paint a tab) * * @author ashokvarma * @version 1.0 * @since 19 Mar 2016 */ public class BottomNavigationItem { private int mIconResource; private Drawable mIcon; private int mInactiveIconResource; private Drawable mInactiveIcon; private boolean inActiveIconAvailable = false; private int mTitleResource; private String mTitle; private int mActiveColorResource; private String mActiveColorCode; private int mActiveColor; private int mInActiveColorResource; private String mInActiveColorCode; private int mInActiveColor; private BadgeItem mBadgeItem; /** * @param mIconResource resource for the Tab icon. * @param mTitle title for the Tab. */ public BottomNavigationItem(@DrawableRes int mIconResource, @NonNull String mTitle) { this.mIconResource = mIconResource; this.mTitle = mTitle; } /** * @param mIcon drawable icon for the Tab. * @param mTitle title for the Tab. */ public BottomNavigationItem(Drawable mIcon, @NonNull String mTitle) { this.mIcon = mIcon; this.mTitle = mTitle; } /** * @param mIcon drawable icon for the Tab. * @param mTitleResource resource for the title. */ public BottomNavigationItem(Drawable mIcon, @StringRes int mTitleResource) { this.mIcon = mIcon; this.mTitleResource = mTitleResource; } /** * @param mIconResource resource for the Tab icon. * @param mTitleResource resource for the title. */ public BottomNavigationItem(@DrawableRes int mIconResource, @StringRes int mTitleResource) { this.mIconResource = mIconResource; this.mTitleResource = mTitleResource; } /** * By default library will switch the color of icon provided (in between active and in-active icons) * This method is used, if people need to set different icons for active and in-active modes. * * @param mInactiveIcon in-active drawable icon * @return this, to allow builder pattern */ public BottomNavigationItem setInactiveIcon(Drawable mInactiveIcon) { if (mInactiveIcon != null) { this.mInactiveIcon = mInactiveIcon; inActiveIconAvailable = true; } return this; } /** * By default library will switch the color of icon provided (in between active and in-active icons) * This method is used, if people need to set different icons for active and in-active modes. * * @param mInactiveIconResource resource for the in-active icon. * @return this, to allow builder pattern */ public BottomNavigationItem setInactiveIconResource(@DrawableRes int mInactiveIconResource) { this.mInactiveIconResource = mInactiveIconResource; inActiveIconAvailable = true; return this; } /** * @param colorResource resource for active color * @return this, to allow builder pattern */ public BottomNavigationItem setActiveColorResource(@ColorRes int colorResource) { this.mActiveColorResource = colorResource; return this; } /** * @param colorCode color code for active color * @return this, to allow builder pattern */ public BottomNavigationItem setActiveColor(@Nullable String colorCode) { this.mActiveColorCode = colorCode; return this; } /** * @param color active color * @return this, to allow builder pattern */ public BottomNavigationItem setActiveColor(int color) { this.mActiveColor = color; return this; } /** * @param colorResource resource for in-active color * @return this, to allow builder pattern */ public BottomNavigationItem setInActiveColorResource(@ColorRes int colorResource) { this.mInActiveColorResource = colorResource; return this; } /** * @param colorCode color code for in-active color * @return this, to allow builder pattern */ public BottomNavigationItem setInActiveColor(@Nullable String colorCode) { this.mInActiveColorCode = colorCode; return this; } /** * @param color in-active color * @return this, to allow builder pattern */ public BottomNavigationItem setInActiveColor(int color) { this.mInActiveColor = color; return this; } /** * @param badgeItem badge that needs to be displayed for this tab * @return this, to allow builder pattern */ public BottomNavigationItem setBadgeItem(@Nullable ShapeBadgeItem badgeItem) { this.mBadgeItem = badgeItem; return this; } /** * @param badgeItem badge that needs to be displayed for this tab * @return this, to allow builder pattern */ public BottomNavigationItem setBadgeItem(@Nullable TextBadgeItem badgeItem) { this.mBadgeItem = badgeItem; return this; } /////////////////////////////////////////////////////////////////////////// // Library only access method /////////////////////////////////////////////////////////////////////////// /** * @param context to fetch drawable * @return icon drawable */ Drawable getIcon(Context context) { if (this.mIconResource != 0) { return ContextCompat.getDrawable(context, this.mIconResource); } else { return this.mIcon; } } /** * @param context to fetch resource * @return title string */ String getTitle(Context context) { if (this.mTitleResource != 0) { return context.getString(this.mTitleResource); } else { return this.mTitle; } } /** * @param context to fetch resources * @return in-active icon drawable */ Drawable getInactiveIcon(Context context) { if (this.mInactiveIconResource != 0) { return ContextCompat.getDrawable(context, this.mInactiveIconResource); } else { return this.mInactiveIcon; } } /** * @return if in-active icon is set */ boolean isInActiveIconAvailable() { return inActiveIconAvailable; } /** * @param context to fetch color * @return active color (or) -1 if no color is specified */ int getActiveColor(Context context) { if (this.mActiveColorResource != 0) { return ContextCompat.getColor(context, mActiveColorResource); } else if (!TextUtils.isEmpty(mActiveColorCode)) { return Color.parseColor(mActiveColorCode); } else if (this.mActiveColor != 0) { return mActiveColor; } else { return Utils.NO_COLOR; } } /** * @param context to fetch color * @return in-active color (or) -1 if no color is specified */ int getInActiveColor(Context context) { if (this.mInActiveColorResource != 0) { return ContextCompat.getColor(context, mInActiveColorResource); } else if (!TextUtils.isEmpty(mInActiveColorCode)) { return Color.parseColor(mInActiveColorCode); } else if (this.mInActiveColor != 0) { return mInActiveColor; } else { return Utils.NO_COLOR; } } /** * @return badge item that needs to set to respective view */ BadgeItem getBadgeItem() { return mBadgeItem; } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BottomNavigationItem.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
1,753
```java package com.ashokvarma.bottomnavigation.behaviour; import android.view.View; import android.view.animation.Interpolator; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.view.ViewCompat; import androidx.interpolator.view.animation.FastOutSlowInInterpolator; import com.ashokvarma.bottomnavigation.BottomNavigationBar; import com.google.android.material.snackbar.Snackbar; import java.lang.ref.WeakReference; import java.util.List; /** * Class description * * @author ashokvarma * @version 1.0 * @see VerticalScrollingBehavior * @since 25 Mar 2016 */ public class BottomVerticalScrollBehavior<V extends View> extends VerticalScrollingBehavior<V> { private static final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator(); private int mBottomNavHeight; private WeakReference<BottomNavigationBar> mViewRef; /////////////////////////////////////////////////////////////////////////// // onBottomBar changes /////////////////////////////////////////////////////////////////////////// @Override public boolean onLayoutChild(CoordinatorLayout parent, final V child, int layoutDirection) { // First let the parent lay it out parent.onLayoutChild(child, layoutDirection); if (child instanceof BottomNavigationBar) { mViewRef = new WeakReference<>((BottomNavigationBar) child); } child.post(new Runnable() { @Override public void run() { mBottomNavHeight = child.getHeight(); } }); updateSnackBarPosition(parent, child, getSnackBarInstance(parent, child)); return super.onLayoutChild(parent, child, layoutDirection); } /////////////////////////////////////////////////////////////////////////// // SnackBar Handling /////////////////////////////////////////////////////////////////////////// @Override public boolean layoutDependsOn(CoordinatorLayout parent, V child, View dependency) { return isDependent(dependency) || super.layoutDependsOn(parent, child, dependency); } private boolean isDependent(View dependency) { return dependency instanceof Snackbar.SnackbarLayout; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View dependency) { if (isDependent(dependency)) { updateSnackBarPosition(parent, child, dependency); return false; } return super.onDependentViewChanged(parent, child, dependency); } private void updateSnackBarPosition(CoordinatorLayout parent, V child, View dependency) { updateSnackBarPosition(parent, child, dependency, child.getTranslationY() - child.getHeight()); } private void updateSnackBarPosition(CoordinatorLayout parent, V child, View dependency, float translationY) { if (dependency != null && dependency instanceof Snackbar.SnackbarLayout) { ViewCompat.animate(dependency).setInterpolator(INTERPOLATOR).setDuration(80).setStartDelay(0).translationY(translationY).start(); } } private Snackbar.SnackbarLayout getSnackBarInstance(CoordinatorLayout parent, V child) { final List<View> dependencies = parent.getDependencies(child); for (int i = 0, z = dependencies.size(); i < z; i++) { final View view = dependencies.get(i); if (view instanceof Snackbar.SnackbarLayout) { return (Snackbar.SnackbarLayout) view; } } return null; } /////////////////////////////////////////////////////////////////////////// // Auto Hide Handling /////////////////////////////////////////////////////////////////////////// @Override public void onNestedVerticalScrollUnconsumed(CoordinatorLayout coordinatorLayout, V child, @ScrollDirection int scrollDirection, int currentOverScroll, int totalScroll) { // Empty body } @Override public void onNestedVerticalPreScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dx, int dy, int[] consumed, @ScrollDirection int scrollDirection) { // handleDirection(child, scrollDirection); } @Override protected boolean onNestedDirectionFling(CoordinatorLayout coordinatorLayout, V child, View target, float velocityX, float velocityY, boolean consumed, @ScrollDirection int scrollDirection) { // if (consumed) { // handleDirection(child, scrollDirection); // } return consumed; } @Override public void onNestedVerticalScrollConsumed(CoordinatorLayout coordinatorLayout, V child, @ScrollDirection int scrollDirection, int currentOverScroll, int totalConsumedScroll) { handleDirection(coordinatorLayout, child, scrollDirection); } private void handleDirection(CoordinatorLayout parent, V child, int scrollDirection) { BottomNavigationBar bottomNavigationBar = mViewRef.get(); if (bottomNavigationBar != null && bottomNavigationBar.isAutoHideEnabled()) { if (scrollDirection == ScrollDirection.SCROLL_DIRECTION_DOWN && bottomNavigationBar.isHidden()) { updateSnackBarPosition(parent, child, getSnackBarInstance(parent, child), -mBottomNavHeight); bottomNavigationBar.show(); } else if (scrollDirection == ScrollDirection.SCROLL_DIRECTION_UP && !bottomNavigationBar.isHidden()) { updateSnackBarPosition(parent, child, getSnackBarInstance(parent, child), 0); bottomNavigationBar.hide(); } } } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/behaviour/BottomVerticalScrollBehavior.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
1,061
```java package com.ashokvarma.bottomnavigation.utils; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Point; import android.util.TypedValue; import android.view.WindowManager; /** * Class description : These are common utils and can be used for other projects as well * * @author ashokvarma * @version 1.0 * @since 19 Mar 2016 */ public class Utils { public static final int NO_COLOR = Color.TRANSPARENT; private Utils() { } /** * @param context used to get system services * @return screenWidth in pixels */ public static int getScreenWidth(Context context) { WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Point size = new Point(); wm.getDefaultDisplay().getSize(size); return size.x; } /** * This method can be extended to get all android attributes color, string, dimension ...etc * * @param context used to fetch android attribute * @param androidAttribute attribute codes like R.attr.colorAccent * @return in this case color of android attribute */ public static int fetchContextColor(Context context, int androidAttribute) { TypedValue typedValue = new TypedValue(); TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[]{androidAttribute}); int color = a.getColor(0, 0); a.recycle(); return color; } /** * @param context used to fetch display metrics * @param dp dp value * @return pixel value */ public static int dp2px(Context context, float dp) { float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); return Math.round(px); } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/utils/Utils.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
394
```java package com.ashokvarma.bottomnavigation.behaviour; import android.content.Context; import android.util.AttributeSet; import android.view.View; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.coordinatorlayout.widget.CoordinatorLayout; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Class description * * @author ashokvarma * @version 1.0 * @since 25 Mar 2016 */ public abstract class VerticalScrollingBehavior<V extends View> extends CoordinatorLayout.Behavior<V> { private int mTotalDyUnconsumed = -1; private int mTotalDyConsumed = -1; private int mTotalDy = -1; @ScrollDirection private int mScrollDirection = ScrollDirection.SCROLL_NONE; @ScrollDirection private int mPreScrollDirection = ScrollDirection.SCROLL_NONE; @ScrollDirection private int mConsumedScrollDirection = ScrollDirection.SCROLL_NONE; public VerticalScrollingBehavior(Context context, AttributeSet attrs) { super(context, attrs); } public VerticalScrollingBehavior() { super(); } @Retention(RetentionPolicy.SOURCE) @IntDef({ScrollDirection.SCROLL_DIRECTION_UP, ScrollDirection.SCROLL_DIRECTION_DOWN}) public @interface ScrollDirection { int SCROLL_DIRECTION_UP = 1; int SCROLL_DIRECTION_DOWN = -1; int SCROLL_NONE = 0; } /** * @return Scroll direction: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN, SCROLL_NONE */ @ScrollDirection public int getScrollDirection() { return mScrollDirection; } /** * @return ConsumedScroll direction: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN, SCROLL_NONE */ @ScrollDirection public int getConsumedScrollDirection() { return mConsumedScrollDirection; } /** * @return PreScroll direction: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN, SCROLL_NONE */ @ScrollDirection public int getPreScrollDirection() { return mPreScrollDirection; } @Override public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View directTargetChild, @NonNull View target, int nestedScrollAxes) { return (nestedScrollAxes & View.SCROLL_AXIS_VERTICAL) != 0; } // @Override // public void onNestedScrollAccepted(CoordinatorLayout coordinatorLayout, V child, View directTargetChild, View target, int nestedScrollAxes) { // super.onNestedScrollAccepted(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes); // } // // @Override // public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target) { // super.onStopNestedScroll(coordinatorLayout, child, target); // } @Override public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed); if (dyUnconsumed > 0 && mTotalDyUnconsumed < 0) { mTotalDyUnconsumed = 0; mScrollDirection = ScrollDirection.SCROLL_DIRECTION_UP; onNestedVerticalScrollUnconsumed(coordinatorLayout, child, mScrollDirection, dyConsumed, mTotalDyUnconsumed); } else if (dyUnconsumed < 0 && mTotalDyUnconsumed > 0) { mTotalDyUnconsumed = 0; mScrollDirection = ScrollDirection.SCROLL_DIRECTION_DOWN; onNestedVerticalScrollUnconsumed(coordinatorLayout, child, mScrollDirection, dyConsumed, mTotalDyUnconsumed); } mTotalDyUnconsumed += dyUnconsumed; if (dyConsumed > 0 && mTotalDyConsumed < 0) { mTotalDyConsumed = 0; mConsumedScrollDirection = ScrollDirection.SCROLL_DIRECTION_UP; onNestedVerticalScrollConsumed(coordinatorLayout, child, mConsumedScrollDirection, dyConsumed, mTotalDyConsumed); } else if (dyConsumed < 0 && mTotalDyConsumed > 0) { mTotalDyConsumed = 0; mConsumedScrollDirection = ScrollDirection.SCROLL_DIRECTION_DOWN; onNestedVerticalScrollConsumed(coordinatorLayout, child, mConsumedScrollDirection, dyConsumed, mTotalDyConsumed); } mTotalDyConsumed += dyConsumed; } @Override public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, int dx, int dy, @NonNull int[] consumed) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed); if (dy > 0 && mTotalDy < 0) { mTotalDy = 0; mPreScrollDirection = ScrollDirection.SCROLL_DIRECTION_UP; onNestedVerticalPreScroll(coordinatorLayout, child, target, dx, dy, consumed, mPreScrollDirection); } else if (dy < 0 && mTotalDy > 0) { mTotalDy = 0; mPreScrollDirection = ScrollDirection.SCROLL_DIRECTION_DOWN; onNestedVerticalPreScroll(coordinatorLayout, child, target, dx, dy, consumed, mPreScrollDirection); } mTotalDy += dy; } @Override public boolean onNestedFling(@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, float velocityX, float velocityY, boolean consumed) { super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed); return onNestedDirectionFling(coordinatorLayout, child, target, velocityX, velocityY, consumed , velocityY > 0 ? ScrollDirection.SCROLL_DIRECTION_UP : ScrollDirection.SCROLL_DIRECTION_DOWN); } /** * @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is * associated with * @param child the child view of the CoordinatorLayout this Behavior is associated with * @param scrollDirection Direction of the scroll: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN * @param currentOverScroll Unconsumed value, negative or positive based on the direction; * @param totalScroll Cumulative value for current direction (Unconsumed) */ public abstract void onNestedVerticalScrollUnconsumed(CoordinatorLayout coordinatorLayout, V child, @ScrollDirection int scrollDirection, int currentOverScroll, int totalScroll); /** * @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is * associated with * @param child the child view of the CoordinatorLayout this Behavior is associated with * @param scrollDirection Direction of the scroll: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN * @param currentOverScroll Unconsumed value, negative or positive based on the direction; * @param totalConsumedScroll Cumulative value for current direction (Unconsumed) */ public abstract void onNestedVerticalScrollConsumed(CoordinatorLayout coordinatorLayout, V child, @ScrollDirection int scrollDirection, int currentOverScroll, int totalConsumedScroll); /** * @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is * associated with * @param child the child view of the CoordinatorLayout this Behavior is associated with * @param target the descendant view of the CoordinatorLayout performing the nested scroll * @param dx the raw horizontal number of pixels that the user attempted to scroll * @param dy the raw vertical number of pixels that the user attempted to scroll * @param consumed out parameter. consumed[0] should be set to the distance of dx that * was consumed, consumed[1] should be set to the distance of dy that * was consumed * @param scrollDirection Direction of the scroll: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN */ public abstract void onNestedVerticalPreScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dx, int dy, int[] consumed, @ScrollDirection int scrollDirection); /** * @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is * associated with * @param child the child view of the CoordinatorLayout this Behavior is associated with * @param target the descendant view of the CoordinatorLayout performing the nested scroll * @param velocityX horizontal velocity of the attempted fling * @param velocityY vertical velocity of the attempted fling * @param consumed true if the nested child view consumed the fling * @param scrollDirection Direction of the scroll: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN * @return true if the Behavior consumed the fling */ protected abstract boolean onNestedDirectionFling(CoordinatorLayout coordinatorLayout, V child, View target, float velocityX, float velocityY, boolean consumed, @ScrollDirection int scrollDirection); // @Override // public boolean onNestedPreFling(CoordinatorLayout coordinatorLayout, V child, View target, float velocityX, float velocityY) { // return super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY); // } // // @Override // public WindowInsetsCompat onApplyWindowInsets(CoordinatorLayout coordinatorLayout, V child, WindowInsetsCompat insets) { // // return super.onApplyWindowInsets(coordinatorLayout, child, insets); // } // // @Override // public Parcelable onSaveInstanceState(CoordinatorLayout parent, V child) { // return super.onSaveInstanceState(parent, child); // } } ```
/content/code_sandbox/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/behaviour/VerticalScrollingBehavior.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
2,199
```kotlin package com.ashokvarma.bottomnavigation.sample import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Parcel import android.os.Parcelable import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.ashokvarma.bottomnavigation.BottomNavigationBar import com.ashokvarma.bottomnavigation.BottomNavigationItem import com.ashokvarma.bottomnavigation.ShapeBadgeItem import com.ashokvarma.bottomnavigation.TextBadgeItem import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import java.util.* class HomeActivity() : AppCompatActivity(), View.OnClickListener, CompoundButton.OnCheckedChangeListener, BottomNavigationBar.OnTabSelectedListener, AdapterView.OnItemSelectedListener, Parcelable { // Views private lateinit var bottomNavigationBar: BottomNavigationBar private lateinit var fabHome: FloatingActionButton private lateinit var modeSpinner: Spinner private lateinit var shapeSpinner: Spinner private lateinit var itemSpinner: Spinner private lateinit var bgSpinner: Spinner private lateinit var autoHide: CheckBox private lateinit var toggleHide: Button private lateinit var toggleBadge: Button private lateinit var message: TextView private lateinit var fragment1: TextFragment private lateinit var fragment2: TextFragment private lateinit var fragment3: TextFragment private lateinit var fragment4: TextFragment private lateinit var fragment5: TextFragment private lateinit var fragment6: TextFragment // Variables private var lastSelectedPosition = 0 private lateinit var numberBadgeItem: TextBadgeItem private lateinit var shapeBadgeItem: ShapeBadgeItem constructor(parcel: Parcel) : this() { lastSelectedPosition = parcel.readInt() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) // All late init's bottomNavigationBar = findViewById(R.id.bottom_navigation_bar) fabHome = findViewById(R.id.fab_home) modeSpinner = findViewById(R.id.mode_spinner) bgSpinner = findViewById(R.id.bg_spinner) shapeSpinner = findViewById(R.id.shape_spinner) itemSpinner = findViewById(R.id.item_spinner) autoHide = findViewById(R.id.auto_hide) toggleHide = findViewById(R.id.toggle_hide) toggleBadge = findViewById(R.id.toggle_badge) message = findViewById(R.id.message) fragment1 = newTextFragmentInstance(getString(R.string.para1)) fragment2 = newTextFragmentInstance(getString(R.string.para2)) fragment3 = newTextFragmentInstance(getString(R.string.para3)) fragment4 = newTextFragmentInstance(getString(R.string.para4)) fragment5 = newTextFragmentInstance(getString(R.string.para5)) fragment6 = newTextFragmentInstance(getString(R.string.para6)) numberBadgeItem = TextBadgeItem() .setBorderWidth(4) .setBackgroundColorResource(R.color.blue) .setText("0") .setHideOnSelect(autoHide.isChecked) shapeBadgeItem = ShapeBadgeItem() .setShapeColorResource(R.color.teal) .setGravity(Gravity.TOP or Gravity.END) .setHideOnSelect(autoHide.isChecked) // adapters val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, Arrays.asList("MODE_DEFAULT", "MODE_FIXED", "MODE_SHIFTING", "MODE_FIXED_NO_TITLE", "MODE_SHIFTING_NO_TITLE")) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) modeSpinner.adapter = adapter modeSpinner.setSelection(2) val itemAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, Arrays.asList("3 items", "4 items", "5 items")) itemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) itemSpinner.adapter = itemAdapter itemSpinner.setSelection(2) val shapeAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, Arrays.asList("SHAPE_OVAL", "SHAPE_RECTANGLE", "SHAPE_HEART", "SHAPE_STAR_3_VERTICES", "SHAPE_STAR_4_VERTICES", "SHAPE_STAR_5_VERTICES", "SHAPE_STAR_6_VERTICES")) shapeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) shapeSpinner.adapter = shapeAdapter shapeSpinner.setSelection(5) val bgAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, Arrays.asList("BACKGROUND_STYLE_DEFAULT", "BACKGROUND_STYLE_STATIC", "BACKGROUND_STYLE_RIPPLE")) bgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) bgSpinner.adapter = bgAdapter bgSpinner.setSelection(1) // listeners modeSpinner.onItemSelectedListener = this bgSpinner.onItemSelectedListener = this shapeSpinner.onItemSelectedListener = this itemSpinner.onItemSelectedListener = this autoHide.setOnCheckedChangeListener(this) toggleHide.setOnClickListener(this) toggleBadge.setOnClickListener(this) fabHome.setOnClickListener(this) bottomNavigationBar.setTabSelectedListener(this) } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.home_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_github -> { val url = "path_to_url" val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse(url) startActivity(i) return true } } return super.onOptionsItemSelected(item) } override fun onClick(v: View) { when (v.id) { R.id.toggle_hide -> bottomNavigationBar.toggle() R.id.toggle_badge -> { numberBadgeItem.toggle() shapeBadgeItem.toggle() } R.id.fab_home -> { val snackbar = Snackbar.make(message, "Fab Clicked", Snackbar.LENGTH_LONG) snackbar.setAction("dismiss") { snackbar.dismiss() } snackbar.show() } } } override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) { refresh() } override fun onNothingSelected(adapterView: AdapterView<*>) { } override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) { refresh() } private fun refresh() { numberBadgeItem .show() .setText("" + lastSelectedPosition) .setHideOnSelect(autoHide.isChecked) shapeBadgeItem .show() .setShape(shapeSpinner.selectedItemPosition) .setHideOnSelect(autoHide.isChecked) bottomNavigationBar.clearAll() // bottomNavigationBar.setFab(fabHome, BottomNavigationBar.FAB_BEHAVIOUR_TRANSLATE_AND_STICK); bottomNavigationBar.setFab(fabHome) bottomNavigationBar.setMode(modeSpinner.selectedItemPosition) bottomNavigationBar.setBackgroundStyle(bgSpinner.selectedItemPosition) when (itemSpinner.selectedItemPosition) { 0 -> { bottomNavigationBar .addItem(BottomNavigationItem(R.drawable.ic_location_on_white_24dp, "Nearby").setActiveColorResource(R.color.orange).setBadgeItem(numberBadgeItem)) .addItem(BottomNavigationItem(R.drawable.ic_find_replace_white_24dp, "Find").setActiveColorResource(R.color.teal)) .addItem(BottomNavigationItem(R.drawable.ic_favorite_white_24dp, "Categories").setActiveColorResource(R.color.blue).setBadgeItem(shapeBadgeItem)) .initialise() bottomNavigationBar.selectTab(if (lastSelectedPosition > 2) 2 else lastSelectedPosition, true) } 1 -> { bottomNavigationBar .addItem(BottomNavigationItem(R.drawable.ic_home_white_24dp, "Home").setActiveColorResource(R.color.orange).setBadgeItem(numberBadgeItem)) .addItem(BottomNavigationItem(R.drawable.ic_book_white_24dp, "Books").setActiveColorResource(R.color.teal)) .addItem(BottomNavigationItem(R.drawable.ic_music_note_white_24dp, "Music").setActiveColorResource(R.color.blue).setBadgeItem(shapeBadgeItem)) .addItem(BottomNavigationItem(R.drawable.ic_tv_white_24dp, "Movies & TV").setActiveColorResource(R.color.brown)) .initialise() bottomNavigationBar.selectTab(if (lastSelectedPosition > 3) 3 else lastSelectedPosition, true) } 2 -> { bottomNavigationBar .addItem(BottomNavigationItem(R.drawable.ic_home_white_24dp, "Home").setActiveColorResource(R.color.orange).setBadgeItem(numberBadgeItem)) .addItem(BottomNavigationItem(R.drawable.ic_book_white_24dp, "Books").setActiveColorResource(R.color.teal)) .addItem(BottomNavigationItem(R.drawable.ic_music_note_white_24dp, "Music").setActiveColorResource(R.color.blue).setBadgeItem(shapeBadgeItem)) .addItem(BottomNavigationItem(R.drawable.ic_tv_white_24dp, "Movies & TV").setActiveColorResource(R.color.brown)) .addItem(BottomNavigationItem(R.drawable.ic_videogame_asset_white_24dp, "Games").setActiveColorResource(R.color.grey)) .initialise() bottomNavigationBar.selectTab(lastSelectedPosition, true) } } } override fun onTabSelected(position: Int) { lastSelectedPosition = position setMessageText("${position + 1} Tab Selected") numberBadgeItem.setText((position + 1).toString()) replaceFragments(position) } override fun onTabUnselected(position: Int) {} override fun onTabReselected(position: Int) { setMessageText("${position + 1} Tab Reselected") } private fun setMessageText(messageText: String) { message.text = messageText } private fun replaceFragments(position: Int) { supportFragmentManager.beginTransaction().apply { when (position) { 0 -> replace(R.id.home_activity_frag_container, fragment1) 1 -> replace(R.id.home_activity_frag_container, fragment2) 2 -> replace(R.id.home_activity_frag_container, fragment3) 3 -> replace(R.id.home_activity_frag_container, fragment4) 4 -> replace(R.id.home_activity_frag_container, fragment5) else -> replace(R.id.home_activity_frag_container, fragment6) } }.commitAllowingStateLoss() } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeInt(lastSelectedPosition) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<HomeActivity> { override fun createFromParcel(parcel: Parcel): HomeActivity { return HomeActivity(parcel) } override fun newArray(size: Int): Array<HomeActivity?> { return arrayOfNulls(size) } } } ```
/content/code_sandbox/sample/src/main/java/com/ashokvarma/bottomnavigation/sample/HomeActivity.kt
kotlin
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
2,285
```java package com.ashokvarma.bottomnavigation.sample; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Spinner; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.ashokvarma.bottomnavigation.BottomNavigationBar; import com.ashokvarma.bottomnavigation.BottomNavigationItem; import com.ashokvarma.bottomnavigation.ShapeBadgeItem; import com.ashokvarma.bottomnavigation.TextBadgeItem; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; /** * Class description * * @author ashokvarma * @version 1.0 * @since 10 Jul 2017 */ public class HomeActivityJava extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, BottomNavigationBar.OnTabSelectedListener, AdapterView.OnItemSelectedListener { BottomNavigationBar bottomNavigationBar; FloatingActionButton fabHome; Spinner modeSpinner; Spinner shapeSpinner; Spinner itemSpinner; Spinner bgSpinner; CheckBox autoHide; Button toggleHide; Button toggleBadge; TextView message; TextView scrollableText; int lastSelectedPosition = 0; TextFragment fragment1; TextFragment fragment2; TextFragment fragment3; TextFragment fragment4; TextFragment fragment5; TextFragment fragment6; @Nullable TextBadgeItem numberBadgeItem; @Nullable ShapeBadgeItem shapeBadgeItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); bottomNavigationBar = findViewById(R.id.bottom_navigation_bar); fabHome = findViewById(R.id.fab_home); modeSpinner = findViewById(R.id.mode_spinner); bgSpinner = findViewById(R.id.bg_spinner); shapeSpinner = findViewById(R.id.shape_spinner); itemSpinner = findViewById(R.id.item_spinner); autoHide = findViewById(R.id.auto_hide); toggleHide = findViewById(R.id.toggle_hide); toggleBadge = findViewById(R.id.toggle_badge); message = findViewById(R.id.message); fragment1 = TextFragmentKt.newTextFragmentInstance(getString(R.string.para1)); fragment2 = TextFragmentKt.newTextFragmentInstance(getString(R.string.para2)); fragment3 = TextFragmentKt.newTextFragmentInstance(getString(R.string.para3)); fragment4 = TextFragmentKt.newTextFragmentInstance(getString(R.string.para4)); fragment5 = TextFragmentKt.newTextFragmentInstance(getString(R.string.para5)); fragment6 = TextFragmentKt.newTextFragmentInstance(getString(R.string.para6)); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]{"MODE_DEFAULT", "MODE_FIXED", "MODE_SHIFTING", "MODE_FIXED_NO_TITLE", "MODE_SHIFTING_NO_TITLE"}); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); modeSpinner.setAdapter(adapter); modeSpinner.setSelection(2); ArrayAdapter<String> itemAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]{"3 items", "4 items", "5 items"}); itemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); itemSpinner.setAdapter(itemAdapter); itemSpinner.setSelection(2); ArrayAdapter<String> shapeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]{"SHAPE_OVAL", "SHAPE_RECTANGLE", "SHAPE_HEART", "SHAPE_STAR_3_VERTICES", "SHAPE_STAR_4_VERTICES", "SHAPE_STAR_5_VERTICES", "SHAPE_STAR_6_VERTICES"}); shapeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); shapeSpinner.setAdapter(shapeAdapter); shapeSpinner.setSelection(5); ArrayAdapter<String> bgAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]{"BACKGROUND_STYLE_DEFAULT", "BACKGROUND_STYLE_STATIC", "BACKGROUND_STYLE_RIPPLE"}); bgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); bgSpinner.setAdapter(bgAdapter); bgSpinner.setSelection(1); modeSpinner.setOnItemSelectedListener(this); bgSpinner.setOnItemSelectedListener(this); shapeSpinner.setOnItemSelectedListener(this); itemSpinner.setOnItemSelectedListener(this); autoHide.setOnCheckedChangeListener(this); toggleHide.setOnClickListener(this); toggleBadge.setOnClickListener(this); fabHome.setOnClickListener(this); bottomNavigationBar.setTabSelectedListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.home_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_github: String url = "path_to_url"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.toggle_hide: if (bottomNavigationBar != null) { bottomNavigationBar.toggle(); } break; case R.id.toggle_badge: if (numberBadgeItem != null) { numberBadgeItem.toggle(); } if (shapeBadgeItem != null) { shapeBadgeItem.toggle(); } break; case R.id.fab_home: final Snackbar snackbar = Snackbar.make(message, "Fab Clicked", Snackbar.LENGTH_LONG); snackbar.setAction("dismiss", new View.OnClickListener() { @Override public void onClick(View v) { snackbar.dismiss(); } }); snackbar.show(); break; } } @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { refresh(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { refresh(); } private void refresh() { bottomNavigationBar.clearAll(); // bottomNavigationBar.setFab(fabHome, BottomNavigationBar.FAB_BEHAVIOUR_TRANSLATE_AND_STICK); bottomNavigationBar.setFab(fabHome); setScrollableText(lastSelectedPosition); numberBadgeItem = new TextBadgeItem() .setBorderWidth(4) .setBackgroundColorResource(R.color.blue) .setText("" + lastSelectedPosition) .setHideOnSelect(autoHide.isChecked()); shapeBadgeItem = new ShapeBadgeItem() .setShape(shapeSpinner.getSelectedItemPosition()) .setShapeColorResource(R.color.teal) .setGravity(Gravity.TOP | Gravity.END) .setHideOnSelect(autoHide.isChecked()); bottomNavigationBar.setMode(modeSpinner.getSelectedItemPosition()); bottomNavigationBar.setBackgroundStyle(bgSpinner.getSelectedItemPosition()); switch (itemSpinner.getSelectedItemPosition()) { case 0: bottomNavigationBar .addItem(new BottomNavigationItem(R.drawable.ic_location_on_white_24dp, "Nearby").setActiveColorResource(R.color.orange).setBadgeItem(numberBadgeItem)) .addItem(new BottomNavigationItem(R.drawable.ic_find_replace_white_24dp, "Find").setActiveColorResource(R.color.teal)) .addItem(new BottomNavigationItem(R.drawable.ic_favorite_white_24dp, "Categories").setActiveColorResource(R.color.blue).setBadgeItem(shapeBadgeItem)) .setFirstSelectedPosition(lastSelectedPosition > 2 ? 2 : lastSelectedPosition) .initialise(); break; case 1: bottomNavigationBar .addItem(new BottomNavigationItem(R.drawable.ic_home_white_24dp, "Home").setActiveColorResource(R.color.orange).setBadgeItem(numberBadgeItem)) .addItem(new BottomNavigationItem(R.drawable.ic_book_white_24dp, "Books").setActiveColorResource(R.color.teal)) .addItem(new BottomNavigationItem(R.drawable.ic_music_note_white_24dp, "Music").setActiveColorResource(R.color.blue).setBadgeItem(shapeBadgeItem)) .addItem(new BottomNavigationItem(R.drawable.ic_tv_white_24dp, "Movies & TV").setActiveColorResource(R.color.brown)) .setFirstSelectedPosition(lastSelectedPosition > 3 ? 3 : lastSelectedPosition) .initialise(); break; case 2: bottomNavigationBar .addItem(new BottomNavigationItem(R.drawable.ic_home_white_24dp, "Home").setActiveColorResource(R.color.orange).setBadgeItem(numberBadgeItem)) .addItem(new BottomNavigationItem(R.drawable.ic_book_white_24dp, "Books").setActiveColorResource(R.color.teal)) .addItem(new BottomNavigationItem(R.drawable.ic_music_note_white_24dp, "Music").setActiveColorResource(R.color.blue).setBadgeItem(shapeBadgeItem)) .addItem(new BottomNavigationItem(R.drawable.ic_tv_white_24dp, "Movies & TV").setActiveColorResource(R.color.brown)) .addItem(new BottomNavigationItem(R.drawable.ic_videogame_asset_white_24dp, "Games").setActiveColorResource(R.color.grey)) .setFirstSelectedPosition(lastSelectedPosition) .initialise(); break; } } @Override public void onTabSelected(int position) { lastSelectedPosition = position; setMessageText(position + " Tab Selected"); if (numberBadgeItem != null) { numberBadgeItem.setText(Integer.toString(position)); } setScrollableText(position); } @Override public void onTabUnselected(int position) { } @Override public void onTabReselected(int position) { setMessageText(position + " Tab Reselected"); } private void setMessageText(String messageText) { message.setText(messageText); } private void setScrollableText(int position) { switch (position) { case 0: getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_frag_container, fragment1).commitAllowingStateLoss(); break; case 1: getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_frag_container, fragment2).commitAllowingStateLoss(); break; case 2: getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_frag_container, fragment3).commitAllowingStateLoss(); break; case 3: getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_frag_container, fragment4).commitAllowingStateLoss(); break; case 4: getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_frag_container, fragment5).commitAllowingStateLoss(); break; default: getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_frag_container, fragment6).commitAllowingStateLoss(); break; } } } ```
/content/code_sandbox/sample/src/main/java/com/ashokvarma/bottomnavigation/sample/HomeActivityJava.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
2,308
```kotlin package com.ashokvarma.bottomnavigation.sample import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment /** * Class description * @author ashokvarma * * * @version 1.0 * * * @see * @since 10 Jul 2017 */ internal const val KEY_MESSAGE = "message" fun newTextFragmentInstance(message: String): TextFragment { val textFragment = TextFragment() val args = Bundle() args.putString(KEY_MESSAGE, message) textFragment.arguments = args return textFragment } class TextFragment : Fragment() { private var msg: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) msg = arguments?.getString(KEY_MESSAGE, "") } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_text, container, false) (view.findViewById<TextView>(R.id.tf_textview)).text = msg ?: "" return view } } ```
/content/code_sandbox/sample/src/main/java/com/ashokvarma/bottomnavigation/sample/TextFragment.kt
kotlin
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
240
```java package com.ashokvarma.sample; import android.support.test.rule.ActivityTestRule; import com.ashokvarma.bottomnavigation.sample.HomeActivity; import com.ashokvarma.bottomnavigation.sample.R; import org.junit.Rule; import org.junit.Test; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.matcher.ViewMatchers.isRoot; import static android.support.test.espresso.matcher.ViewMatchers.withId; /** * Class description * * @author ashokvarma * @version 1.0 * @see * @since 26 May 2016 */ public class HomeScreenTest { @Rule public ActivityTestRule<HomeActivity> mHomeActivityTestRule = new ActivityTestRule<>(HomeActivity.class); @Test public void scrollHome_test() throws Exception { onView(withId(R.id.nested_scroll_view)) .perform(Utils.swipeUpSlow()); onView(isRoot()).perform(Utils.waitId(R.id.nested_scroll_view, 150 * 1000)); onView(withId(R.id.nested_scroll_view)) .perform(Utils.swipeDownSlow()); onView(withId(R.id.auto_hide)) .perform(click()); onView(isRoot()).perform(Utils.waitId(R.id.nested_scroll_view, 150 * 1000)); } } ```
/content/code_sandbox/sample/src/androidTest/java/com/ashokvarma/sample/HomeScreenTest.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
285
```java package com.ashokvarma.sample; import android.view.View; import androidx.test.espresso.PerformException; import androidx.test.espresso.UiController; import androidx.test.espresso.ViewAction; import androidx.test.espresso.action.CoordinatesProvider; import androidx.test.espresso.action.GeneralLocation; import androidx.test.espresso.action.GeneralSwipeAction; import androidx.test.espresso.action.Press; import androidx.test.espresso.action.Swipe; import androidx.test.espresso.util.HumanReadables; import androidx.test.espresso.util.TreeIterables; import org.hamcrest.Matcher; import java.util.concurrent.TimeoutException; import static androidx.test.espresso.action.ViewActions.actionWithAssertions; import static androidx.test.espresso.matcher.ViewMatchers.isRoot; import static androidx.test.espresso.matcher.ViewMatchers.withId; /** * Class description * * @author ashokvarma * @version 1.0 * @see * @since 26 May 2016 */ public class Utils { /** * The distance of a swipe's start position from the view's edge, in terms of the view's length. * We do not start the swipe exactly on the view's edge, but somewhat more inward, since swiping * from the exact edge may behave in an unexpected way (e.g. may open a navigation drawer). */ private static final float EDGE_FUZZ_FACTOR = 0.083f; /** * Perform action of waiting for a specific view id. */ public static ViewAction waitId(final int viewId, final long millis) { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isRoot(); } @Override public String getDescription() { return "wait for a specific view with id <" + viewId + "> during " + millis + " millis."; } @Override public void perform(final UiController uiController, final View view) { uiController.loopMainThreadUntilIdle(); final long startTime = System.currentTimeMillis(); final long endTime = startTime + millis; final Matcher<View> viewMatcher = withId(viewId); do { for (View child : TreeIterables.breadthFirstViewTraversal(view)) { // found view with required ID if (viewMatcher.matches(child)) { return; } } uiController.loopMainThreadForAtLeast(50); } while (System.currentTimeMillis() < endTime); // timeout happens throw new PerformException.Builder() .withActionDescription(this.getDescription()) .withViewDescription(HumanReadables.describe(view)) .withCause(new TimeoutException()) .build(); } }; } /** * Returns an action that performs a swipe right-to-left across the vertical center of the * view. The swipe doesn't start at the very edge of the view, but is a bit offset.<br> * <br> * View constraints: * <ul> * <li>must be displayed on screen * <ul> */ public static ViewAction swipeLeftSlow() { return actionWithAssertions(new GeneralSwipeAction(Swipe.SLOW, translate(GeneralLocation.CENTER_RIGHT, -EDGE_FUZZ_FACTOR, 0), GeneralLocation.CENTER_LEFT, Press.FINGER)); } /** * Returns an action that performs a swipe left-to-right across the vertical center of the * view. The swipe doesn't start at the very edge of the view, but is a bit offset.<br> * <br> * View constraints: * <ul> * <li>must be displayed on screen * <ul> */ public static ViewAction swipeRightSlow() { return actionWithAssertions(new GeneralSwipeAction(Swipe.SLOW, translate(GeneralLocation.CENTER_LEFT, EDGE_FUZZ_FACTOR, 0), GeneralLocation.CENTER_RIGHT, Press.FINGER)); } /** * Returns an action that performs a swipe top-to-bottom across the horizontal center of the view. * The swipe doesn't start at the very edge of the view, but has a bit of offset.<br> * <br> * View constraints: * <ul> * <li>must be displayed on screen * <ul> */ public static ViewAction swipeDownSlow() { return actionWithAssertions(new GeneralSwipeAction(Swipe.SLOW, translate(GeneralLocation.TOP_CENTER, 0, EDGE_FUZZ_FACTOR), GeneralLocation.BOTTOM_CENTER, Press.FINGER)); } /** * Returns an action that performs a swipe bottom-to-top across the horizontal center of the view. * The swipe doesn't start at the very edge of the view, but has a bit of offset.<br> * <br> * View constraints: * <ul> * <li>must be displayed on screen * <ul> */ public static ViewAction swipeUpSlow() { return actionWithAssertions(new GeneralSwipeAction(Swipe.SLOW, translate(GeneralLocation.BOTTOM_CENTER, 0, -EDGE_FUZZ_FACTOR), GeneralLocation.TOP_CENTER, Press.FINGER)); } /** * Translates the given coordinates by the given distances. The distances are given in term * of the view's size -- 1.0 means to translate by an amount equivalent to the view's length. */ static CoordinatesProvider translate(final CoordinatesProvider coords, final float dx, final float dy) { return new CoordinatesProvider() { @Override public float[] calculateCoordinates(View view) { float xy[] = coords.calculateCoordinates(view); xy[0] += dx * view.getWidth(); xy[1] += dy * view.getHeight(); return xy; } }; } } ```
/content/code_sandbox/sample/src/androidTest/java/com/ashokvarma/sample/Utils.java
java
2016-03-19T19:19:30
2024-08-15T10:59:01
BottomNavigation
Ashok-Varma/BottomNavigation
4,353
1,208
```python import conftest # Add root path to sys.path from PathPlanning.VisibilityRoadMap import visibility_road_map as m def test1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_voronoi_road_map_planner.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
61
```python import conftest from PathPlanning.BugPlanning import bug as m def test_1(): m.show_animation = False m.main(bug_0=True, bug_1=True, bug_2=True) if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_bug.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
66
```python import conftest import numpy as np from PathPlanning.DynamicWindowApproach import dynamic_window_approach as m def test_main1(): m.show_animation = False m.main(gx=1.0, gy=1.0) def test_main2(): m.show_animation = False m.main(gx=1.0, gy=1.0, robot_type=m.RobotType.rectangle) def test_stuck_main(): m.show_animation = False # adjust cost m.config.to_goal_cost_gain = 0.2 m.config.obstacle_cost_gain = 2.0 # obstacles and goals for stuck condition m.config.ob = -1 * np.array([[-1.0, -1.0], [0.0, 2.0], [2.0, 6.0], [2.0, 8.0], [3.0, 9.27], [3.79, 9.39], [7.25, 8.97], [7.0, 2.0], [3.0, 4.0], [6.0, 5.0], [3.5, 5.8], [6.0, 9.0], [8.8, 9.0], [5.0, 9.0], [7.5, 3.0], [9.0, 8.0], [5.8, 4.4], [12.0, 12.0], [3.0, 2.0], [13.0, 13.0] ]) m.main(gx=-5.0, gy=-7.0) if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_dynamic_window_approach.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
409
```toml line-length = 88 select = ["F", "E", "W", "UP"] ignore = ["E501", "E741", "E402"] exclude = [ ] # Assume Python 3.11 target-version = "py312" [per-file-ignores] [mccabe] # Unlike Flake8, default to a complexity level of 10. max-complexity = 10 [pydocstyle] convention = "numpy" ```
/content/code_sandbox/ruff.toml
toml
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
98
```python import conftest from Localization.cubature_kalman_filter import cubature_kalman_filter as m def test1(): m.show_final = False m.show_animation = False m.show_ellipse = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_cubature_kalman_filter.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
73
```python import conftest # Add root path to sys.path from PathPlanning.LQRPlanner import lqr_planner as m def test_1(): m.SHOW_ANIMATION = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_LQR_planner.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
65
```python import conftest # Add root path to sys.path from PathPlanning.QuinticPolynomialsPlanner import quintic_polynomials_planner as m def test1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_quintic_polynomials_planner.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
67
```python import conftest # Add root path to sys.path import os import matplotlib.pyplot as plt from PathPlanning.WavefrontCPP import wavefront_coverage_path_planner wavefront_coverage_path_planner.do_animation = False def wavefront_cpp(img, start, goal): num_free = 0 for i in range(img.shape[0]): for j in range(img.shape[1]): num_free += 1 - img[i][j] DT = wavefront_coverage_path_planner.transform( img, goal, transform_type='distance') DT_path = wavefront_coverage_path_planner.wavefront(DT, start, goal) assert len(DT_path) == num_free # assert complete coverage PT = wavefront_coverage_path_planner.transform( img, goal, transform_type='path', alpha=0.01) PT_path = wavefront_coverage_path_planner.wavefront(PT, start, goal) assert len(PT_path) == num_free # assert complete coverage def test_wavefront_CPP_1(): img_dir = os.path.dirname( os.path.abspath(__file__)) + "/../PathPlanning/WavefrontCPP" img = plt.imread(os.path.join(img_dir, 'map', 'test.png')) img = 1 - img start = (43, 0) goal = (0, 0) wavefront_cpp(img, start, goal) def test_wavefront_CPP_2(): img_dir = os.path.dirname( os.path.abspath(__file__)) + "/../PathPlanning/WavefrontCPP" img = plt.imread(os.path.join(img_dir, 'map', 'test_2.png')) img = 1 - img start = (10, 0) goal = (10, 40) wavefront_cpp(img, start, goal) def test_wavefront_CPP_3(): img_dir = os.path.dirname( os.path.abspath(__file__)) + "/../PathPlanning/WavefrontCPP" img = plt.imread(os.path.join(img_dir, 'map', 'test_3.png')) img = 1 - img start = (0, 0) goal = (30, 30) wavefront_cpp(img, start, goal) if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_wavefront_coverage_path_planner.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
501
```python import conftest from PathTracking.cgmres_nmpc import cgmres_nmpc as m def test1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_cgmres_nmpc.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
58
```python import conftest # Add root path to sys.path from ArmNavigation.two_joint_arm_to_point_control \ import two_joint_arm_to_point_control as m def test1(): m.show_animation = False m.animation() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_two_joint_arm_to_point_control.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
68
```python import conftest # Add root path to sys.path from Localization.unscented_kalman_filter import unscented_kalman_filter as m def test1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_unscented_kalman_filter.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
68
```python import conftest # Add root path to sys.path from Control.move_to_pose import move_to_pose as m def test_1(): m.show_animation = False m.main() def test_2(): """ This unit test tests the move_to_pose.py program for a MAX_LINEAR_SPEED and MAX_ANGULAR_SPEED """ m.show_animation = False m.MAX_LINEAR_SPEED = 11 m.MAX_ANGULAR_SPEED = 5 m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_move_to_pose.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
125
```python import conftest # Add root path to sys.path from PathPlanning.RRTStar import rrt_star as m def test1(): m.show_animation = False m.main() def test_no_obstacle(): obstacle_list = [] # Set Initial parameters rrt_star = m.RRTStar(start=[0, 0], goal=[6, 10], rand_area=[-2, 15], obstacle_list=obstacle_list) path = rrt_star.planning(animation=False) assert path is not None def test_no_obstacle_and_robot_radius(): obstacle_list = [] # Set Initial parameters rrt_star = m.RRTStar(start=[0, 0], goal=[6, 10], rand_area=[-2, 15], obstacle_list=obstacle_list, robot_radius=0.8) path = rrt_star.planning(animation=False) assert path is not None if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_rrt_star.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
225
```python import conftest from PathPlanning.BreadthFirstSearch import breadth_first_search as m def test_1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_breadth_first_search.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
55
```python import conftest from Control.inverted_pendulum import inverted_pendulum_lqr_control as m def test_1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_inverted_pendulum_lqr_control.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
58
```yaml os: Visual Studio 2022 environment: global: # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the # /E:ON and /V:ON options are not enabled in the batch script intepreter # See: path_to_url CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\appveyor\\run_with_env.cmd" matrix: - PYTHON_DIR: C:\Python310-x64 branches: only: - master init: - "ECHO %PYTHON_DIR%" install: # If there is a newer build queued for the same PR, cancel this one. # The AppVeyor 'rollout builds' option is supposed to serve the same # purpose but it is problematic because it tends to cancel builds pushed # directly to master instead of just PR builds (or the converse). # credits: JuliaLang developers. - ps: if ($env:APPVEYOR_PULL_REQUEST_NUMBER -and $env:APPVEYOR_BUILD_NUMBER -ne ((Invoke-RestMethod ` path_to_url | ` Where-Object pullRequestId -eq $env:APPVEYOR_PULL_REQUEST_NUMBER)[0].buildNumber) { ` throw "There are newer queued builds for this pull request, failing early." } - ECHO "Filesystem root:" - ps: "ls \"C:/\"" # Prepend newly installed Python to the PATH of this build (this cannot be # done from inside the powershell script as it would require to restart # the parent CMD process). - SET PATH=%PYTHON_DIR%;%PYTHON_DIR%\\Scripts;%PATH% - SET PATH=%PYTHON%;%PYTHON%\Scripts;%PYTHON%\Library\bin;%PATH% - SET PATH=%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin - "python -m pip install --upgrade pip" - "python -m pip install -r requirements/requirements.txt" - "python -m pip install pytest-xdist" # Check that we have the expected version and architecture for Python - "python --version" - "python -c \"import struct; print(struct.calcsize('P') * 8)\"" build: off test_script: - "pytest tests -n auto -Werror --durations=0" ```
/content/code_sandbox/appveyor.yml
yaml
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
525
```python import conftest from PathPlanning.DStarLite import d_star_lite as m def test_1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_d_star_lite.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
53
```python import conftest # Add root path to sys.path from ArmNavigation.rrt_star_seven_joint_arm_control \ import rrt_star_seven_joint_arm_control as m def test1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_rrt_star_seven_joint_arm.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
73
```python import conftest # Add root path to sys.path from Localization.particle_filter import particle_filter as m def test_1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_particle_filter.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
59
```python import conftest from AerialNavigation.drone_3d_trajectory_following \ import drone_3d_trajectory_following as m def test1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_drone_3d_trajectory_following.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
64
```python import conftest from PathPlanning.GridBasedSweepCPP \ import grid_based_sweep_coverage_path_planner grid_based_sweep_coverage_path_planner.do_animation = False RIGHT = grid_based_sweep_coverage_path_planner. \ SweepSearcher.MovingDirection.RIGHT LEFT = grid_based_sweep_coverage_path_planner. \ SweepSearcher.MovingDirection.LEFT UP = grid_based_sweep_coverage_path_planner. \ SweepSearcher.SweepDirection.UP DOWN = grid_based_sweep_coverage_path_planner. \ SweepSearcher.SweepDirection.DOWN def test_planning1(): ox = [0.0, 20.0, 50.0, 100.0, 130.0, 40.0, 0.0] oy = [0.0, -20.0, 0.0, 30.0, 60.0, 80.0, 0.0] resolution = 5.0 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=RIGHT, sweeping_direction=DOWN, ) assert len(px) >= 5 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=LEFT, sweeping_direction=DOWN, ) assert len(px) >= 5 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=RIGHT, sweeping_direction=UP, ) assert len(px) >= 5 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=RIGHT, sweeping_direction=UP, ) assert len(px) >= 5 def test_planning2(): ox = [0.0, 50.0, 50.0, 0.0, 0.0] oy = [0.0, 0.0, 30.0, 30.0, 0.0] resolution = 1.3 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=RIGHT, sweeping_direction=DOWN, ) assert len(px) >= 5 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=LEFT, sweeping_direction=DOWN, ) assert len(px) >= 5 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=RIGHT, sweeping_direction=UP, ) assert len(px) >= 5 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=RIGHT, sweeping_direction=DOWN, ) assert len(px) >= 5 def test_planning3(): ox = [0.0, 20.0, 50.0, 200.0, 130.0, 40.0, 0.0] oy = [0.0, -80.0, 0.0, 30.0, 60.0, 80.0, 0.0] resolution = 5.1 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=RIGHT, sweeping_direction=DOWN, ) assert len(px) >= 5 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=LEFT, sweeping_direction=DOWN, ) assert len(px) >= 5 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=RIGHT, sweeping_direction=UP, ) assert len(px) >= 5 px, py = grid_based_sweep_coverage_path_planner.planning( ox, oy, resolution, moving_direction=RIGHT, sweeping_direction=DOWN, ) assert len(px) >= 5 if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_grid_based_sweep_coverage_path_planner.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
943
```python import os import subprocess import conftest SUBPACKAGE_LIST = [ "AerialNavigation", "ArmNavigation", "Bipedal", "Control", "Localization", "Mapping", "PathPlanning", "PathTracking", "SLAM", ] def run_mypy(dir_name, project_path, config_path): res = subprocess.run( ['mypy', '--config-file', config_path, '-p', dir_name], cwd=project_path, stdout=subprocess.PIPE, encoding='utf-8') return res.returncode, res.stdout def test(): project_dir_path = os.path.dirname( os.path.dirname(os.path.abspath(__file__))) print(f"{project_dir_path=}") config_path = os.path.join(project_dir_path, "mypy.ini") print(f"{config_path=}") for sub_package_name in SUBPACKAGE_LIST: rc, errors = run_mypy(sub_package_name, project_dir_path, config_path) if errors: print(errors) else: print("No lint errors found.") assert rc == 0 if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_mypy_type_check.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
259
```python import conftest # Add root path to sys.path from PathTracking.stanley_controller import stanley_controller as m def test1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_stanley_controller.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
61
```python import conftest from PathPlanning.FrenetOptimalTrajectory import frenet_optimal_trajectory as m def test1(): m.show_animation = False m.SIM_LOOP = 5 m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_frenet_optimal_trajectory.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
67
```shell #!/usr/bin/env bash echo "Run test suites! " # === pytest based test runner === # -Werror: warning as error # --durations=0: show ranking of test durations # -l (--showlocals); show local variables when test failed pytest tests -l -Werror --durations=0 ```
/content/code_sandbox/runtests.sh
shell
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
71
```python import conftest # Add root path to sys.path from PathTracking.pure_pursuit import pure_pursuit as m def test1(): m.show_animation = False m.main() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_pure_pursuit.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
63
```python import conftest # Add root path to sys.path from PathPlanning.RRT import rrt_with_sobol_sampler as m import random random.seed(12345) def test1(): m.show_animation = False m.main(gx=1.0, gy=1.0) if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_rrt_with_sobol_sampler.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
84
```python import conftest from PathPlanning.BezierPath import bezier_path as m def test_1(): m.show_animation = False m.main() def test_2(): m.show_animation = False m.main2() if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_bezier_path.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
69
```python from Mapping.grid_map_lib.grid_map_lib import GridMap import conftest import numpy as np def test_position_set(): grid_map = GridMap(100, 120, 0.5, 10.0, -0.5) grid_map.set_value_from_xy_pos(10.1, -1.1, 1.0) grid_map.set_value_from_xy_pos(10.1, -0.1, 1.0) grid_map.set_value_from_xy_pos(10.1, 1.1, 1.0) grid_map.set_value_from_xy_pos(11.1, 0.1, 1.0) grid_map.set_value_from_xy_pos(10.1, 0.1, 1.0) grid_map.set_value_from_xy_pos(9.1, 0.1, 1.0) def test_polygon_set(): ox = [0.0, 4.35, 20.0, 50.0, 100.0, 130.0, 40.0] oy = [0.0, -4.15, -20.0, 0.0, 30.0, 60.0, 80.0] grid_map = GridMap(600, 290, 0.7, 60.0, 30.5) grid_map.set_value_from_polygon(ox, oy, 1.0, inside=False) grid_map.set_value_from_polygon(np.array(ox), np.array(oy), 1.0, inside=False) def test_xy_and_grid_index_conversion(): grid_map = GridMap(100, 120, 0.5, 10.0, -0.5) for x_ind in range(grid_map.width): for y_ind in range(grid_map.height): grid_ind = grid_map.calc_grid_index_from_xy_index(x_ind, y_ind) x_ind_2, y_ind_2 = grid_map.calc_xy_index_from_grid_index(grid_ind) assert x_ind == x_ind_2 assert y_ind == y_ind_2 if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_grid_map_lib.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
480
```python import numpy as np import conftest from PathPlanning.DubinsPath import dubins_path_planner np.random.seed(12345) def check_edge_condition(px, py, pyaw, start_x, start_y, start_yaw, end_x, end_y, end_yaw): assert (abs(px[0] - start_x) <= 0.01) assert (abs(py[0] - start_y) <= 0.01) assert (abs(pyaw[0] - start_yaw) <= 0.01) assert (abs(px[-1] - end_x) <= 0.01) assert (abs(py[-1] - end_y) <= 0.01) assert (abs(pyaw[-1] - end_yaw) <= 0.01) def check_path_length(px, py, lengths): path_len = sum( [np.hypot(dx, dy) for (dx, dy) in zip(np.diff(px), np.diff(py))]) assert (abs(path_len - sum(lengths)) <= 0.1) def test_1(): start_x = 1.0 # [m] start_y = 1.0 # [m] start_yaw = np.deg2rad(45.0) # [rad] end_x = -3.0 # [m] end_y = -3.0 # [m] end_yaw = np.deg2rad(-45.0) # [rad] curvature = 1.0 px, py, pyaw, mode, lengths = dubins_path_planner.plan_dubins_path( start_x, start_y, start_yaw, end_x, end_y, end_yaw, curvature) check_edge_condition(px, py, pyaw, start_x, start_y, start_yaw, end_x, end_y, end_yaw) check_path_length(px, py, lengths) def test_2(): dubins_path_planner.show_animation = False dubins_path_planner.main() def test_3(): N_TEST = 10 for i in range(N_TEST): start_x = (np.random.rand() - 0.5) * 10.0 # [m] start_y = (np.random.rand() - 0.5) * 10.0 # [m] start_yaw = np.deg2rad((np.random.rand() - 0.5) * 180.0) # [rad] end_x = (np.random.rand() - 0.5) * 10.0 # [m] end_y = (np.random.rand() - 0.5) * 10.0 # [m] end_yaw = np.deg2rad((np.random.rand() - 0.5) * 180.0) # [rad] curvature = 1.0 / (np.random.rand() * 5.0) px, py, pyaw, mode, lengths = \ dubins_path_planner.plan_dubins_path( start_x, start_y, start_yaw, end_x, end_y, end_yaw, curvature) check_edge_condition(px, py, pyaw, start_x, start_y, start_yaw, end_x, end_y, end_yaw) check_path_length(px, py, lengths) def test_path_plannings_types(): dubins_path_planner.show_animation = False start_x = 1.0 # [m] start_y = 1.0 # [m] start_yaw = np.deg2rad(45.0) # [rad] end_x = -3.0 # [m] end_y = -3.0 # [m] end_yaw = np.deg2rad(-45.0) # [rad] curvature = 1.0 _, _, _, mode, _ = dubins_path_planner.plan_dubins_path( start_x, start_y, start_yaw, end_x, end_y, end_yaw, curvature, selected_types=["RSL"]) assert mode == ["R", "S", "L"] if __name__ == '__main__': conftest.run_this_test(__file__) ```
/content/code_sandbox/tests/test_dubins_path_planning.py
python
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
920
```yaml name: python_robotics channels: - conda-forge dependencies: - python=3.12 - pip - scipy - numpy - cvxpy - matplotlib ```
/content/code_sandbox/requirements/environment.yml
yaml
2016-03-21T09:34:43
2024-08-16T19:00:08
PythonRobotics
AtsushiSakai/PythonRobotics
22,516
48