Repository: zj-wukewei/Hot Branch: master Commit: 7a3b3acc804d Files: 203 Total size: 575.0 KB Directory structure: gitextract_j2m0kka4/ ├── .flowconfig ├── .gitignore ├── .vscode/ │ ├── launchReactNative.js │ ├── settings.json │ └── typings/ │ ├── react/ │ │ ├── react-addons-create-fragment.d.ts │ │ ├── react-addons-css-transition-group.d.ts │ │ ├── react-addons-linked-state-mixin.d.ts │ │ ├── react-addons-perf.d.ts │ │ ├── react-addons-pure-render-mixin.d.ts │ │ ├── react-addons-test-utils.d.ts │ │ ├── react-addons-transition-group.d.ts │ │ ├── react-addons-update.d.ts │ │ ├── react-dom.d.ts │ │ ├── react-global.d.ts │ │ └── react.d.ts │ └── react-native/ │ └── react-native.d.ts ├── README.md ├── app/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── wkw/ │ │ └── hot/ │ │ └── ApplicationTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── wkw/ │ │ │ └── hot/ │ │ │ ├── adapter/ │ │ │ │ └── FragmentAdapter.java │ │ │ ├── base/ │ │ │ │ ├── BaseActivity.java │ │ │ │ ├── BaseFragment.java │ │ │ │ ├── BaseLazyFragment.java │ │ │ │ ├── BaseLoadMoreAdapter.java │ │ │ │ ├── BaseOnScrollListener.java │ │ │ │ ├── BasePresenter.java │ │ │ │ ├── ILoadingView.java │ │ │ │ ├── IPresenter.java │ │ │ │ ├── IView.java │ │ │ │ └── page/ │ │ │ │ ├── BaseLazyPageFragment.java │ │ │ │ ├── BaseListAdapter.java │ │ │ │ ├── BasePageFragment.java │ │ │ │ └── IDataVIew.java │ │ │ ├── cache/ │ │ │ │ ├── CacheLoader.java │ │ │ │ ├── DiskCache.java │ │ │ │ ├── ICache.java │ │ │ │ ├── MemoryCache.java │ │ │ │ └── NetworkCache.java │ │ │ ├── common/ │ │ │ │ └── Constants.java │ │ │ ├── data/ │ │ │ │ ├── DataManager.java │ │ │ │ └── api/ │ │ │ │ └── HotApi.java │ │ │ ├── entity/ │ │ │ │ ├── ListPopularEntity.java │ │ │ │ ├── PagePopularEntity.java │ │ │ │ └── PopularEntity.java │ │ │ ├── mapper/ │ │ │ │ └── PopularModelDataMapper.java │ │ │ ├── model/ │ │ │ │ └── PopularModel.java │ │ │ ├── navigator/ │ │ │ │ └── Navigator.java │ │ │ ├── reject/ │ │ │ │ ├── ContextLife.java │ │ │ │ ├── PerActivity.java │ │ │ │ ├── PerFragment.java │ │ │ │ ├── component/ │ │ │ │ │ ├── ActivityComponent.java │ │ │ │ │ ├── AppComponent.java │ │ │ │ │ └── FragmentComponent.java │ │ │ │ └── module/ │ │ │ │ ├── ActivityModule.java │ │ │ │ ├── AppModule.java │ │ │ │ └── FragmentModule.java │ │ │ ├── ui/ │ │ │ │ ├── AboutActivity.java │ │ │ │ ├── App.java │ │ │ │ ├── item/ │ │ │ │ │ ├── ItemAdapter.java │ │ │ │ │ ├── ItemContract.java │ │ │ │ │ ├── ItemFragment.java │ │ │ │ │ └── ItemPresenter.java │ │ │ │ ├── main/ │ │ │ │ │ ├── MainActivity.java │ │ │ │ │ ├── MainContract.java │ │ │ │ │ └── MainPresenter.java │ │ │ │ ├── react/ │ │ │ │ │ └── MyReactActivity.java │ │ │ │ ├── search/ │ │ │ │ │ └── SearchActivity.java │ │ │ │ └── web/ │ │ │ │ ├── WebActivity.java │ │ │ │ ├── WebContract.java │ │ │ │ └── WebPresenter.java │ │ │ └── utils/ │ │ │ ├── GlideManager.java │ │ │ └── Logger.java │ │ └── res/ │ │ ├── drawable/ │ │ │ ├── custom_cursor.xml │ │ │ ├── progress_bar_bg.xml │ │ │ └── side_nav_bar.xml │ │ ├── drawable-v21/ │ │ │ ├── ic_menu_camera.xml │ │ │ ├── ic_menu_gallery.xml │ │ │ ├── ic_menu_manage.xml │ │ │ ├── ic_menu_send.xml │ │ │ ├── ic_menu_share.xml │ │ │ └── ic_menu_slideshow.xml │ │ ├── layout/ │ │ │ ├── activity_about.xml │ │ │ ├── activity_main.xml │ │ │ ├── activity_search.xml │ │ │ ├── activity_web.xml │ │ │ ├── app_bar_main.xml │ │ │ ├── fragment_item.xml │ │ │ ├── fragment_list.xml │ │ │ ├── layout_item.xml │ │ │ ├── layout_toolbar_view.xml │ │ │ └── nav_header_main.xml │ │ ├── menu/ │ │ │ ├── activity_main_drawer.xml │ │ │ ├── main.xml │ │ │ └── menu_web.xml │ │ ├── values/ │ │ │ ├── arrays.xml │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── drawables.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ ├── values-v21/ │ │ │ └── styles.xml │ │ └── values-w820dp/ │ │ └── dimens.xml │ └── test/ │ └── java/ │ └── com/ │ └── wkw/ │ └── hot/ │ └── ExampleUnitTest.java ├── build.gradle ├── common_lib/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── wkw/ │ │ └── common_lib/ │ │ └── ApplicationTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── wkw/ │ │ │ └── common_lib/ │ │ │ ├── Ext.java │ │ │ ├── image/ │ │ │ │ ├── ImageConfig.java │ │ │ │ ├── ImageLoader.java │ │ │ │ ├── ImageLoaderStrategy.java │ │ │ │ └── glide/ │ │ │ │ ├── GlideImageConfig.java │ │ │ │ └── GlideImageLoaderStrategy.java │ │ │ ├── network/ │ │ │ │ ├── AccessPoint.java │ │ │ │ ├── Network.java │ │ │ │ ├── NetworkDash.java │ │ │ │ ├── NetworkObserver.java │ │ │ │ ├── NetworkState.java │ │ │ │ ├── NetworkStateListener.java │ │ │ │ ├── NetworkType.java │ │ │ │ ├── ServiceProvider.java │ │ │ │ └── WifiDash.java │ │ │ ├── rx/ │ │ │ │ ├── ApiResponse.java │ │ │ │ ├── ProgressSubscriber.java │ │ │ │ ├── RxBus.java │ │ │ │ ├── RxResultHelper.java │ │ │ │ ├── RxSubscriber.java │ │ │ │ ├── SchedulersCompat.java │ │ │ │ └── error/ │ │ │ │ ├── DefaultErrorBundle.java │ │ │ │ ├── ErrorBundle.java │ │ │ │ ├── ErrorHanding.java │ │ │ │ ├── NetworkConnectionException.java │ │ │ │ └── ServerException.java │ │ │ ├── sp/ │ │ │ │ ├── Once.java │ │ │ │ └── PersistedMap.java │ │ │ ├── utils/ │ │ │ │ ├── AndroidUtils.java │ │ │ │ ├── AppManager.java │ │ │ │ ├── AppUtils.java │ │ │ │ ├── DialogUtil.java │ │ │ │ ├── HtmlUtils.java │ │ │ │ ├── NetWorkUtils.java │ │ │ │ ├── ProcessUtils.java │ │ │ │ ├── PropertyUtils.java │ │ │ │ ├── Singleton.java │ │ │ │ ├── StringUtils.java │ │ │ │ ├── ThreadUtils.java │ │ │ │ ├── ToashUtils.java │ │ │ │ └── ViewUtils.java │ │ │ └── widget/ │ │ │ ├── ClearEditText.java │ │ │ ├── CustomTabHost.java │ │ │ ├── ProgressLayout.java │ │ │ ├── TimerButton.java │ │ │ └── loadmore/ │ │ │ ├── DefaultEmptyItem.java │ │ │ ├── DefaultFootItem.java │ │ │ ├── EmptyFootItem.java │ │ │ ├── EmptyItem.java │ │ │ ├── FootItem.java │ │ │ ├── OnLoadMoreListener.java │ │ │ ├── RecyclerViewUtils.java │ │ │ └── RecyclerViewWithFooter.java │ │ └── res/ │ │ ├── layout/ │ │ │ ├── layout_error_view.xml │ │ │ ├── layout_loading_footer_view.xml │ │ │ ├── layout_loading_view.xml │ │ │ ├── layout_no_data_view.xml │ │ │ ├── rv_with_footer_empty_layout.xml │ │ │ └── rv_with_footer_loading.xml │ │ └── values/ │ │ ├── attrs.xml │ │ ├── dimens.xml │ │ ├── rv_with_footer_strings.xml │ │ └── strings.xml │ └── test/ │ └── java/ │ └── com/ │ └── wkw/ │ └── common_lib/ │ └── ExampleUnitTest.java ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── index.android.js ├── js/ │ ├── actions/ │ │ └── newsList.js │ ├── components/ │ │ ├── Header.js │ │ └── LoadingView.js │ ├── constants/ │ │ ├── ActionTypes.js │ │ └── Urls.js │ ├── containes/ │ │ ├── App.js │ │ ├── NewsContaines.js │ │ └── WebViewContaines.js │ ├── pages/ │ │ ├── News.js │ │ └── WebViewPage.js │ ├── reducers/ │ │ ├── index.js │ │ └── newsList.js │ ├── rootApp.js │ ├── store/ │ │ └── store.js │ └── utils/ │ ├── CommonUtil.js │ ├── Services.js │ └── ToastUtil.js ├── package.json ├── settings.gradle ├── tsconfig.json └── version.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .flowconfig ================================================ [ignore] # We fork some components by platform. .*/*.android.js # Ignore templates with `@flow` in header .*/local-cli/generator.* # Ignore malformed json .*/node_modules/y18n/test/.*\.json # Ignore the website subdir /website/.* # Ignore BUCK generated dirs /\.buckd/ # Ignore unexpected extra @providesModule .*/node_modules/commoner/test/source/widget/share.js # Ignore duplicate module providers # For RN Apps installed via npm, "Libraries" folder is inside node_modules/react-native but in the source repo it is in the root .*/Libraries/react-native/React.js .*/Libraries/react-native/ReactNative.js .*/node_modules/jest-runtime/build/__tests__/.* [include] [libs] Libraries/react-native/react-native-interface.js flow/ [options] module.system=haste esproposal.class_static_fields=enable esproposal.class_instance_fields=enable experimental.strict_type_args=true munge_underscores=true module.name_mapper='^image![a-zA-Z0-9$_-]+$' -> 'GlobalImageStub' module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub' suppress_type=$FlowIssue suppress_type=$FlowFixMe suppress_type=$FixMe suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(30\\|[1-2][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\) suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(30\\|1[0-9]\\|[1-2][0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+ suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy unsafe.enable_getters_and_setters=true [version] ^0.30.0 ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /.idea/workspace.xml /.idea/libraries .DS_Store /build /captures /node_modules /projectFilesBackup1 .idea /projectFilesBackup ================================================ FILE: .vscode/launchReactNative.js ================================================ // This file is automatically generated by vscode-react-native@0.1.6 // Please do not modify it manually. All changes will be lost. try { var path = require("path"); var Launcher = require("/Users/wukewei/.vscode/extensions/vsmobile.vscode-react-native-0.1.6/out/debugger/launcher.js").Launcher; new Launcher(path.resolve(__dirname, "..")).launch(); } catch (e) { throw new Error("Unable to launch application. Try deleting .vscode/launchReactNative.js and restarting vscode."); } ================================================ FILE: .vscode/settings.json ================================================ // 将设置放入此文件中以覆盖默认值和用户设置。 { } ================================================ FILE: .vscode/typings/react/react-addons-create-fragment.d.ts ================================================ // Type definitions for React v0.14 (react-addons-create-fragment) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare namespace __React { namespace __Addons { export function createFragment(object: { [key: string]: ReactNode }): ReactFragment; } } declare module "react-addons-create-fragment" { export = __React.__Addons.createFragment; } ================================================ FILE: .vscode/typings/react/react-addons-css-transition-group.d.ts ================================================ // Type definitions for React v0.14 (react-addons-css-transition-group) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// /// declare namespace __React { interface CSSTransitionGroupTransitionName { enter: string; enterActive?: string; leave: string; leaveActive?: string; appear?: string; appearActive?: string; } interface CSSTransitionGroupProps extends TransitionGroupProps { transitionName: string | CSSTransitionGroupTransitionName; transitionAppear?: boolean; transitionAppearTimeout?: number; transitionEnter?: boolean; transitionEnterTimeout?: number; transitionLeave?: boolean; transitionLeaveTimeout?: number; } type CSSTransitionGroup = ComponentClass; namespace __Addons { export var CSSTransitionGroup: __React.CSSTransitionGroup; } } declare module "react-addons-css-transition-group" { var CSSTransitionGroup: __React.CSSTransitionGroup; type CSSTransitionGroup = __React.CSSTransitionGroup; export = CSSTransitionGroup; } ================================================ FILE: .vscode/typings/react/react-addons-linked-state-mixin.d.ts ================================================ // Type definitions for React v0.14 (react-addons-linked-state-mixin) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare namespace __React { interface ReactLink { value: T; requestChange(newValue: T): void; } interface LinkedStateMixin extends Mixin { linkState(key: string): ReactLink; } interface HTMLAttributes { checkedLink?: ReactLink; valueLink?: ReactLink; } namespace __Addons { export var LinkedStateMixin: LinkedStateMixin; } } declare module "react-addons-linked-state-mixin" { var LinkedStateMixin: __React.LinkedStateMixin; type LinkedStateMixin = __React.LinkedStateMixin; export = LinkedStateMixin; } ================================================ FILE: .vscode/typings/react/react-addons-perf.d.ts ================================================ // Type definitions for React v0.14 (react-addons-perf) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare namespace __React { interface ComponentPerfContext { current: string; owner: string; } interface NumericPerfContext { [key: string]: number; } interface Measurements { exclusive: NumericPerfContext; inclusive: NumericPerfContext; render: NumericPerfContext; counts: NumericPerfContext; writes: NumericPerfContext; displayNames: { [key: string]: ComponentPerfContext; }; totalTime: number; } namespace __Addons { namespace Perf { export function start(): void; export function stop(): void; export function printInclusive(measurements: Measurements[]): void; export function printExclusive(measurements: Measurements[]): void; export function printWasted(measurements: Measurements[]): void; export function printDOM(measurements: Measurements[]): void; export function getLastMeasurements(): Measurements[]; } } } declare module "react-addons-perf" { import Perf = __React.__Addons.Perf; export = Perf; } ================================================ FILE: .vscode/typings/react/react-addons-pure-render-mixin.d.ts ================================================ // Type definitions for React v0.14 (react-addons-pure-render-mixin) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare namespace __React { interface PureRenderMixin extends Mixin {} namespace __Addons { export var PureRenderMixin: PureRenderMixin; } } declare module "react-addons-pure-render-mixin" { var PureRenderMixin: __React.PureRenderMixin; type PureRenderMixin = __React.PureRenderMixin; export = PureRenderMixin; } ================================================ FILE: .vscode/typings/react/react-addons-test-utils.d.ts ================================================ // Type definitions for React v0.14 (react-addons-test-utils) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare namespace __React { interface SyntheticEventData { altKey?: boolean; button?: number; buttons?: number; clientX?: number; clientY?: number; changedTouches?: TouchList; charCode?: boolean; clipboardData?: DataTransfer; ctrlKey?: boolean; deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; detail?: number; getModifierState?(key: string): boolean; key?: string; keyCode?: number; locale?: string; location?: number; metaKey?: boolean; pageX?: number; pageY?: number; relatedTarget?: EventTarget; repeat?: boolean; screenX?: number; screenY?: number; shiftKey?: boolean; targetTouches?: TouchList; touches?: TouchList; view?: AbstractView; which?: number; } interface EventSimulator { (element: Element, eventData?: SyntheticEventData): void; (component: Component, eventData?: SyntheticEventData): void; } interface MockedComponentClass { new(): any; } class ShallowRenderer { getRenderOutput>(): E; getRenderOutput(): ReactElement; render(element: ReactElement, context?: any): void; unmount(): void; } namespace __Addons { namespace TestUtils { namespace Simulate { export var blur: EventSimulator; export var change: EventSimulator; export var click: EventSimulator; export var cut: EventSimulator; export var doubleClick: EventSimulator; export var drag: EventSimulator; export var dragEnd: EventSimulator; export var dragEnter: EventSimulator; export var dragExit: EventSimulator; export var dragLeave: EventSimulator; export var dragOver: EventSimulator; export var dragStart: EventSimulator; export var drop: EventSimulator; export var focus: EventSimulator; export var input: EventSimulator; export var keyDown: EventSimulator; export var keyPress: EventSimulator; export var keyUp: EventSimulator; export var mouseDown: EventSimulator; export var mouseEnter: EventSimulator; export var mouseLeave: EventSimulator; export var mouseMove: EventSimulator; export var mouseOut: EventSimulator; export var mouseOver: EventSimulator; export var mouseUp: EventSimulator; export var paste: EventSimulator; export var scroll: EventSimulator; export var submit: EventSimulator; export var touchCancel: EventSimulator; export var touchEnd: EventSimulator; export var touchMove: EventSimulator; export var touchStart: EventSimulator; export var wheel: EventSimulator; } export function renderIntoDocument( element: DOMElement): Element; export function renderIntoDocument

( element: ReactElement

): Component; export function renderIntoDocument>( element: ReactElement): C; export function mockComponent( mocked: MockedComponentClass, mockTagName?: string): typeof TestUtils; export function isElementOfType( element: ReactElement, type: ReactType): boolean; export function isDOMComponent(instance: ReactInstance): boolean; export function isCompositeComponent(instance: ReactInstance): boolean; export function isCompositeComponentWithType( instance: ReactInstance, type: ComponentClass): boolean; export function findAllInRenderedTree( root: Component, fn: (i: ReactInstance) => boolean): ReactInstance[]; export function scryRenderedDOMComponentsWithClass( root: Component, className: string): Element[]; export function findRenderedDOMComponentWithClass( root: Component, className: string): Element; export function scryRenderedDOMComponentsWithTag( root: Component, tagName: string): Element[]; export function findRenderedDOMComponentWithTag( root: Component, tagName: string): Element; export function scryRenderedComponentsWithType

( root: Component, type: ComponentClass

): Component[]; export function scryRenderedComponentsWithType>( root: Component, type: ComponentClass): C[]; export function findRenderedComponentWithType

( root: Component, type: ComponentClass

): Component; export function findRenderedComponentWithType>( root: Component, type: ComponentClass): C; export function createRenderer(): ShallowRenderer; } } } declare module "react-addons-test-utils" { import TestUtils = __React.__Addons.TestUtils; export = TestUtils; } ================================================ FILE: .vscode/typings/react/react-addons-transition-group.d.ts ================================================ // Type definitions for React v0.14 (react-addons-transition-group) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare namespace __React { interface TransitionGroupProps { component?: ReactType; childFactory?: (child: ReactElement) => ReactElement; } type TransitionGroup = ComponentClass; namespace __Addons { export var TransitionGroup: __React.TransitionGroup; } } declare module "react-addons-transition-group" { var TransitionGroup: __React.TransitionGroup; type TransitionGroup = __React.TransitionGroup; export = TransitionGroup; } ================================================ FILE: .vscode/typings/react/react-addons-update.d.ts ================================================ // Type definitions for React v0.14 (react-addons-update) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare namespace __React { interface UpdateSpecCommand { $set?: any; $merge?: {}; $apply?(value: any): any; } interface UpdateSpecPath { [key: string]: UpdateSpec; } type UpdateSpec = UpdateSpecCommand | UpdateSpecPath; interface UpdateArraySpec extends UpdateSpecCommand { $push?: any[]; $unshift?: any[]; $splice?: any[][]; } namespace __Addons { export function update(value: any[], spec: UpdateArraySpec): any[]; export function update(value: {}, spec: UpdateSpec): any; } } declare module "react-addons-update" { export = __React.__Addons.update; } ================================================ FILE: .vscode/typings/react/react-dom.d.ts ================================================ // Type definitions for React v0.14 (react-dom) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare namespace __React { namespace __DOM { function findDOMNode(instance: ReactInstance): E; function findDOMNode(instance: ReactInstance): Element; function render

( element: DOMElement

, container: Element, callback?: (element: Element) => any): Element; function render( element: ClassicElement

, container: Element, callback?: (component: ClassicComponent) => any): ClassicComponent; function render( element: ReactElement

, container: Element, callback?: (component: Component) => any): Component; function unmountComponentAtNode(container: Element): boolean; var version: string; function unstable_batchedUpdates(callback: (a: A, b: B) => any, a: A, b: B): void; function unstable_batchedUpdates(callback: (a: A) => any, a: A): void; function unstable_batchedUpdates(callback: () => any): void; function unstable_renderSubtreeIntoContainer

( parentComponent: Component, nextElement: DOMElement

, container: Element, callback?: (element: Element) => any): Element; function unstable_renderSubtreeIntoContainer( parentComponent: Component, nextElement: ClassicElement

, container: Element, callback?: (component: ClassicComponent) => any): ClassicComponent; function unstable_renderSubtreeIntoContainer( parentComponent: Component, nextElement: ReactElement

, container: Element, callback?: (component: Component) => any): Component; } namespace __DOMServer { function renderToString(element: ReactElement): string; function renderToStaticMarkup(element: ReactElement): string; var version: string; } } declare module "react-dom" { import DOM = __React.__DOM; export = DOM; } declare module "react-dom/server" { import DOMServer = __React.__DOMServer; export = DOMServer; } ================================================ FILE: .vscode/typings/react/react-global.d.ts ================================================ // Type definitions for React v0.14 (namespace) // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped /// /// /// /// /// /// /// /// /// /// import React = __React; import ReactDOM = __React.__DOM; declare namespace __React { export import addons = __React.__Addons; } ================================================ FILE: .vscode/typings/react/react.d.ts ================================================ // Type definitions for React v0.14 // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/borisyankov/DefinitelyTyped declare namespace __React { // // React Elements // ---------------------------------------------------------------------- type ReactType = string | ComponentClass | StatelessComponent; interface ReactElement

> { type: string | ComponentClass

| StatelessComponent

; props: P; key: string | number; ref: string | ((component: Component | Element) => any); } interface ClassicElement

extends ReactElement

{ type: ClassicComponentClass

; ref: string | ((component: ClassicComponent) => any); } interface DOMElement

> extends ReactElement

{ type: string; ref: string | ((element: Element) => any); } interface ReactHTMLElement extends DOMElement> { ref: string | ((element: HTMLElement) => any); } interface ReactSVGElement extends DOMElement { ref: string | ((element: SVGElement) => any); } // // Factories // ---------------------------------------------------------------------- interface Factory

{ (props?: P, ...children: ReactNode[]): ReactElement

; } interface ClassicFactory

extends Factory

{ (props?: P, ...children: ReactNode[]): ClassicElement

; } interface DOMFactory

> extends Factory

{ (props?: P, ...children: ReactNode[]): DOMElement

; } type HTMLFactory = DOMFactory>; type SVGFactory = DOMFactory; // // React Nodes // http://facebook.github.io/react/docs/glossary.html // ---------------------------------------------------------------------- type ReactText = string | number; type ReactChild = ReactElement | ReactText; // Should be Array but type aliases cannot be recursive type ReactFragment = {} | Array; type ReactNode = ReactChild | ReactFragment | boolean; // // Top Level API // ---------------------------------------------------------------------- function createClass(spec: ComponentSpec): ClassicComponentClass

; function createFactory

(type: string): DOMFactory

; function createFactory

(type: ClassicComponentClass

): ClassicFactory

; function createFactory

(type: ComponentClass

| StatelessComponent

): Factory

; function createElement

( type: string, props?: P, ...children: ReactNode[]): DOMElement

; function createElement

( type: ClassicComponentClass

, props?: P, ...children: ReactNode[]): ClassicElement

; function createElement

( type: ComponentClass

| StatelessComponent

, props?: P, ...children: ReactNode[]): ReactElement

; function cloneElement

( element: DOMElement

, props?: P, ...children: ReactNode[]): DOMElement

; function cloneElement

( element: ClassicElement

, props?: P, ...children: ReactNode[]): ClassicElement

; function cloneElement

( element: ReactElement

, props?: P, ...children: ReactNode[]): ReactElement

; function isValidElement(object: {}): boolean; var DOM: ReactDOM; var PropTypes: ReactPropTypes; var Children: ReactChildren; // // Component API // ---------------------------------------------------------------------- type ReactInstance = Component | Element; // Base component for plain JS classes class Component implements ComponentLifecycle { constructor(props?: P, context?: any); setState(f: (prevState: S, props: P) => S, callback?: () => any): void; setState(state: S, callback?: () => any): void; forceUpdate(callBack?: () => any): void; render(): JSX.Element; props: P; state: S; context: {}; refs: { [key: string]: ReactInstance }; } interface ClassicComponent extends Component { replaceState(nextState: S, callback?: () => any): void; isMounted(): boolean; getInitialState?(): S; } interface ChildContextProvider { getChildContext(): CC; } // // Class Interfaces // ---------------------------------------------------------------------- interface StatelessComponent

{ (props?: P, context?: any): ReactElement; propTypes?: ValidationMap

; contextTypes?: ValidationMap; defaultProps?: P; displayName?: string; } interface ComponentClass

{ new(props?: P, context?: any): Component; propTypes?: ValidationMap

; contextTypes?: ValidationMap; childContextTypes?: ValidationMap; defaultProps?: P; } interface ClassicComponentClass

extends ComponentClass

{ new(props?: P, context?: any): ClassicComponent; getDefaultProps?(): P; displayName?: string; } // // Component Specs and Lifecycle // ---------------------------------------------------------------------- interface ComponentLifecycle { componentWillMount?(): void; componentDidMount?(): void; componentWillReceiveProps?(nextProps: P, nextContext: any): void; shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: any): boolean; componentWillUpdate?(nextProps: P, nextState: S, nextContext: any): void; componentDidUpdate?(prevProps: P, prevState: S, prevContext: any): void; componentWillUnmount?(): void; } interface Mixin extends ComponentLifecycle { mixins?: Mixin; statics?: { [key: string]: any; }; displayName?: string; propTypes?: ValidationMap; contextTypes?: ValidationMap; childContextTypes?: ValidationMap; getDefaultProps?(): P; getInitialState?(): S; } interface ComponentSpec extends Mixin { render(): ReactElement; [propertyName: string]: any; } // // Event System // ---------------------------------------------------------------------- interface SyntheticEvent { bubbles: boolean; cancelable: boolean; currentTarget: EventTarget; defaultPrevented: boolean; eventPhase: number; isTrusted: boolean; nativeEvent: Event; preventDefault(): void; stopPropagation(): void; target: EventTarget; timeStamp: Date; type: string; } interface ClipboardEvent extends SyntheticEvent { clipboardData: DataTransfer; } interface CompositionEvent extends SyntheticEvent { data: string; } interface DragEvent extends SyntheticEvent { dataTransfer: DataTransfer; } interface FocusEvent extends SyntheticEvent { relatedTarget: EventTarget; } interface FormEvent extends SyntheticEvent { } interface KeyboardEvent extends SyntheticEvent { altKey: boolean; charCode: number; ctrlKey: boolean; getModifierState(key: string): boolean; key: string; keyCode: number; locale: string; location: number; metaKey: boolean; repeat: boolean; shiftKey: boolean; which: number; } interface MouseEvent extends SyntheticEvent { altKey: boolean; button: number; buttons: number; clientX: number; clientY: number; ctrlKey: boolean; getModifierState(key: string): boolean; metaKey: boolean; pageX: number; pageY: number; relatedTarget: EventTarget; screenX: number; screenY: number; shiftKey: boolean; } interface TouchEvent extends SyntheticEvent { altKey: boolean; changedTouches: TouchList; ctrlKey: boolean; getModifierState(key: string): boolean; metaKey: boolean; shiftKey: boolean; targetTouches: TouchList; touches: TouchList; } interface UIEvent extends SyntheticEvent { detail: number; view: AbstractView; } interface WheelEvent extends SyntheticEvent { deltaMode: number; deltaX: number; deltaY: number; deltaZ: number; } // // Event Handler Types // ---------------------------------------------------------------------- interface EventHandler { (event: E): void; } type ReactEventHandler = EventHandler; type ClipboardEventHandler = EventHandler; type CompositionEventHandler = EventHandler; type DragEventHandler = EventHandler; type FocusEventHandler = EventHandler; type FormEventHandler = EventHandler; type KeyboardEventHandler = EventHandler; type MouseEventHandler = EventHandler; type TouchEventHandler = EventHandler; type UIEventHandler = EventHandler; type WheelEventHandler = EventHandler; // // Props / DOM Attributes // ---------------------------------------------------------------------- interface Props { children?: ReactNode; key?: string | number; ref?: string | ((component: T) => any); } interface HTMLProps extends HTMLAttributes, Props { } interface SVGProps extends SVGAttributes, Props { } interface DOMAttributes { dangerouslySetInnerHTML?: { __html: string; }; // Clipboard Events onCopy?: ClipboardEventHandler; onCut?: ClipboardEventHandler; onPaste?: ClipboardEventHandler; // Composition Events onCompositionEnd?: CompositionEventHandler; onCompositionStart?: CompositionEventHandler; onCompositionUpdate?: CompositionEventHandler; // Focus Events onFocus?: FocusEventHandler; onBlur?: FocusEventHandler; // Form Events onChange?: FormEventHandler; onInput?: FormEventHandler; onSubmit?: FormEventHandler; // Image Events onLoad?: ReactEventHandler; onError?: ReactEventHandler; // also a Media Event // Keyboard Events onKeyDown?: KeyboardEventHandler; onKeyPress?: KeyboardEventHandler; onKeyUp?: KeyboardEventHandler; // Media Events onAbort?: ReactEventHandler; onCanPlay?: ReactEventHandler; onCanPlayThrough?: ReactEventHandler; onDurationChange?: ReactEventHandler; onEmptied?: ReactEventHandler; onEncrypted?: ReactEventHandler; onEnded?: ReactEventHandler; onLoadedData?: ReactEventHandler; onLoadedMetadata?: ReactEventHandler; onLoadStart?: ReactEventHandler; onPause?: ReactEventHandler; onPlay?: ReactEventHandler; onPlaying?: ReactEventHandler; onProgress?: ReactEventHandler; onRateChange?: ReactEventHandler; onSeeked?: ReactEventHandler; onSeeking?: ReactEventHandler; onStalled?: ReactEventHandler; onSuspend?: ReactEventHandler; onTimeUpdate?: ReactEventHandler; onVolumeChange?: ReactEventHandler; onWaiting?: ReactEventHandler; // MouseEvents onClick?: MouseEventHandler; onContextMenu?: MouseEventHandler; onDoubleClick?: MouseEventHandler; onDrag?: DragEventHandler; onDragEnd?: DragEventHandler; onDragEnter?: DragEventHandler; onDragExit?: DragEventHandler; onDragLeave?: DragEventHandler; onDragOver?: DragEventHandler; onDragStart?: DragEventHandler; onDrop?: DragEventHandler; onMouseDown?: MouseEventHandler; onMouseEnter?: MouseEventHandler; onMouseLeave?: MouseEventHandler; onMouseMove?: MouseEventHandler; onMouseOut?: MouseEventHandler; onMouseOver?: MouseEventHandler; onMouseUp?: MouseEventHandler; // Selection Events onSelect?: ReactEventHandler; // Touch Events onTouchCancel?: TouchEventHandler; onTouchEnd?: TouchEventHandler; onTouchMove?: TouchEventHandler; onTouchStart?: TouchEventHandler; // UI Events onScroll?: UIEventHandler; // Wheel Events onWheel?: WheelEventHandler; } // This interface is not complete. Only properties accepting // unitless numbers are listed here (see CSSProperty.js in React) interface CSSProperties { boxFlex?: number; boxFlexGroup?: number; columnCount?: number; flex?: number | string; flexGrow?: number; flexShrink?: number; fontWeight?: number | string; lineClamp?: number; lineHeight?: number | string; opacity?: number; order?: number; orphans?: number; widows?: number; zIndex?: number; zoom?: number; fontSize?: number | string; // SVG-related properties fillOpacity?: number; strokeOpacity?: number; strokeWidth?: number; // Remaining properties auto-extracted from http://docs.webplatform.org. // License: http://docs.webplatform.org/wiki/Template:CC-by-3.0 /** * Aligns a flex container's lines within the flex container when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis. */ alignContent?: any; /** * Sets the default alignment in the cross axis for all of the flex container's items, including anonymous flex items, similarly to how justify-content aligns items along the main axis. */ alignItems?: any; /** * Allows the default alignment to be overridden for individual flex items. */ alignSelf?: any; /** * This property allows precise alignment of elements, such as graphics, that do not have a baseline-table or lack the desired baseline in their baseline-table. With the alignment-adjust property, the position of the baseline identified by the alignment-baseline can be explicitly determined. It also determines precisely the alignment point for each glyph within a textual element. */ alignmentAdjust?: any; alignmentBaseline?: any; /** * Defines a length of time to elapse before an animation starts, allowing an animation to begin execution some time after it is applied. */ animationDelay?: any; /** * Defines whether an animation should run in reverse on some or all cycles. */ animationDirection?: any; /** * Specifies how many times an animation cycle should play. */ animationIterationCount?: any; /** * Defines the list of animations that apply to the element. */ animationName?: any; /** * Defines whether an animation is running or paused. */ animationPlayState?: any; /** * Allows changing the style of any element to platform-based interface elements or vice versa. */ appearance?: any; /** * Determines whether or not the “back” side of a transformed element is visible when facing the viewer. */ backfaceVisibility?: any; /** * This property describes how the element's background images should blend with each other and the element's background color. * The value is a list of blend modes that corresponds to each background image. Each element in the list will apply to the corresponding element of background-image. If a property doesn’t have enough comma-separated values to match the number of layers, the UA must calculate its used value by repeating the list of values until there are enough. */ backgroundBlendMode?: any; backgroundColor?: any; backgroundComposite?: any; /** * Applies one or more background images to an element. These can be any valid CSS image, including url() paths to image files or CSS gradients. */ backgroundImage?: any; /** * Specifies what the background-position property is relative to. */ backgroundOrigin?: any; /** * Sets the horizontal position of a background image. */ backgroundPositionX?: any; /** * Background-repeat defines if and how background images will be repeated after they have been sized and positioned */ backgroundRepeat?: any; /** * Obsolete - spec retired, not implemented. */ baselineShift?: any; /** * Non standard. Sets or retrieves the location of the Dynamic HTML (DHTML) behavior. */ behavior?: any; /** * Shorthand property that defines the different properties of all four sides of an element's border in a single declaration. It can be used to set border-width, border-style and border-color, or a subset of these. */ border?: any; /** * Defines the shape of the border of the bottom-left corner. */ borderBottomLeftRadius?: any; /** * Defines the shape of the border of the bottom-right corner. */ borderBottomRightRadius?: any; /** * Sets the width of an element's bottom border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderBottomWidth?: any; /** * Border-collapse can be used for collapsing the borders between table cells */ borderCollapse?: any; /** * The CSS border-color property sets the color of an element's four borders. This property can have from one to four values, made up of the elementary properties: • border-top-color * • border-right-color * • border-bottom-color * • border-left-color The default color is the currentColor of each of these values. * If you provide one value, it sets the color for the element. Two values set the horizontal and vertical values, respectively. Providing three values sets the top, vertical, and bottom values, in that order. Four values set all for sides: top, right, bottom, and left, in that order. */ borderColor?: any; /** * Specifies different corner clipping effects, such as scoop (inner curves), bevel (straight cuts) or notch (cut-off rectangles). Works along with border-radius to specify the size of each corner effect. */ borderCornerShape?: any; /** * The property border-image-source is used to set the image to be used instead of the border style. If this is set to none the border-style is used instead. */ borderImageSource?: any; /** * The border-image-width CSS property defines the offset to use for dividing the border image in nine parts, the top-left corner, central top edge, top-right-corner, central right edge, bottom-right corner, central bottom edge, bottom-left corner, and central right edge. They represent inward distance from the top, right, bottom, and left edges. */ borderImageWidth?: any; /** * Shorthand property that defines the border-width, border-style and border-color of an element's left border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the left border — border-left-width, border-left-style and border-left-color. */ borderLeft?: any; /** * The CSS border-left-color property sets the color of an element's left border. This page explains the border-left-color value, but often you will find it more convenient to fix the border's left color as part of a shorthand set, either border-left or border-color. * Colors can be defined several ways. For more information, see Usage. */ borderLeftColor?: any; /** * Sets the style of an element's left border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. */ borderLeftStyle?: any; /** * Sets the width of an element's left border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderLeftWidth?: any; /** * Shorthand property that defines the border-width, border-style and border-color of an element's right border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the right border — border-right-width, border-right-style and border-right-color. */ borderRight?: any; /** * Sets the color of an element's right border. This page explains the border-right-color value, but often you will find it more convenient to fix the border's right color as part of a shorthand set, either border-right or border-color. * Colors can be defined several ways. For more information, see Usage. */ borderRightColor?: any; /** * Sets the style of an element's right border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. */ borderRightStyle?: any; /** * Sets the width of an element's right border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderRightWidth?: any; /** * Specifies the distance between the borders of adjacent cells. */ borderSpacing?: any; /** * Sets the style of an element's four borders. This property can have from one to four values. With only one value, the value will be applied to all four borders; otherwise, this works as a shorthand property for each of border-top-style, border-right-style, border-bottom-style, border-left-style, where each border style may be assigned a separate value. */ borderStyle?: any; /** * Shorthand property that defines the border-width, border-style and border-color of an element's top border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the top border — border-top-width, border-top-style and border-top-color. */ borderTop?: any; /** * Sets the color of an element's top border. This page explains the border-top-color value, but often you will find it more convenient to fix the border's top color as part of a shorthand set, either border-top or border-color. * Colors can be defined several ways. For more information, see Usage. */ borderTopColor?: any; /** * Sets the rounding of the top-left corner of the element. */ borderTopLeftRadius?: any; /** * Sets the rounding of the top-right corner of the element. */ borderTopRightRadius?: any; /** * Sets the style of an element's top border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. */ borderTopStyle?: any; /** * Sets the width of an element's top border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderTopWidth?: any; /** * Sets the width of an element's four borders. This property can have from one to four values. This is a shorthand property for setting values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderWidth?: any; /** * Obsolete. */ boxAlign?: any; /** * Breaks a box into fragments creating new borders, padding and repeating backgrounds or lets it stay as a continuous box on a page break, column break, or, for inline elements, at a line break. */ boxDecorationBreak?: any; /** * Deprecated */ boxDirection?: any; /** * Do not use. This property has been replaced by the flex-wrap property. * Gets or sets a value that specifies the direction to add successive rows or columns when the value of box-lines is set to multiple. */ boxLineProgression?: any; /** * Do not use. This property has been replaced by the flex-wrap property. * Gets or sets a value that specifies whether child elements wrap onto multiple lines or columns based on the space available in the object. */ boxLines?: any; /** * Do not use. This property has been replaced by flex-order. * Specifies the ordinal group that a child element of the object belongs to. This ordinal value identifies the display order (along the axis defined by the box-orient property) for the group. */ boxOrdinalGroup?: any; /** * The CSS break-after property allows you to force a break on multi-column layouts. More specifically, it allows you to force a break after an element. It allows you to determine if a break should occur, and what type of break it should be. The break-after CSS property describes how the page, column or region break behaves after the generated box. If there is no generated box, the property is ignored. */ breakAfter?: any; /** * Control page/column/region breaks that fall above a block of content */ breakBefore?: any; /** * Control page/column/region breaks that fall within a block of content */ breakInside?: any; /** * The clear CSS property specifies if an element can be positioned next to or must be positioned below the floating elements that precede it in the markup. */ clear?: any; /** * Deprecated; see clip-path. * Lets you specify the dimensions of an absolutely positioned element that should be visible, and the element is clipped into this shape, and displayed. */ clip?: any; /** * Clipping crops an graphic, so that only a portion of the graphic is rendered, or filled. This clip-rule property, when used with the clip-path property, defines which clip rule, or algorithm, to use when filling the different parts of a graphics. */ clipRule?: any; /** * The color property sets the color of an element's foreground content (usually text), accepting any standard CSS color from keywords and hex values to RGB(a) and HSL(a). */ color?: any; /** * Specifies how to fill columns (balanced or sequential). */ columnFill?: any; /** * The column-gap property controls the width of the gap between columns in multi-column elements. */ columnGap?: any; /** * Sets the width, style, and color of the rule between columns. */ columnRule?: any; /** * Specifies the color of the rule between columns. */ columnRuleColor?: any; /** * Specifies the width of the rule between columns. */ columnRuleWidth?: any; /** * The column-span CSS property makes it possible for an element to span across all columns when its value is set to all. An element that spans more than one column is called a spanning element. */ columnSpan?: any; /** * Specifies the width of columns in multi-column elements. */ columnWidth?: any; /** * This property is a shorthand property for setting column-width and/or column-count. */ columns?: any; /** * The counter-increment property accepts one or more names of counters (identifiers), each one optionally followed by an integer which specifies the value by which the counter should be incremented (e.g. if the value is 2, the counter increases by 2 each time it is invoked). */ counterIncrement?: any; /** * The counter-reset property contains a list of one or more names of counters, each one optionally followed by an integer (otherwise, the integer defaults to 0.) Each time the given element is invoked, the counters specified by the property are set to the given integer. */ counterReset?: any; /** * The cue property specifies sound files (known as an "auditory icon") to be played by speech media agents before and after presenting an element's content; if only one file is specified, it is played both before and after. The volume at which the file(s) should be played, relative to the volume of the main element, may also be specified. The icon files may also be set separately with the cue-before and cue-after properties. */ cue?: any; /** * The cue-after property specifies a sound file (known as an "auditory icon") to be played by speech media agents after presenting an element's content; the volume at which the file should be played may also be specified. The shorthand property cue sets cue sounds for both before and after the element is presented. */ cueAfter?: any; /** * The direction CSS property specifies the text direction/writing direction. The rtl is used for Hebrew or Arabic text, the ltr is for other languages. */ direction?: any; /** * This property specifies the type of rendering box used for an element. It is a shorthand property for many other display properties. */ display?: any; /** * The ‘fill’ property paints the interior of the given graphical element. The area to be painted consists of any areas inside the outline of the shape. To determine the inside of the shape, all subpaths are considered, and the interior is determined according to the rules associated with the current value of the ‘fill-rule’ property. The zero-width geometric outline of a shape is included in the area to be painted. */ fill?: any; /** * The ‘fill-rule’ property indicates the algorithm which is to be used to determine what parts of the canvas are included inside the shape. For a simple, non-intersecting path, it is intuitively clear what region lies "inside"; however, for a more complex path, such as a path that intersects itself or where one subpath encloses another, the interpretation of "inside" is not so obvious. * The ‘fill-rule’ property provides two options for how the inside of a shape is determined: */ fillRule?: any; /** * Applies various image processing effects. This property is largely unsupported. See Compatibility section for more information. */ filter?: any; /** * Obsolete, do not use. This property has been renamed to align-items. * Specifies the alignment (perpendicular to the layout axis defined by the flex-direction property) of child elements of the object. */ flexAlign?: any; /** * The flex-basis CSS property describes the initial main size of the flex item before any free space is distributed according to the flex factors described in the flex property (flex-grow and flex-shrink). */ flexBasis?: any; /** * The flex-direction CSS property describes how flex items are placed in the flex container, by setting the direction of the flex container's main axis. */ flexDirection?: any; /** * The flex-flow CSS property defines the flex container's main and cross axis. It is a shorthand property for the flex-direction and flex-wrap properties. */ flexFlow?: any; /** * Do not use. This property has been renamed to align-self * Specifies the alignment (perpendicular to the layout axis defined by flex-direction) of child elements of the object. */ flexItemAlign?: any; /** * Do not use. This property has been renamed to align-content. * Specifies how a flexbox's lines align within the flexbox when there is extra space along the axis that is perpendicular to the axis defined by the flex-direction property. */ flexLinePack?: any; /** * Gets or sets a value that specifies the ordinal group that a flexbox element belongs to. This ordinal value identifies the display order for the group. */ flexOrder?: any; /** * Elements which have the style float are floated horizontally. These elements can move as far to the left or right of the containing element. All elements after the floating element will flow around it, but elements before the floating element are not impacted. If several floating elements are placed after each other, they will float next to each other as long as there is room. */ float?: any; /** * Flows content from a named flow (specified by a corresponding flow-into) through selected elements to form a dynamic chain of layout regions. */ flowFrom?: any; /** * The font property is shorthand that allows you to do one of two things: you can either set up six of the most mature font properties in one line, or you can set one of a choice of keywords to adopt a system font setting. */ font?: any; /** * The font-family property allows one or more font family names and/or generic family names to be specified for usage on the selected element(s)' text. The browser then goes through the list; for each character in the selection it applies the first font family that has an available glyph for that character. */ fontFamily?: any; /** * The font-kerning property allows contextual adjustment of inter-glyph spacing, i.e. the spaces between the characters in text. This property controls metric kerning - that utilizes adjustment data contained in the font. Optical Kerning is not supported as yet. */ fontKerning?: any; /** * The font-size-adjust property adjusts the font-size of the fallback fonts defined with font-family, so that the x-height is the same no matter what font is used. This preserves the readability of the text when fallback happens. */ fontSizeAdjust?: any; /** * Allows you to expand or condense the widths for a normal, condensed, or expanded font face. */ fontStretch?: any; /** * The font-style property allows normal, italic, or oblique faces to be selected. Italic forms are generally cursive in nature while oblique faces are typically sloped versions of the regular face. Oblique faces can be simulated by artificially sloping the glyphs of the regular face. */ fontStyle?: any; /** * This value specifies whether the user agent is allowed to synthesize bold or oblique font faces when a font family lacks bold or italic faces. */ fontSynthesis?: any; /** * The font-variant property enables you to select the small-caps font within a font family. */ fontVariant?: any; /** * Fonts can provide alternate glyphs in addition to default glyph for a character. This property provides control over the selection of these alternate glyphs. */ fontVariantAlternates?: any; /** * Lays out one or more grid items bound by 4 grid lines. Shorthand for setting grid-column-start, grid-column-end, grid-row-start, and grid-row-end in a single declaration. */ gridArea?: any; /** * Controls a grid item's placement in a grid area, particularly grid position and a grid span. Shorthand for setting grid-column-start and grid-column-end in a single declaration. */ gridColumn?: any; /** * Controls a grid item's placement in a grid area as well as grid position and a grid span. The grid-column-end property (with grid-row-start, grid-row-end, and grid-column-start) determines a grid item's placement by specifying the grid lines of a grid item's grid area. */ gridColumnEnd?: any; /** * Determines a grid item's placement by specifying the starting grid lines of a grid item's grid area . A grid item's placement in a grid area consists of a grid position and a grid span. See also ( grid-row-start, grid-row-end, and grid-column-end) */ gridColumnStart?: any; /** * Gets or sets a value that indicates which row an element within a Grid should appear in. Shorthand for setting grid-row-start and grid-row-end in a single declaration. */ gridRow?: any; /** * Determines a grid item’s placement by specifying the block-end. A grid item's placement in a grid area consists of a grid position and a grid span. The grid-row-end property (with grid-row-start, grid-column-start, and grid-column-end) determines a grid item's placement by specifying the grid lines of a grid item's grid area. */ gridRowEnd?: any; /** * Specifies a row position based upon an integer location, string value, or desired row size. * css/properties/grid-row is used as short-hand for grid-row-position and grid-row-position */ gridRowPosition?: any; gridRowSpan?: any; /** * Specifies named grid areas which are not associated with any particular grid item, but can be referenced from the grid-placement properties. The syntax of the grid-template-areas property also provides a visualization of the structure of the grid, making the overall layout of the grid container easier to understand. */ gridTemplateAreas?: any; /** * Specifies (with grid-template-rows) the line names and track sizing functions of the grid. Each sizing function can be specified as a length, a percentage of the grid container’s size, a measurement of the contents occupying the column or row, or a fraction of the free space in the grid. */ gridTemplateColumns?: any; /** * Specifies (with grid-template-columns) the line names and track sizing functions of the grid. Each sizing function can be specified as a length, a percentage of the grid container’s size, a measurement of the contents occupying the column or row, or a fraction of the free space in the grid. */ gridTemplateRows?: any; /** * Sets the height of an element. The content area of the element height does not include the padding, border, and margin of the element. */ height?: any; /** * Specifies the minimum number of characters in a hyphenated word */ hyphenateLimitChars?: any; /** * Indicates the maximum number of successive hyphenated lines in an element. The ‘no-limit’ value means that there is no limit. */ hyphenateLimitLines?: any; /** * Specifies the maximum amount of trailing whitespace (before justification) that may be left in a line before hyphenation is triggered to pull part of a word from the next line back up into the current one. */ hyphenateLimitZone?: any; /** * Specifies whether or not words in a sentence can be split by the use of a manual or automatic hyphenation mechanism. */ hyphens?: any; imeMode?: any; layoutGrid?: any; layoutGridChar?: any; layoutGridLine?: any; layoutGridMode?: any; layoutGridType?: any; /** * Sets the left edge of an element */ left?: any; /** * The letter-spacing CSS property specifies the spacing behavior between text characters. */ letterSpacing?: any; /** * Deprecated. Gets or sets line-breaking rules for text in selected languages such as Japanese, Chinese, and Korean. */ lineBreak?: any; /** * Shorthand property that sets the list-style-type, list-style-position and list-style-image properties in one declaration. */ listStyle?: any; /** * This property sets the image that will be used as the list item marker. When the image is available, it will replace the marker set with the 'list-style-type' marker. That also means that if the image is not available, it will show the style specified by list-style-property */ listStyleImage?: any; /** * Specifies if the list-item markers should appear inside or outside the content flow. */ listStylePosition?: any; /** * Specifies the type of list-item marker in a list. */ listStyleType?: any; /** * The margin property is shorthand to allow you to set all four margins of an element at once. Its equivalent longhand properties are margin-top, margin-right, margin-bottom and margin-left. Negative values are also allowed. */ margin?: any; /** * margin-bottom sets the bottom margin of an element. */ marginBottom?: any; /** * margin-left sets the left margin of an element. */ marginLeft?: any; /** * margin-right sets the right margin of an element. */ marginRight?: any; /** * margin-top sets the top margin of an element. */ marginTop?: any; /** * The marquee-direction determines the initial direction in which the marquee content moves. */ marqueeDirection?: any; /** * The 'marquee-style' property determines a marquee's scrolling behavior. */ marqueeStyle?: any; /** * This property is shorthand for setting mask-image, mask-mode, mask-repeat, mask-position, mask-clip, mask-origin, mask-composite and mask-size. Omitted values are set to their original properties' initial values. */ mask?: any; /** * This property is shorthand for setting mask-border-source, mask-border-slice, mask-border-width, mask-border-outset, and mask-border-repeat. Omitted values are set to their original properties' initial values. */ maskBorder?: any; /** * This property specifies how the images for the sides and the middle part of the mask image are scaled and tiled. The first keyword applies to the horizontal sides, the second one applies to the vertical ones. If the second keyword is absent, it is assumed to be the same as the first, similar to the CSS border-image-repeat property. */ maskBorderRepeat?: any; /** * This property specifies inward offsets from the top, right, bottom, and left edges of the mask image, dividing it into nine regions: four corners, four edges, and a middle. The middle image part is discarded and treated as fully transparent black unless the fill keyword is present. The four values set the top, right, bottom and left offsets in that order, similar to the CSS border-image-slice property. */ maskBorderSlice?: any; /** * Specifies an image to be used as a mask. An image that is empty, fails to download, is non-existent, or cannot be displayed is ignored and does not mask the element. */ maskBorderSource?: any; /** * This property sets the width of the mask box image, similar to the CSS border-image-width property. */ maskBorderWidth?: any; /** * Determines the mask painting area, which defines the area that is affected by the mask. The painted content of an element may be restricted to this area. */ maskClip?: any; /** * For elements rendered as a single box, specifies the mask positioning area. For elements rendered as multiple boxes (e.g., inline boxes on several lines, boxes on several pages) specifies which boxes box-decoration-break operates on to determine the mask positioning area(s). */ maskOrigin?: any; /** * This property must not be used. It is no longer included in any standard or standard track specification, nor is it implemented in any browser. It is only used when the text-align-last property is set to size. It controls allowed adjustments of font-size to fit line content. */ maxFontSize?: any; /** * Sets the maximum height for an element. It prevents the height of the element to exceed the specified value. If min-height is specified and is greater than max-height, max-height is overridden. */ maxHeight?: any; /** * Sets the maximum width for an element. It limits the width property to be larger than the value specified in max-width. */ maxWidth?: any; /** * Sets the minimum height for an element. It prevents the height of the element to be smaller than the specified value. The value of min-height overrides both max-height and height. */ minHeight?: any; /** * Sets the minimum width of an element. It limits the width property to be not smaller than the value specified in min-width. */ minWidth?: any; /** * The CSS outline property is a shorthand property for setting one or more of the individual outline properties outline-style, outline-width and outline-color in a single rule. In most cases the use of this shortcut is preferable and more convenient. * Outlines differ from borders in the following ways: • Outlines do not take up space, they are drawn above the content. * • Outlines may be non-rectangular. They are rectangular in Gecko/Firefox. Internet Explorer attempts to place the smallest contiguous outline around all elements or shapes that are indicated to have an outline. Opera draws a non-rectangular shape around a construct. */ outline?: any; /** * The outline-color property sets the color of the outline of an element. An outline is a line that is drawn around elements, outside the border edge, to make the element stand out. */ outlineColor?: any; /** * The outline-offset property offsets the outline and draw it beyond the border edge. */ outlineOffset?: any; /** * The overflow property controls how extra content exceeding the bounding box of an element is rendered. It can be used in conjunction with an element that has a fixed width and height, to eliminate text-induced page distortion. */ overflow?: any; /** * Specifies the preferred scrolling methods for elements that overflow. */ overflowStyle?: any; /** * The overflow-x property is a specific case of the generic overflow property. It controls how extra content exceeding the x-axis of the bounding box of an element is rendered. */ overflowX?: any; /** * The padding optional CSS property sets the required padding space on one to four sides of an element. The padding area is the space between an element and its border. Negative values are not allowed but decimal values are permitted. The element size is treated as fixed, and the content of the element shifts toward the center as padding is increased. * The padding property is a shorthand to avoid setting each side separately (padding-top, padding-right, padding-bottom, padding-left). */ padding?: any; /** * The padding-bottom CSS property of an element sets the padding space required on the bottom of an element. The padding area is the space between the content of the element and its border. Contrary to margin-bottom values, negative values of padding-bottom are invalid. */ paddingBottom?: any; /** * The padding-left CSS property of an element sets the padding space required on the left side of an element. The padding area is the space between the content of the element and its border. Contrary to margin-left values, negative values of padding-left are invalid. */ paddingLeft?: any; /** * The padding-right CSS property of an element sets the padding space required on the right side of an element. The padding area is the space between the content of the element and its border. Contrary to margin-right values, negative values of padding-right are invalid. */ paddingRight?: any; /** * The padding-top CSS property of an element sets the padding space required on the top of an element. The padding area is the space between the content of the element and its border. Contrary to margin-top values, negative values of padding-top are invalid. */ paddingTop?: any; /** * The page-break-after property is supported in all major browsers. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. */ pageBreakAfter?: any; /** * The page-break-before property sets the page-breaking behavior before an element. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. */ pageBreakBefore?: any; /** * Sets the page-breaking behavior inside an element. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. */ pageBreakInside?: any; /** * The pause property determines how long a speech media agent should pause before and after presenting an element. It is a shorthand for the pause-before and pause-after properties. */ pause?: any; /** * The pause-after property determines how long a speech media agent should pause after presenting an element. It may be replaced by the shorthand property pause, which sets pause time before and after. */ pauseAfter?: any; /** * The pause-before property determines how long a speech media agent should pause before presenting an element. It may be replaced by the shorthand property pause, which sets pause time before and after. */ pauseBefore?: any; /** * The perspective property defines how far an element is placed from the view on the z-axis, from the screen to the viewer. * Perspective defines how an object is viewed. In graphic arts, perspective is the representation on a flat surface of what the viewer's eye would see in a 3D space. (See Wikipedia for more information about graphical perspective and for related illustrations.) * The illusion of perspective on a flat surface, such as a computer screen, is created by projecting points on the flat surface as they would appear if the flat surface were a window through which the viewer was looking at the object. In discussion of virtual environments, this flat surface is called a projection plane. */ perspective?: any; /** * The perspective-origin property establishes the origin for the perspective property. It effectively sets the X and Y position at which the viewer appears to be looking at the children of the element. * When used with perspective, perspective-origin changes the appearance of an object, as if a viewer were looking at it from a different origin. An object appears differently if a viewer is looking directly at it versus looking at it from below, above, or from the side. Thus, the perspective-origin is like a vanishing point. * The default value of perspective-origin is 50% 50%. This displays an object as if the viewer's eye were positioned directly at the center of the screen, both top-to-bottom and left-to-right. A value of 0% 0% changes the object as if the viewer was looking toward the top left angle. A value of 100% 100% changes the appearance as if viewed toward the bottom right angle. */ perspectiveOrigin?: any; /** * The pointer-events property allows you to control whether an element can be the target for the pointing device (e.g, mouse, pen) events. */ pointerEvents?: any; /** * The position property controls the type of positioning used by an element within its parent elements. The effect of the position property depends on a lot of factors, for example the position property of parent elements. */ position?: any; /** * Obsolete: unsupported. * This property determines whether or not a full-width punctuation mark character should be trimmed if it appears at the beginning of a line, so that its "ink" lines up with the first glyph in the line above and below. */ punctuationTrim?: any; /** * Sets the type of quotation marks for embedded quotations. */ quotes?: any; /** * Controls whether the last region in a chain displays additional 'overset' content according its default overflow property, or if it displays a fragment of content as if it were flowing into a subsequent region. */ regionFragment?: any; /** * The rest-after property determines how long a speech media agent should pause after presenting an element's main content, before presenting that element's exit cue sound. It may be replaced by the shorthand property rest, which sets rest time before and after. */ restAfter?: any; /** * The rest-before property determines how long a speech media agent should pause after presenting an intro cue sound for an element, before presenting that element's main content. It may be replaced by the shorthand property rest, which sets rest time before and after. */ restBefore?: any; /** * Specifies the position an element in relation to the right side of the containing element. */ right?: any; rubyAlign?: any; rubyPosition?: any; /** * Defines the alpha channel threshold used to extract a shape from an image. Can be thought of as a "minimum opacity" threshold; that is, a value of 0.5 means that the shape will enclose all the pixels that are more than 50% opaque. */ shapeImageThreshold?: any; /** * A future level of CSS Shapes will define a shape-inside property, which will define a shape to wrap content within the element. See Editor's Draft and CSSWG wiki page on next-level plans */ shapeInside?: any; /** * Adds a margin to a shape-outside. In effect, defines a new shape that is the smallest contour around all the points that are the shape-margin distance outward perpendicular to each point on the underlying shape. For points where a perpendicular direction is not defined (e.g., a triangle corner), takes all points on a circle centered at the point and with a radius of the shape-margin distance. This property accepts only non-negative values. */ shapeMargin?: any; /** * Declares a shape around which text should be wrapped, with possible modifications from the shape-margin property. The shape defined by shape-outside and shape-margin changes the geometry of a float element's float area. */ shapeOutside?: any; /** * The speak property determines whether or not a speech synthesizer will read aloud the contents of an element. */ speak?: any; /** * The speak-as property determines how the speech synthesizer interprets the content: words as whole words or as a sequence of letters, numbers as a numerical value or a sequence of digits, punctuation as pauses in speech or named punctuation characters. */ speakAs?: any; /** * The tab-size CSS property is used to customise the width of a tab (U+0009) character. */ tabSize?: any; /** * The 'table-layout' property controls the algorithm used to lay out the table cells, rows, and columns. */ tableLayout?: any; /** * The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content. */ textAlign?: any; /** * The text-align-last CSS property describes how the last line of a block element or a line before line break is aligned in its parent block element. */ textAlignLast?: any; /** * The text-decoration CSS property is used to set the text formatting to underline, overline, line-through or blink. * underline and overline decorations are positioned under the text, line-through over it. */ textDecoration?: any; /** * Sets the color of any text decoration, such as underlines, overlines, and strike throughs. */ textDecorationColor?: any; /** * Sets what kind of line decorations are added to an element, such as underlines, overlines, etc. */ textDecorationLine?: any; textDecorationLineThrough?: any; textDecorationNone?: any; textDecorationOverline?: any; /** * Specifies what parts of an element’s content are skipped over when applying any text decoration. */ textDecorationSkip?: any; /** * This property specifies the style of the text decoration line drawn on the specified element. The intended meaning for the values are the same as those of the border-style-properties. */ textDecorationStyle?: any; textDecorationUnderline?: any; /** * The text-emphasis property will apply special emphasis marks to the elements text. Slightly similar to the text-decoration property only that this property can have affect on the line-height. It also is noted that this is shorthand for text-emphasis-style and for text-emphasis-color. */ textEmphasis?: any; /** * The text-emphasis-color property specifies the foreground color of the emphasis marks. */ textEmphasisColor?: any; /** * The text-emphasis-style property applies special emphasis marks to an element's text. */ textEmphasisStyle?: any; /** * This property helps determine an inline box's block-progression dimension, derived from the text-height and font-size properties for non-replaced elements, the height or the width for replaced elements, and the stacked block-progression dimension for inline-block elements. The block-progression dimension determines the position of the padding, border and margin for the element. */ textHeight?: any; /** * Specifies the amount of space horizontally that should be left on the first line of the text of an element. This horizontal spacing is at the beginning of the first line and is in respect to the left edge of the containing block box. */ textIndent?: any; textJustifyTrim?: any; textKashidaSpace?: any; /** * The text-line-through property is a shorthand property for text-line-through-style, text-line-through-color and text-line-through-mode. (Considered obsolete; use text-decoration instead.) */ textLineThrough?: any; /** * Specifies the line colors for the line-through text decoration. * (Considered obsolete; use text-decoration-color instead.) */ textLineThroughColor?: any; /** * Sets the mode for the line-through text decoration, determining whether the text decoration affects the space characters or not. * (Considered obsolete; use text-decoration-skip instead.) */ textLineThroughMode?: any; /** * Specifies the line style for line-through text decoration. * (Considered obsolete; use text-decoration-style instead.) */ textLineThroughStyle?: any; /** * Specifies the line width for the line-through text decoration. */ textLineThroughWidth?: any; /** * The text-overflow shorthand CSS property determines how overflowed content that is not displayed is signaled to the users. It can be clipped, display an ellipsis ('…', U+2026 HORIZONTAL ELLIPSIS) or a Web author-defined string. It covers the two long-hand properties text-overflow-mode and text-overflow-ellipsis */ textOverflow?: any; /** * The text-overline property is the shorthand for the text-overline-style, text-overline-width, text-overline-color, and text-overline-mode properties. */ textOverline?: any; /** * Specifies the line color for the overline text decoration. */ textOverlineColor?: any; /** * Sets the mode for the overline text decoration, determining whether the text decoration affects the space characters or not. */ textOverlineMode?: any; /** * Specifies the line style for overline text decoration. */ textOverlineStyle?: any; /** * Specifies the line width for the overline text decoration. */ textOverlineWidth?: any; /** * The text-rendering CSS property provides information to the browser about how to optimize when rendering text. Options are: legibility, speed or geometric precision. */ textRendering?: any; /** * Obsolete: unsupported. */ textScript?: any; /** * The CSS text-shadow property applies one or more drop shadows to the text and of an element. Each shadow is specified as an offset from the text, along with optional color and blur radius values. */ textShadow?: any; /** * This property transforms text for styling purposes. (It has no effect on the underlying content.) */ textTransform?: any; /** * Unsupported. * This property will add a underline position value to the element that has an underline defined. */ textUnderlinePosition?: any; /** * After review this should be replaced by text-decoration should it not? * This property will set the underline style for text with a line value for underline, overline, and line-through. */ textUnderlineStyle?: any; /** * This property specifies how far an absolutely positioned box's top margin edge is offset below the top edge of the box's containing block. For relatively positioned boxes, the offset is with respect to the top edges of the box itself (i.e., the box is given a position in the normal flow, then offset from that position according to these properties). */ top?: any; /** * Determines whether touch input may trigger default behavior supplied by the user agent, such as panning or zooming. */ touchAction?: any; /** * CSS transforms allow elements styled with CSS to be transformed in two-dimensional or three-dimensional space. Using this property, elements can be translated, rotated, scaled, and skewed. The value list may consist of 2D and/or 3D transform values. */ transform?: any; /** * This property defines the origin of the transformation axes relative to the element to which the transformation is applied. */ transformOrigin?: any; /** * This property allows you to define the relative position of the origin of the transformation grid along the z-axis. */ transformOriginZ?: any; /** * This property specifies how nested elements are rendered in 3D space relative to their parent. */ transformStyle?: any; /** * The transition CSS property is a shorthand property for transition-property, transition-duration, transition-timing-function, and transition-delay. It allows to define the transition between two states of an element. */ transition?: any; /** * Defines when the transition will start. A value of ‘0s’ means the transition will execute as soon as the property is changed. Otherwise, the value specifies an offset from the moment the property is changed, and the transition will delay execution by that offset. */ transitionDelay?: any; /** * The 'transition-duration' property specifies the length of time a transition animation takes to complete. */ transitionDuration?: any; /** * The 'transition-property' property specifies the name of the CSS property to which the transition is applied. */ transitionProperty?: any; /** * Sets the pace of action within a transition */ transitionTimingFunction?: any; /** * The unicode-bidi CSS property specifies the level of embedding with respect to the bidirectional algorithm. */ unicodeBidi?: any; /** * unicode-range allows you to set a specific range of characters to be downloaded from a font (embedded using @font-face) and made available for use on the current page. */ unicodeRange?: any; /** * This is for all the high level UX stuff. */ userFocus?: any; /** * For inputing user content */ userInput?: any; /** * The vertical-align property controls how inline elements or text are vertically aligned compared to the baseline. If this property is used on table-cells it controls the vertical alignment of content of the table cell. */ verticalAlign?: any; /** * The visibility property specifies whether the boxes generated by an element are rendered. */ visibility?: any; /** * The voice-balance property sets the apparent position (in stereo sound) of the synthesized voice for spoken media. */ voiceBalance?: any; /** * The voice-duration property allows the author to explicitly set the amount of time it should take a speech synthesizer to read an element's content, for example to allow the speech to be synchronized with other media. With a value of auto (the default) the length of time it takes to read the content is determined by the content itself and the voice-rate property. */ voiceDuration?: any; /** * The voice-family property sets the speaker's voice used by a speech media agent to read an element. The speaker may be specified as a named character (to match a voice option in the speech reading software) or as a generic description of the age and gender of the voice. Similar to the font-family property for visual media, a comma-separated list of fallback options may be given in case the speech reader does not recognize the character name or cannot synthesize the requested combination of generic properties. */ voiceFamily?: any; /** * The voice-pitch property sets pitch or tone (high or low) for the synthesized speech when reading an element; the pitch may be specified absolutely or relative to the normal pitch for the voice-family used to read the text. */ voicePitch?: any; /** * The voice-range property determines how much variation in pitch or tone will be created by the speech synthesize when reading an element. Emphasized text, grammatical structures and punctuation may all be rendered as changes in pitch, this property determines how strong or obvious those changes are; large ranges are associated with enthusiastic or emotional speech, while small ranges are associated with flat or mechanical speech. */ voiceRange?: any; /** * The voice-rate property sets the speed at which the voice synthesized by a speech media agent will read content. */ voiceRate?: any; /** * The voice-stress property sets the level of vocal emphasis to be used for synthesized speech reading the element. */ voiceStress?: any; /** * The voice-volume property sets the volume for spoken content in speech media. It replaces the deprecated volume property. */ voiceVolume?: any; /** * The white-space property controls whether and how white space inside the element is collapsed, and whether lines may wrap at unforced "soft wrap" opportunities. */ whiteSpace?: any; /** * Obsolete: unsupported. */ whiteSpaceTreatment?: any; /** * Specifies the width of the content area of an element. The content area of the element width does not include the padding, border, and margin of the element. */ width?: any; /** * The word-break property is often used when there is long generated content that is strung together without and spaces or hyphens to beak apart. A common case of this is when there is a long URL that does not have any hyphens. This case could potentially cause the breaking of the layout as it could extend past the parent element. */ wordBreak?: any; /** * The word-spacing CSS property specifies the spacing behavior between "words". */ wordSpacing?: any; /** * An alias of css/properties/overflow-wrap, word-wrap defines whether to break words when the content exceeds the boundaries of its container. */ wordWrap?: any; /** * Specifies how exclusions affect inline content within block-level elements. Elements lay out their inline content in their content area but wrap around exclusion areas. */ wrapFlow?: any; /** * Set the value that is used to offset the inner wrap shape from other shapes. Inline content that intersects a shape with this property will be pushed by this shape's margin. */ wrapMargin?: any; /** * Obsolete and unsupported. Do not use. * This CSS property controls the text when it reaches the end of the block in which it is enclosed. */ wrapOption?: any; /** * writing-mode specifies if lines of text are laid out horizontally or vertically, and the direction which lines of text and blocks progress. */ writingMode?: any; [propertyName: string]: any; } interface HTMLAttributes extends DOMAttributes { // React-specific Attributes defaultChecked?: boolean; defaultValue?: string | string[]; // Standard HTML Attributes accept?: string; acceptCharset?: string; accessKey?: string; action?: string; allowFullScreen?: boolean; allowTransparency?: boolean; alt?: string; async?: boolean; autoComplete?: string; autoFocus?: boolean; autoPlay?: boolean; capture?: boolean; cellPadding?: number | string; cellSpacing?: number | string; charSet?: string; challenge?: string; checked?: boolean; classID?: string; className?: string; cols?: number; colSpan?: number; content?: string; contentEditable?: boolean; contextMenu?: string; controls?: boolean; coords?: string; crossOrigin?: string; data?: string; dateTime?: string; default?: boolean; defer?: boolean; dir?: string; disabled?: boolean; download?: any; draggable?: boolean; encType?: string; form?: string; formAction?: string; formEncType?: string; formMethod?: string; formNoValidate?: boolean; formTarget?: string; frameBorder?: number | string; headers?: string; height?: number | string; hidden?: boolean; high?: number; href?: string; hrefLang?: string; htmlFor?: string; httpEquiv?: string; icon?: string; id?: string; inputMode?: string; integrity?: string; is?: string; keyParams?: string; keyType?: string; kind?: string; label?: string; lang?: string; list?: string; loop?: boolean; low?: number; manifest?: string; marginHeight?: number; marginWidth?: number; max?: number | string; maxLength?: number; media?: string; mediaGroup?: string; method?: string; min?: number | string; minLength?: number; multiple?: boolean; muted?: boolean; name?: string; noValidate?: boolean; open?: boolean; optimum?: number; pattern?: string; placeholder?: string; poster?: string; preload?: string; radioGroup?: string; readOnly?: boolean; rel?: string; required?: boolean; role?: string; rows?: number; rowSpan?: number; sandbox?: string; scope?: string; scoped?: boolean; scrolling?: string; seamless?: boolean; selected?: boolean; shape?: string; size?: number; sizes?: string; span?: number; spellCheck?: boolean; src?: string; srcDoc?: string; srcLang?: string; srcSet?: string; start?: number; step?: number | string; style?: CSSProperties; summary?: string; tabIndex?: number; target?: string; title?: string; type?: string; useMap?: string; value?: string | string[]; width?: number | string; wmode?: string; wrap?: string; // RDFa Attributes about?: string; datatype?: string; inlist?: any; prefix?: string; property?: string; resource?: string; typeof?: string; vocab?: string; // Non-standard Attributes autoCapitalize?: string; autoCorrect?: string; autoSave?: string; color?: string; itemProp?: string; itemScope?: boolean; itemType?: string; itemID?: string; itemRef?: string; results?: number; security?: string; unselectable?: boolean; } interface SVGAttributes extends HTMLAttributes { clipPath?: string; cx?: number | string; cy?: number | string; d?: string; dx?: number | string; dy?: number | string; fill?: string; fillOpacity?: number | string; fontFamily?: string; fontSize?: number | string; fx?: number | string; fy?: number | string; gradientTransform?: string; gradientUnits?: string; markerEnd?: string; markerMid?: string; markerStart?: string; offset?: number | string; opacity?: number | string; patternContentUnits?: string; patternUnits?: string; points?: string; preserveAspectRatio?: string; r?: number | string; rx?: number | string; ry?: number | string; spreadMethod?: string; stopColor?: string; stopOpacity?: number | string; stroke?: string; strokeDasharray?: string; strokeLinecap?: string; strokeMiterlimit?: string; strokeOpacity?: number | string; strokeWidth?: number | string; textAnchor?: string; transform?: string; version?: string; viewBox?: string; x1?: number | string; x2?: number | string; x?: number | string; xlinkActuate?: string; xlinkArcrole?: string; xlinkHref?: string; xlinkRole?: string; xlinkShow?: string; xlinkTitle?: string; xlinkType?: string; xmlBase?: string; xmlLang?: string; xmlSpace?: string; y1?: number | string; y2?: number | string; y?: number | string; } // // React.DOM // ---------------------------------------------------------------------- interface ReactDOM { // HTML a: HTMLFactory; abbr: HTMLFactory; address: HTMLFactory; area: HTMLFactory; article: HTMLFactory; aside: HTMLFactory; audio: HTMLFactory; b: HTMLFactory; base: HTMLFactory; bdi: HTMLFactory; bdo: HTMLFactory; big: HTMLFactory; blockquote: HTMLFactory; body: HTMLFactory; br: HTMLFactory; button: HTMLFactory; canvas: HTMLFactory; caption: HTMLFactory; cite: HTMLFactory; showapi_res_code: HTMLFactory; col: HTMLFactory; colgroup: HTMLFactory; data: HTMLFactory; datalist: HTMLFactory; dd: HTMLFactory; del: HTMLFactory; details: HTMLFactory; dfn: HTMLFactory; dialog: HTMLFactory; div: HTMLFactory; dl: HTMLFactory; dt: HTMLFactory; em: HTMLFactory; embed: HTMLFactory; fieldset: HTMLFactory; figcaption: HTMLFactory; figure: HTMLFactory; footer: HTMLFactory; form: HTMLFactory; h1: HTMLFactory; h2: HTMLFactory; h3: HTMLFactory; h4: HTMLFactory; h5: HTMLFactory; h6: HTMLFactory; head: HTMLFactory; header: HTMLFactory; hr: HTMLFactory; html: HTMLFactory; i: HTMLFactory; iframe: HTMLFactory; img: HTMLFactory; input: HTMLFactory; ins: HTMLFactory; kbd: HTMLFactory; keygen: HTMLFactory; label: HTMLFactory; legend: HTMLFactory; li: HTMLFactory; link: HTMLFactory; main: HTMLFactory; map: HTMLFactory; mark: HTMLFactory; menu: HTMLFactory; menuitem: HTMLFactory; meta: HTMLFactory; meter: HTMLFactory; nav: HTMLFactory; noscript: HTMLFactory; object: HTMLFactory; ol: HTMLFactory; optgroup: HTMLFactory; option: HTMLFactory; output: HTMLFactory; p: HTMLFactory; param: HTMLFactory; picture: HTMLFactory; pre: HTMLFactory; progress: HTMLFactory; q: HTMLFactory; rp: HTMLFactory; rt: HTMLFactory; ruby: HTMLFactory; s: HTMLFactory; samp: HTMLFactory; script: HTMLFactory; section: HTMLFactory; select: HTMLFactory; small: HTMLFactory; source: HTMLFactory; span: HTMLFactory; strong: HTMLFactory; style: HTMLFactory; sub: HTMLFactory; summary: HTMLFactory; sup: HTMLFactory; table: HTMLFactory; tbody: HTMLFactory; td: HTMLFactory; textarea: HTMLFactory; tfoot: HTMLFactory; th: HTMLFactory; thead: HTMLFactory; time: HTMLFactory; title: HTMLFactory; tr: HTMLFactory; track: HTMLFactory; u: HTMLFactory; ul: HTMLFactory; "var": HTMLFactory; video: HTMLFactory; wbr: HTMLFactory; // SVG svg: SVGFactory; circle: SVGFactory; defs: SVGFactory; ellipse: SVGFactory; g: SVGFactory; image: SVGFactory; line: SVGFactory; linearGradient: SVGFactory; mask: SVGFactory; path: SVGFactory; pattern: SVGFactory; polygon: SVGFactory; polyline: SVGFactory; radialGradient: SVGFactory; rect: SVGFactory; stop: SVGFactory; text: SVGFactory; tspan: SVGFactory; } // // React.PropTypes // ---------------------------------------------------------------------- interface Validator { (object: T, key: string, componentName: string): Error; } interface Requireable extends Validator { isRequired: Validator; } interface ValidationMap { [key: string]: Validator; } interface ReactPropTypes { any: Requireable; array: Requireable; bool: Requireable; func: Requireable; number: Requireable; object: Requireable; string: Requireable; node: Requireable; element: Requireable; instanceOf(expectedClass: {}): Requireable; oneOf(types: any[]): Requireable; oneOfType(types: Validator[]): Requireable; arrayOf(type: Validator): Requireable; objectOf(type: Validator): Requireable; shape(type: ValidationMap): Requireable; } // // React.Children // ---------------------------------------------------------------------- interface ReactChildren { map(children: ReactNode, fn: (child: ReactChild, index: number) => T): T[]; forEach(children: ReactNode, fn: (child: ReactChild, index: number) => any): void; count(children: ReactNode): number; only(children: ReactNode): ReactElement; toArray(children: ReactNode): ReactChild[]; } // // Browser Interfaces // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts // ---------------------------------------------------------------------- interface AbstractView { styleMedia: StyleMedia; document: Document; } interface Touch { identifier: number; target: EventTarget; screenX: number; screenY: number; clientX: number; clientY: number; pageX: number; pageY: number; } interface TouchList { [index: number]: Touch; length: number; item(index: number): Touch; identifiedTouch(identifier: number): Touch; } } declare module "react" { export = __React; } declare namespace JSX { import React = __React; interface Element extends React.ReactElement { } interface ElementClass extends React.Component { render(): JSX.Element; } interface ElementAttributesProperty { props: {}; } interface IntrinsicAttributes { key?: string | number; } interface IntrinsicClassAttributes { ref?: string | ((classInstance: T) => void); } interface IntrinsicElements { // HTML a: React.HTMLProps; abbr: React.HTMLProps; address: React.HTMLProps; area: React.HTMLProps; article: React.HTMLProps; aside: React.HTMLProps; audio: React.HTMLProps; b: React.HTMLProps; base: React.HTMLProps; bdi: React.HTMLProps; bdo: React.HTMLProps; big: React.HTMLProps; blockquote: React.HTMLProps; body: React.HTMLProps; br: React.HTMLProps; button: React.HTMLProps; canvas: React.HTMLProps; caption: React.HTMLProps; cite: React.HTMLProps; showapi_res_code: React.HTMLProps; col: React.HTMLProps; colgroup: React.HTMLProps; data: React.HTMLProps; datalist: React.HTMLProps; dd: React.HTMLProps; del: React.HTMLProps; details: React.HTMLProps; dfn: React.HTMLProps; dialog: React.HTMLProps; div: React.HTMLProps; dl: React.HTMLProps; dt: React.HTMLProps; em: React.HTMLProps; embed: React.HTMLProps; fieldset: React.HTMLProps; figcaption: React.HTMLProps; figure: React.HTMLProps; footer: React.HTMLProps; form: React.HTMLProps; h1: React.HTMLProps; h2: React.HTMLProps; h3: React.HTMLProps; h4: React.HTMLProps; h5: React.HTMLProps; h6: React.HTMLProps; head: React.HTMLProps; header: React.HTMLProps; hr: React.HTMLProps; html: React.HTMLProps; i: React.HTMLProps; iframe: React.HTMLProps; img: React.HTMLProps; input: React.HTMLProps; ins: React.HTMLProps; kbd: React.HTMLProps; keygen: React.HTMLProps; label: React.HTMLProps; legend: React.HTMLProps; li: React.HTMLProps; link: React.HTMLProps; main: React.HTMLProps; map: React.HTMLProps; mark: React.HTMLProps; menu: React.HTMLProps; menuitem: React.HTMLProps; meta: React.HTMLProps; meter: React.HTMLProps; nav: React.HTMLProps; noscript: React.HTMLProps; object: React.HTMLProps; ol: React.HTMLProps; optgroup: React.HTMLProps; option: React.HTMLProps; output: React.HTMLProps; p: React.HTMLProps; param: React.HTMLProps; picture: React.HTMLProps; pre: React.HTMLProps; progress: React.HTMLProps; q: React.HTMLProps; rp: React.HTMLProps; rt: React.HTMLProps; ruby: React.HTMLProps; s: React.HTMLProps; samp: React.HTMLProps; script: React.HTMLProps; section: React.HTMLProps; select: React.HTMLProps; small: React.HTMLProps; source: React.HTMLProps; span: React.HTMLProps; strong: React.HTMLProps; style: React.HTMLProps; sub: React.HTMLProps; summary: React.HTMLProps; sup: React.HTMLProps; table: React.HTMLProps; tbody: React.HTMLProps; td: React.HTMLProps; textarea: React.HTMLProps; tfoot: React.HTMLProps; th: React.HTMLProps; thead: React.HTMLProps; time: React.HTMLProps; title: React.HTMLProps; tr: React.HTMLProps; track: React.HTMLProps; u: React.HTMLProps; ul: React.HTMLProps; "var": React.HTMLProps; video: React.HTMLProps; wbr: React.HTMLProps; // SVG svg: React.SVGProps; circle: React.SVGProps; clipPath: React.SVGProps; defs: React.SVGProps; ellipse: React.SVGProps; g: React.SVGProps; image: React.SVGProps; line: React.SVGProps; linearGradient: React.SVGProps; mask: React.SVGProps; path: React.SVGProps; pattern: React.SVGProps; polygon: React.SVGProps; polyline: React.SVGProps; radialGradient: React.SVGProps; rect: React.SVGProps; stop: React.SVGProps; text: React.SVGProps; tspan: React.SVGProps; } } ================================================ FILE: .vscode/typings/react-native/react-native.d.ts ================================================ // Type definitions for react-native 0.14 // Project: https://github.com/facebook/react-native // Definitions by: Bruno Grieder // Definitions: https://github.com/borisyankov/DefinitelyTyped /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // USING: these definitions are meant to be used with the TSC compiler target set to ES6 // // USAGE EXAMPLES: check the RNTSExplorer project at https://github.com/bgrieder/RNTSExplorer // // CONTRIBUTING: please open pull requests and make sure that the changes do not break RNTSExplorer (they should not) // Do not hesitate to open a pull request against RNTSExplorer to provide an example for a case not covered by the current App // // CREDITS: This work is based on an original work made by Bernd Paradies: https://github.com/bparadie // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// //so we know what is "original" React import React = __React; //react-native "extends" react declare namespace __React { /** * Represents the completion of an asynchronous operation * @see lib.es6.d.ts */ export interface Promise { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then( onfulfilled?: ( value: T ) => TResult | Promise, onrejected?: ( reason: any ) => TResult | Promise ): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ catch( onrejected?: ( reason: any ) => T | Promise ): Promise; // not in lib.es6.d.ts but called by react-native done( callback?: ( value: T ) => void ): void; } export interface PromiseConstructor { /** * A reference to the prototype. */ prototype: Promise; /** * Creates a new Promise. * @param init A callback used to initialize the promise. This callback is passed two arguments: * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new ( init: ( resolve: ( value?: T | Promise ) => void, reject: ( reason?: any ) => void ) => void ): Promise; ( init: ( resolve: ( value?: T | Promise ) => void, reject: ( reason?: any ) => void ) => void ): Promise; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all( values: (T | Promise)[] ): Promise; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of values. * @returns A new Promise. */ all( values: Promise[] ): Promise; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race( values: (T | Promise)[] ): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ reject( reason: any ): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ reject( reason: any ): Promise; /** * Creates a new resolved promise for the provided value. * @param value A promise. * @returns A promise whose internal state matches the provided promise. */ resolve( value: T | Promise ): Promise; /** * Creates a new resolved promise . * @returns A resolved promise. */ resolve(): Promise; } // @see lib.es6.d.ts export var Promise: PromiseConstructor; //TODO: BGR: Replace with ComponentClass ? // node_modules/react-tools/src/classic/class/ReactClass.js export interface ReactClass { // TODO: } // see react-jsx.d.ts export function createElement

( type: React.ReactType, props?: P, ...children: React.ReactNode[] ): React.ReactElement

; export type Runnable = ( appParameters: any ) => void; // Similar to React.SyntheticEvent except for nativeEvent interface NativeSyntheticEvent { bubbles: boolean cancelable: boolean currentTarget: EventTarget defaultPrevented: boolean eventPhase: number isTrusted: boolean nativeEvent: T preventDefault(): void stopPropagation(): void target: EventTarget timeStamp: Date type: string } export interface NativeTouchEvent { /** * Array of all touch events that have changed since the last event */ changedTouches: NativeTouchEvent[] /** * The ID of the touch */ identifier: string /** * The X position of the touch, relative to the element */ locationX: number /** * The Y position of the touch, relative to the element */ locationY: number /** * The X position of the touch, relative to the screen */ pageX: number /** * The Y position of the touch, relative to the screen */ pageY: number /** * The node id of the element receiving the touch event */ target: string /** * A time identifier for the touch, useful for velocity calculation */ timestamp: number /** * Array of all current touches on the screen */ touches : NativeTouchEvent[] } export interface GestureResponderEvent extends NativeSyntheticEvent { } export interface PointProperties { x: number y: number } export interface Insets { top?: number left?: number bottom?: number right?: number } /** * //FIXME: need to find documentation on which compoenent is a native (i.e. non composite component) */ export interface NativeComponent { setNativeProps: ( props: Object ) => void } /** * //FIXME: need to find documentation on which component is a TTouchable and can implement that interface * @see React.DOMAtributes */ export interface Touchable { onTouchStart?: ( event: GestureResponderEvent ) => void onTouchMove?: ( event: GestureResponderEvent ) => void onTouchEnd?: ( event: GestureResponderEvent ) => void onTouchCancel?: ( event: GestureResponderEvent ) => void onTouchEndCapture?: ( event: GestureResponderEvent ) => void } export type AppConfig = { appKey: string; component: ReactClass; run?: Runnable; } // https://github.com/facebook/react-native/blob/master/Libraries/AppRegistry/AppRegistry.js export class AppRegistry { static registerConfig( config: AppConfig[] ): void; static registerComponent( appKey: string, getComponentFunc: () => React.ComponentClass ): string; static registerRunnable( appKey: string, func: Runnable ): string; static runApplication( appKey: string, appParameters: any ): void; } export interface LayoutAnimationTypes { spring: string linear: string easeInEaseOut: string easeIn: string easeOut: string } export interface LayoutAnimationProperties { opacity: string scaleXY: string } export interface LayoutAnimationAnim { duration?: number delay?: number springDamping?: number initialVelocity?: number type?: string //LayoutAnimationTypes property?: string //LayoutAnimationProperties } export interface LayoutAnimationConfig { duration: number create?: LayoutAnimationAnim update?: LayoutAnimationAnim delete?: LayoutAnimationAnim } export interface LayoutAnimationStatic { configureNext: ( config: LayoutAnimationConfig, onAnimationDidEnd?: () => void, onError?: ( error?: any ) => void ) => void create: ( duration: number, type?: string, creationProp?: string ) => LayoutAnimationConfig Types: LayoutAnimationTypes Properties: LayoutAnimationProperties configChecker: ( conf: {config: LayoutAnimationConfig}, name: string, next: string ) => void Presets : { easeInEaseOut: LayoutAnimationConfig linear:LayoutAnimationConfig spring: LayoutAnimationConfig } } /** * Flex Prop Types * @see https://facebook.github.io/react-native/docs/flexbox.html#proptypes * @see LayoutPropTypes.js */ export interface FlexStyle { alignItems?: string; //enum('flex-start', 'flex-end', 'center', 'stretch') alignSelf?: string// enum('auto', 'flex-start', 'flex-end', 'center', 'stretch') borderBottomWidth?: number borderLeftWidth?: number borderRightWidth?: number borderTopWidth?: number borderWidth?: number bottom?: number flex?: number flexDirection?: string // enum('row', 'column') flexWrap?: string // enum('wrap', 'nowrap') height?: number justifyContent?: string // enum('flex-start', 'flex-end', 'center', 'space-between', 'space-around') left?: number margin?: number marginBottom?: number marginHorizontal?: number marginLeft?: number marginRight?: number marginTop?: number marginVertical?: number padding?: number paddingBottom?: number paddingHorizontal?: number paddingLeft?: number paddingRight?: number paddingTop?: number paddingVertical?: number position?: string // enum('absolute', 'relative') right?: number top?: number width?: number } export interface TransformsStyle { transform?: [{perspective: number}, {rotate: string}, {rotateX: string}, {rotateY: string}, {rotateZ: string}, {scale: number}, {scaleX: number}, {scaleY: number}, {translateX: number}, {translateY: number}, {skewX: string}, {skewY: string}] transformMatrix?: Array rotation?: number scaleX?: number scaleY?: number translateX?: number translateY?: number } export interface StyleSheetProperties { // TODO: } export interface LayoutRectangle { x: number; y: number; width: number; height: number; } // @see TextProperties.onLayout export interface LayoutChangeEvent { nativeEvent: { layout: LayoutRectangle } } // @see https://facebook.github.io/react-native/docs/text.html#style export interface TextStyle extends ViewStyle { color?: string fontFamily?: string fontSize?: number fontStyle?: string // 'normal' | 'italic'; fontWeight?: string // enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900') letterSpacing?: number lineHeight?: number textAlign?: string // enum("auto", 'left', 'right', 'center') textDecorationLine?: string // enum("none", 'underline', 'line-through', 'underline line-through') textDecorationStyle?: string // enum("solid", 'double', 'dotted', 'dashed') textDecorationColor?: string writingDirection?: string; //enum("auto", 'ltr', 'rtl') //containerBackgroundColor?: string } export interface TextPropertiesIOS { /** * When true, no visual change is made when text is pressed down. * By default, a gray oval highlights the text on press down. */ suppressHighlighting?: boolean } // https://facebook.github.io/react-native/docs/text.html#props export interface TextProperties extends React.Props { /** * Specifies should fonts scale to respect Text Size accessibility setting on iOS. */ allowFontScaling?: boolean /** * Used to truncate the text with an elipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number. */ numberOfLines?: number /** * Invoked on mount and layout changes with * * {nativeEvent: { layout: {x, y, width, height}}}. */ onLayout?: ( event: LayoutChangeEvent ) => void /** * This function is called on press. * Text intrinsically supports press handling with a default highlight state (which can be disabled with suppressHighlighting). */ onPress?: () => void /** * @see https://facebook.github.io/react-native/docs/text.html#style */ style?: TextStyle /** * Used to locate this view in end-to-end tests. */ testID?: string } /** * A React component for displaying text which supports nesting, styling, and touch handling. */ export interface TextStatic extends React.ComponentClass { } /** * IOS Specific properties for TextInput * @see https://facebook.github.io/react-native/docs/textinput.html#props */ export interface TextInputIOSProperties { /** * If true, the text field will blur when submitted. * The default value is true. */ blurOnSubmit?: boolean /** * enum('never', 'while-editing', 'unless-editing', 'always') * When the clear button should appear on the right side of the text view */ clearButtonMode?: string /** * If true, clears the text field automatically when editing begins */ clearTextOnFocus?: boolean /** * If true, the keyboard disables the return key when there is no text and automatically enables it when there is text. * The default value is false. */ enablesReturnKeyAutomatically?: boolean /** * Callback that is called when a key is pressed. * Pressed key value is passed as an argument to the callback handler. * Fires before onChange callbacks. */ onKeyPress?: () => void /** * enum('default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call') * Determines how the return key should look. */ returnKeyType?: string /** * If true, all text will automatically be selected on focus */ selectTextOnFocus?: boolean /** * //FIXME: requires typing * See DocumentSelectionState.js, some state that is responsible for maintaining selection information for a document */ selectionState?: any } /** * Android Specific properties for TextInput * @see https://facebook.github.io/react-native/docs/textinput.html#props */ export interface TextInputAndroidProperties { /** * Sets the number of lines for a TextInput. * Use it with multiline set to true to be able to fill the lines. */ numberOfLines?: number /** * enum('start', 'center', 'end') * Set the position of the cursor from where editing will begin. */ textAlign?: string /** * enum('top', 'center', 'bottom') * Aligns text vertically within the TextInput. */ textAlignVertical?: string /** * The color of the textInput underline. */ underlineColorAndroid?: string } /** * @see https://facebook.github.io/react-native/docs/textinput.html#props */ export interface TextInputProperties extends TextInputIOSProperties, TextInputAndroidProperties, React.Props { /** * Can tell TextInput to automatically capitalize certain characters. * characters: all characters, * words: first letter of each word * sentences: first letter of each sentence (default) * none: don't auto capitalize anything * * https://facebook.github.io/react-native/docs/textinput.html#autocapitalize */ autoCapitalize?: string /** * If false, disables auto-correct. * The default value is true. */ autoCorrect?: boolean /** * If true, focuses the input on componentDidMount. * The default value is false. */ autoFocus?: boolean /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you don't want to deal with listening to events * and updating the value prop to keep the controlled state in sync. */ defaultValue?: string /** * If false, text is not editable. The default value is true. */ editable?: boolean /** * enum("default", 'numeric', 'email-address', "ascii-capable", 'numbers-and-punctuation', 'url', 'number-pad', 'phone-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search') * Determines which keyboard to open, e.g.numeric. * The following values work across platforms: - default - numeric - email-address */ keyboardType?: string /** * Limits the maximum number of characters that can be entered. * Use this instead of implementing the logic in JS to avoid flicker. */ maxLength?: number /** * If true, the text input can be multiple lines. The default value is false. */ multiline?: boolean /** * Callback that is called when the text input is blurred */ onBlur?: () => void /** * Callback that is called when the text input's text changes. */ onChange?: ( event: {nativeEvent: {text: string}} ) => void /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText?: ( text: string ) => void /** * Callback that is called when text input ends. */ onEndEditing?: ( event: {nativeEvent: {text: string}} ) => void /** * Callback that is called when the text input is focused */ onFocus?: () => void /** * Invoked on mount and layout changes with {x, y, width, height}. */ onLayout?: ( event: {nativeEvent: {x: number, y: number, width: number, height: number}} ) => void /** * Callback that is called when the text input's submit button is pressed. */ onSubmitEditing?: ( event: {nativeEvent: {text: string}} ) => void /** * //FIXME: Not part of the doc but found in examples */ password?: boolean /** * The string that will be rendered before text input has been entered */ placeholder?: string /** * The text color of the placeholder string */ placeholderTextColor?: string /** * If true, the text input obscures the text entered so that sensitive text like passwords stay secure. * The default value is false. */ secureTextEntry?: boolean /** * Styles */ style?: TextStyle /** * Used to locate this view in end-to-end tests */ testID?: string /** * The value to show for the text input. TextInput is a controlled component, * which means the native value will be forced to match this value prop if provided. * For most uses this works great, but in some cases this may cause flickering - one common cause is preventing edits by keeping value the same. * In addition to simply setting the same value, either set editable={false}, * or set/update maxLength to prevent unwanted edits without flicker. */ value?: string } export interface TextInputStatic extends NativeComponent, React.ComponentClass { blur: () => void focus: () => void } /** * Gesture recognition on mobile devices is much more complicated than web. * A touch can go through several phases as the app determines what the user's intention is. * For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. * This can even change during the duration of a touch. There can also be multiple simultaneous touches. * * The touch responder system is needed to allow components to negotiate these touch interactions * without any additional knowledge about their parent or child components. * This system is implemented in ResponderEventPlugin.js, which contains further details and documentation. * * Best Practices * Users can feel huge differences in the usability of web apps vs. native, and this is one of the big causes. * Every action should have the following attributes: * Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture * Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away * * These features make users more comfortable while using an app, * because it allows people to experiment and interact without fear of making mistakes. * * TouchableHighlight and Touchable* * The responder system can be complicated to use. * So we have provided an abstract Touchable implementation for things that should be "tappable". * This uses the responder system and allows you to easily configure tap interactions declaratively. * Use TouchableHighlight anywhere where you would use a button or link on web. */ export interface GestureResponderHandlers { /** * A view can become the touch responder by implementing the correct negotiation methods. * There are two methods to ask the view if it wants to become responder: */ /** * Does this view want to become responder on the start of a touch? */ onStartShouldSetResponder?: ( event: GestureResponderEvent ) => boolean /** * Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness? */ onMoveShouldSetResponder?: ( event: GestureResponderEvent ) => boolean /** * If the View returns true and attempts to become the responder, one of the following will happen: */ /** * The View is now responding for touch events. * This is the time to highlight and show the user what is happening */ onResponderGrant?: ( event: GestureResponderEvent ) => void /** * Something else is the responder right now and will not release it */ onResponderReject?: ( event: GestureResponderEvent ) => void /** * If the view is responding, the following handlers can be called: */ /** * The user is moving their finger */ onResponderMove?: ( event: GestureResponderEvent ) => void /** * Fired at the end of the touch, ie "touchUp" */ onResponderRelease?: ( event: GestureResponderEvent ) => void /** * Something else wants to become responder. * Should this view release the responder? Returning true allows release */ onResponderTerminationRequest?: ( event: GestureResponderEvent ) => boolean /** * The responder has been taken from the View. * Might be taken by other views after a call to onResponderTerminationRequest, * or might be taken by the OS without asking (happens with control center/ notification center on iOS) */ onResponderTerminate?: ( event: GestureResponderEvent ) => void /** * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, * where the deepest node is called first. * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. * This is desirable in most cases, because it makes sure all controls and buttons are usable. * * However, sometimes a parent will want to make sure that it becomes responder. * This can be handled by using the capture phase. * Before the responder system bubbles up from the deepest component, * it will do a capture phase, firing on*ShouldSetResponderCapture. * So if a parent View wants to prevent the child from becoming responder on a touch start, * it should have a onStartShouldSetResponderCapture handler which returns true. */ onStartShouldSetResponderCapture?: ( event: GestureResponderEvent ) => boolean /** * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, * where the deepest node is called first. * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. * This is desirable in most cases, because it makes sure all controls and buttons are usable. * * However, sometimes a parent will want to make sure that it becomes responder. * This can be handled by using the capture phase. * Before the responder system bubbles up from the deepest component, * it will do a capture phase, firing on*ShouldSetResponderCapture. * So if a parent View wants to prevent the child from becoming responder on a touch start, * it should have a onStartShouldSetResponderCapture handler which returns true. */ onMoveShouldSetResponderCapture?: () => void; } // @see https://facebook.github.io/react-native/docs/view.html#style export interface ViewStyle extends FlexStyle, TransformsStyle { backgroundColor?: string; borderBottomColor?: string; borderBottomLeftRadius?: number; borderBottomRightRadius?: number; borderColor?: string; borderLeftColor?: string; borderRadius?: number; borderRightColor?: string; borderTopColor?: string; borderTopLeftRadius?: number; borderTopRightRadius?: number; opacity?: number; overflow?: string; // enum('visible', 'hidden') shadowColor?: string; shadowOffset?: {width: number, height: number}; shadowOpacity?: number; shadowRadius?: number; } export interface ViewPropertiesIOS { /** * Provides additional traits to screen reader. * By default no traits are provided unless specified otherwise in element * * @enum('none', 'button', 'link', 'header', 'search', 'image', 'selected', 'plays', 'key', 'text','summary', 'disabled', 'frequentUpdates', 'startsMedia', 'adjustable', 'allowsDirectInteraction', 'pageTurn') */ accessibilityTraits?: string | string[]; /** * Whether this view should be rendered as a bitmap before compositing. * * On iOS, this is useful for animations and interactions that do not modify this component's dimensions nor its children; * for example, when translating the position of a static view, rasterization allows the renderer to reuse a cached bitmap of a static view * and quickly composite it during each frame. * * Rasterization incurs an off-screen drawing pass and the bitmap consumes memory. * Test and measure when using this property. */ shouldRasterizeIOS?: boolean } export interface ViewPropertiesAndroid { /** * Indicates to accessibility services to treat UI component like a native one. * Works for Android only. * * @enum('none', 'button', 'radiobutton_checked', 'radiobutton_unchecked' ) */ accessibilityComponentType?: string /** * Indicates to accessibility services whether the user should be notified when this view changes. * Works for Android API >= 19 only. * See http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion for references. */ accessibilityLiveRegion?: string /** * Views that are only used to layout their children or otherwise don't draw anything * may be automatically removed from the native hierarchy as an optimization. * Set this property to false to disable this optimization and ensure that this View exists in the native view hierarchy. */ collapsable?: boolean /** * Controls how view is important for accessibility which is if it fires accessibility events * and if it is reported to accessibility services that query the screen. * Works for Android only. See http://developer.android.com/reference/android/R.attr.html#importantForAccessibility for references. * * Possible values: * 'auto' - The system determines whether the view is important for accessibility - default (recommended). * 'yes' - The view is important for accessibility. * 'no' - The view is not important for accessibility. * 'no-hide-descendants' - The view is not important for accessibility, nor are any of its descendant views. */ importantForAccessibility?: string /** * Whether this view needs to rendered offscreen and composited with an alpha in order to preserve 100% correct colors and blending behavior. * The default (false) falls back to drawing the component and its children * with an alpha applied to the paint used to draw each element instead of rendering the full component offscreen and compositing it back with an alpha value. * This default may be noticeable and undesired in the case where the View you are setting an opacity on * has multiple overlapping elements (e.g. multiple overlapping Views, or text and a background). * * Rendering offscreen to preserve correct alpha behavior is extremely expensive * and hard to debug for non-native developers, which is why it is not turned on by default. * If you do need to enable this property for an animation, * consider combining it with renderToHardwareTextureAndroid if the view contents are static (i.e. it doesn't need to be redrawn each frame). * If that property is enabled, this View will be rendered off-screen once, * saved in a hardware texture, and then composited onto the screen with an alpha each frame without having to switch rendering targets on the GPU. */ needsOffscreenAlphaCompositing?: boolean /** * Whether this view should render itself (and all of its children) into a single hardware texture on the GPU. * * On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale: * in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can just be * re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the interaction/animation. */ renderToHardwareTextureAndroid?: boolean; } /** * @see https://facebook.github.io/react-native/docs/view.html#props */ export interface ViewProperties extends ViewPropertiesAndroid, ViewPropertiesIOS, GestureResponderHandlers, Touchable, React.Props { /** * Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the Text nodes separated by space. */ accessibilityLabel?: string; /** * When true, indicates that the view is an accessibility element. * By default, all the touchable elements are accessible. */ accessible?: boolean; /** * When `accessible` is true, the system will try to invoke this function when the user performs accessibility tap gesture. */ onAcccessibilityTap?: () => void; /** * Invoked on mount and layout changes with * * {nativeEvent: { layout: {x, y, width, height}}}. */ onLayout?: ( event: LayoutChangeEvent ) => void; /** * When accessible is true, the system will invoke this function when the user performs the magic tap gesture. */ onMagicTap?: () => void; /** * * In the absence of auto property, none is much like CSS's none value. box-none is as if you had applied the CSS class: * * .box-none { * pointer-events: none; * } * .box-none * { * pointer-events: all; * } * * box-only is the equivalent of * * .box-only { * pointer-events: all; * } * .box-only * { * pointer-events: none; * } * * But since pointerEvents does not affect layout/appearance, and we are already deviating from the spec by adding additional modes, * we opt to not include pointerEvents on style. On some platforms, we would need to implement it as a className anyways. Using style or not is an implementation detail of the platform. */ pointerEvents?: string; /** * * This is a special performance property exposed by RCTView and is useful for scrolling content when there are many subviews, * most of which are offscreen. For this property to be effective, it must be applied to a view that contains many subviews that extend outside its bound. * The subviews must also have overflow: hidden, as should the containing view (or one of its superviews). */ removeClippedSubviews?: boolean style?: ViewStyle; /** * Used to locate this view in end-to-end tests. */ testID?: string; } /** * The most fundamental component for building UI, View is a container that supports layout with flexbox, style, some touch handling, * and accessibility controls, and is designed to be nested inside other views and to have 0 to many children of any type. * View maps directly to the native view equivalent on whatever platform React is running on, * whether that is a UIView,

, android.view, etc. */ export interface ViewStatic extends NativeComponent, React.ComponentClass { } /** * //FIXME: No documentation extracted from showapi_res_code comment on WebView.ios.js */ export interface NavState { url?: string title?: string loading?: boolean canGoBack?: boolean canGoForward?: boolean; [key: string]: any } export interface WebViewPropertiesAndroid { /** * Used for android only, JS is enabled by default for WebView on iOS */ javaScriptEnabledAndroid?: boolean } export interface WebViewPropertiesIOS { /** * Used for iOS only, sets whether the webpage scales to fit the view and the user can change the scale */ scalesPageToFit?: boolean } /** * @see https://facebook.github.io/react-native/docs/webview.html#props */ export interface WebViewProperties extends WebViewPropertiesAndroid, WebViewPropertiesIOS, React.Props { automaticallyAdjustContentInsets?: boolean bounces?: boolean contentInset?: Insets html?: string /** * Sets the JS to be injected when the webpage loads. */ injectedJavaScript?: string onNavigationStateChange?: ( event: NavState ) => void /** * Allows custom handling of any webview requests by a JS handler. * Return true or false from this method to continue loading the request. */ onShouldStartLoadWithRequest?: () => boolean /** * view to show if there's an error */ renderError?: () => ViewStatic /** * loading indicator to show */ renderLoading?: () => ViewStatic scrollEnabled?: boolean startInLoadingState?: boolean style?: ViewStyle url: string } export interface WebViewStatic extends React.ComponentClass { goBack: () => void goForward: () => void reload: () => void } /** * @see */ export interface SegmentedControlIOSProperties { /// TODO } export interface NavigatorIOSProperties extends React.Props { /** * NavigatorIOS uses "route" objects to identify child views, their props, and navigation bar configuration. * "push" and all the other navigation operations expect routes to be like this */ initialRoute?: Route /** * The default wrapper style for components in the navigator. * A common use case is to set the backgroundColor for every page */ itemWrapperStyle?: ViewStyle /** * A Boolean value that indicates whether the navigation bar is hidden */ navigationBarHidden?: boolean /** * A Boolean value that indicates whether to hide the 1px hairline shadow */ shadowHidden?: boolean /** * The color used for buttons in the navigation bar */ tintColor?: string /** * The text color of the navigation bar title */ titleTextColor?: string /** * A Boolean value that indicates whether the navigation bar is translucent */ translucent?: boolean /** * NOT IN THE DOC BUT IN THE EXAMPLES */ style?: ViewStyle } /** * A navigator is an object of navigation functions that a view can call. * It is passed as a prop to any component rendered by NavigatorIOS. * * Navigator functions are also available on the NavigatorIOS component: * * @see https://facebook.github.io/react-native/docs/navigatorios.html#navigator */ export interface NavigationIOS { /** * Navigate forward to a new route */ push: ( route: Route ) => void /** * Go back one page */ pop: () => void /** * Go back N pages at once. When N=1, behavior matches pop() */ popN: ( n: number ) => void /** * Replace the route for the current page and immediately load the view for the new route */ replace: ( route: Route ) => void /** * Replace the route/view for the previous page */ replacePrevious: ( route: Route ) => void /** * Replaces the previous route/view and transitions back to it */ replacePreviousAndPop: ( route: Route ) => void /** * Replaces the top item and popToTop */ resetTo: ( route: Route ) => void /** * Go back to the item for a particular route object */ popToRoute( route: Route ): void /** * Go back to the top item */ popToTop(): void } export interface NavigatorIOSStatic extends NavigationIOS, React.ComponentClass { } /** * @see https://facebook.github.io/react-native/docs/activityindicatorios.html#props */ export interface ActivityIndicatorIOSProperties extends React.Props { /** * Whether to show the indicator (true, the default) or hide it (false). */ animating?: boolean /** * The foreground color of the spinner (default is gray). */ color?: string /** * Whether the indicator should hide when not animating (true by default). */ hidesWhenStopped?: boolean /** * Invoked on mount and layout changes with */ onLayout?: ( event: {nativeEvent: { layout: {x: number, y: number , width: number, height: number}}} ) => void /** * Size of the indicator. * Small has a height of 20, large has a height of 36. * * enum('small', 'large') */ size?: string style?: ViewStyle } export interface ActivityIndicatorIOSStatic extends React.ComponentClass { } export interface DatePickerIOSProperties extends React.Props { /** * The currently selected date. */ date?: Date /** * Maximum date. * Restricts the range of possible date/time values. */ maximumDate?: Date /** * Maximum date. * Restricts the range of possible date/time values. */ minimumDate?: Date /** * enum(1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30) * The interval at which minutes can be selected. */ minuteInterval?: number /** * enum('date', 'time', 'datetime') * The date picker mode. */ mode?: string /** * Date change handler. * This is called when the user changes the date or time in the UI. * The first and only argument is a Date object representing the new date and time. */ onDateChange?: ( newDate: Date ) => void /** * Timezone offset in minutes. * By default, the date picker will use the device's timezone. With this parameter, it is possible to force a certain timezone offset. * For instance, to show times in Pacific Standard Time, pass -7 * 60. */ timeZoneOffsetInMinutes?: number } export interface DatePickerIOSStatic extends React.ComponentClass { } /** * @see PickerIOS.ios.js */ export interface PickerIOSItemProperties extends React.Props { value?: string | number label?: string } /** * @see PickerIOS.ios.js */ export interface PickerIOSItemStatic extends React.ComponentClass { } /** * @see https://facebook.github.io/react-native/docs/pickerios.html * @see PickerIOS.ios.js */ export interface PickerIOSProperties extends React.Props { onValueChange?: ( value: string | number ) => void selectedValue?: string | number style?: ViewStyle } /** * @see https://facebook.github.io/react-native/docs/pickerios.html * @see PickerIOS.ios.js */ export interface PickerIOSStatic extends React.ComponentClass { Item: PickerIOSItemStatic } /** * @see https://facebook.github.io/react-native/docs/sliderios.html */ export interface SliderIOSProperties extends React.Props { /** * If true the user won't be able to move the slider. Default value is false. */ disabled?: boolean /** * Initial maximum value of the slider. Default value is 1. */ maximumValue?: number /** * The color used for the track to the right of the button. Overrides the default blue gradient image. */ maximumTrackTintColor?: string /** * Initial minimum value of the slider. Default value is 0. */ minimumValue?: number /** * The color used for the track to the left of the button. Overrides the default blue gradient image. */ minimumTrackTintColor?: string /** * Callback called when the user finishes changing the value (e.g. when the slider is released). */ onSlidingComplete?: () => void /** * Callback continuously called while the user is dragging the slider. */ onValueChange?: ( value: number ) => void /** * Step value of the slider. * The value should be between 0 and (maximumValue - minimumValue). * Default value is 0. */ step?: number /** * Used to style and layout the Slider. * @see StyleSheet.js and ViewStylePropTypes.js for more info. */ style?: ViewStyle /** * Initial value of the slider. * The value should be between minimumValue and maximumValue, which default to 0 and 1 respectively. * Default value is 0. * * This is not a controlled component, e.g. if you don't update the value, the component won't be reset to its inital value. */ value?: number } export interface SliderIOSStatic extends React.ComponentClass { } /** * //FIXME: no dcumentation, inferred * @see SwitchIOS.ios.js */ export interface SwitchIOSStyle extends ViewStyle { height?: number width?: number } /** * https://facebook.github.io/react-native/docs/switchios.html#props */ export interface SwitchIOSProperties extends React.Props { /** * If true the user won't be able to toggle the switch. Default value is false. */ disabled?: boolean /** * Background color when the switch is turned on. */ onTintColor?: string /** * Callback that is called when the user toggles the switch. */ onValueChange?: ( value: boolean ) => void /** * Background color for the switch round button. */ thumbTintColor?: string /** * Background color when the switch is turned off. */ tintColor?: string /** * The value of the switch, if true the switch will be turned on. Default value is false. */ value?: boolean style?: SwitchIOSStyle } /** * * Use SwitchIOS to render a boolean input on iOS. * * This is a controlled component, so you must hook in to the onValueChange callback and update the value prop in order for the component to update, * otherwise the user's change will be reverted immediately to reflect props.value as the source of truth. * * @see https://facebook.github.io/react-native/docs/switchios.html */ export interface SwitchIOSStatic extends React.ComponentClass { } /** * @see ImageResizeMode.js */ export interface ImageResizeModeStatic { /** * contain - The image will be resized such that it will be completely * visible, contained within the frame of the View. */ contain: string /** * cover - The image will be resized such that the entire area of the view * is covered by the image, potentially clipping parts of the image. */ cover: string /** * stretch - The image will be stretched to fill the entire frame of the * view without clipping. This may change the aspect ratio of the image, * distoring it. Only supported on iOS. */ stretch: string } /** * Image style * @see https://facebook.github.io/react-native/docs/image.html#style */ export interface ImageStyle extends FlexStyle, TransformsStyle { resizeMode?: string //Object.keys(ImageResizeMode) backgroundColor?: string borderColor?: string borderWidth?: number borderRadius?: number overflow?: string // enum('visible', 'hidden') tintColor?: string opacity?: number } export interface ImagePropertiesIOS { /** * The text that's read by the screen reader when the user interacts with the image. */ accessibilityLabel?: string; /** * When true, indicates the image is an accessibility element. */ accessible?: boolean; /** * When the image is resized, the corners of the size specified by capInsets will stay a fixed size, * but the center content and borders of the image will be stretched. * This is useful for creating resizable rounded buttons, shadows, and other resizable assets. * More info on Apple documentation */ capInsets?: Insets /** * A static image to display while downloading the final image off the network. */ defaultSource?: {uri: string} /** * Invoked on load error with {nativeEvent: {error}} */ onError?: ( error: {nativeEvent: any} ) => void /** * Invoked when load completes successfully */ onLoad?: () => void /** * Invoked when load either succeeds or fails */ onLoadEnd?: () => void /** * Invoked on load start */ onLoadStart?: () => void /** * Invoked on download progress with {nativeEvent: {loaded, total}} */ onProgress?: ()=> void } /** * @see https://facebook.github.io/react-native/docs/image.html */ export interface ImageProperties extends ImagePropertiesIOS, React.Props { /** * onLayout function * * Invoked on mount and layout changes with * * {nativeEvent: { layout: {x, y, width, height}}}. */ onLayout?: ( event: LayoutChangeEvent ) => void; /** * Determines how to resize the image when the frame doesn't match the raw image dimensions. * * enum('cover', 'contain', 'stretch') */ resizeMode?: string; /** * uri is a string representing the resource identifier for the image, * which could be an http address, a local file path, * or the name of a static image resource (which should be wrapped in the require('image!name') function). */ source: {uri: string} | string; /** * * Style */ style?: ImageStyle; /** * A unique identifier for this element to be used in UI Automation testing scripts. */ testID?: string; } export interface ImageStatic extends React.ComponentClass { uri: string; resizeMode: ImageResizeModeStatic } /** * @see https://facebook.github.io/react-native/docs/listview.html#props */ export interface ListViewProperties extends ScrollViewProperties, React.Props { dataSource?: ListViewDataSource /** * How many rows to render on initial component mount. Use this to make * it so that the first screen worth of data apears at one time instead of * over the course of multiple frames. */ initialListSize?: number /** * (visibleRows, changedRows) => void * * Called when the set of visible rows changes. `visibleRows` maps * { sectionID: { rowID: true }} for all the visible rows, and * `changedRows` maps { sectionID: { rowID: true | false }} for the rows * that have changed their visibility, with true indicating visible, and * false indicating the view has moved out of view. */ onChangeVisibleRows?: ( visibleRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}>, changedRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}> ) => void /** * Called when all rows have been rendered and the list has been scrolled * to within onEndReachedThreshold of the bottom. The native scroll * event is provided. */ onEndReached?: () => void /** * Threshold in pixels for onEndReached. */ onEndReachedThreshold?: number /** * Number of rows to render per event loop. */ pageSize?: number /** * An experimental performance optimization for improving scroll perf of * large lists, used in conjunction with overflow: 'hidden' on the row * containers. Use at your own risk. */ removeClippedSubviews?: boolean /** * () => renderable * * The header and footer are always rendered (if these props are provided) * on every render pass. If they are expensive to re-render, wrap them * in StaticContainer or other mechanism as appropriate. Footer is always * at the bottom of the list, and header at the top, on every render pass. */ renderFooter?: () => React.ReactElement /** * () => renderable * * The header and footer are always rendered (if these props are provided) * on every render pass. If they are expensive to re-render, wrap them * in StaticContainer or other mechanism as appropriate. Footer is always * at the bottom of the list, and header at the top, on every render pass. */ renderHeader?: () => React.ReactElement /** * (rowData, sectionID, rowID) => renderable * Takes a data entry from the data source and its ids and should return * a renderable component to be rendered as the row. By default the data * is exactly what was put into the data source, but it's also possible to * provide custom extractors. */ renderRow?: ( rowData: any, sectionID: string | number, rowID: string | number, highlightRow?: boolean ) => React.ReactElement /** * A function that returns the scrollable component in which the list rows are rendered. * Defaults to returning a ScrollView with the given props. */ renderScrollComponent?: ( props: ScrollViewProperties ) => React.ReactElement /** * (sectionData, sectionID) => renderable * * If provided, a sticky header is rendered for this section. The sticky * behavior means that it will scroll with the content at the top of the * section until it reaches the top of the screen, at which point it will * stick to the top until it is pushed off the screen by the next section * header. */ renderSectionHeader?: ( sectionData: any, sectionId: string | number ) => React.ReactElement /** * (sectionID, rowID, adjacentRowHighlighted) => renderable * If provided, a renderable component to be rendered as the separator below each row * but not the last row if there is a section header below. * Take a sectionID and rowID of the row above and whether its adjacent row is highlighted. */ renderSeparator?: ( sectionID: string | number, rowID: string | number, adjacentRowHighlighted?: boolean ) => React.ReactElement /** * How early to start rendering rows before they come on screen, in * pixels. */ scrollRenderAheadDistance?: number } export interface ListViewStatic extends React.ComponentClass { DataSource: ListViewDataSource; } export interface MapViewAnnotation { latitude?: number longitude?: number animateDrop?: boolean title?: string subtitle?: string hasLeftCallout?: boolean hasRightCallout?: boolean onLeftCalloutPress?: () => void onRightCalloutPress?: () => void id?: string } export interface MapViewRegion { latitude: number longitude: number latitudeDelta: number longitudeDelta: number } export interface MapViewPropertiesIOS { /** * If false points of interest won't be displayed on the map. * Default value is true. */ showsPointsOfInterest?: boolean } export interface MapViewProperties extends MapViewPropertiesIOS, Touchable, React.Props { /** * Map annotations with title/subtitle. */ annotations?: MapViewAnnotation[] /** * Insets for the map's legal label, originally at bottom left of the map. See EdgeInsetsPropType.js for more information. */ legalLabelInsets?: Insets /** * The map type to be displayed. * standard: standard road map (default) * satellite: satellite view * hybrid: satellite view with roads and points of interest overlayed * * enum('standard', 'satellite', 'hybrid') */ mapType?: string /** * Maximum size of area that can be displayed. */ maxDelta?: number /** * Minimum size of area that can be displayed. */ minDelta?: number /** * Callback that is called once, when the user taps an annotation. */ onAnnotationPress?: () => void /** * Callback that is called continuously when the user is dragging the map. */ onRegionChange?: ( region: MapViewRegion ) => void /** * Callback that is called once, when the user is done moving the map. */ onRegionChangeComplete?: ( region: MapViewRegion ) => void /** * When this property is set to true and a valid camera is associated with the map, * the camera’s pitch angle is used to tilt the plane of the map. * * When this property is set to false, the camera’s pitch angle is ignored and * the map is always displayed as if the user is looking straight down onto it. */ pitchEnabled?: boolean /** * The region to be displayed by the map. * The region is defined by the center coordinates and the span of coordinates to display. */ region?: MapViewRegion /** * When this property is set to true and a valid camera is associated with the map, * the camera’s heading angle is used to rotate the plane of the map around its center point. * * When this property is set to false, the camera’s heading angle is ignored and the map is always oriented * so that true north is situated at the top of the map view */ rotateEnabled?: boolean /** * If false the user won't be able to change the map region being displayed. * Default value is true. */ scrollEnabled?: boolean /** * If true the app will ask for the user's location and focus on it. * Default value is false. * * NOTE: You need to add NSLocationWhenInUseUsageDescription key in Info.plist to enable geolocation, * otherwise it is going to fail silently! */ showsUserLocation?: boolean /** * Used to style and layout the MapView. * See StyleSheet.js and ViewStylePropTypes.js for more info. */ style?: ViewStyle /** * If false the user won't be able to pinch/zoom the map. * Default value is true. */ zoomEnabled?: boolean } /** * @see https://facebook.github.io/react-native/docs/mapview.html#content */ export interface MapViewStatic extends React.ComponentClass { } export interface TouchableWithoutFeedbackAndroidProperties { /** * Indicates to accessibility services to treat UI component like a native one. * Works for Android only. * * @enum('none', 'button', 'radiobutton_checked', 'radiobutton_unchecked' ) */ accessibilityComponentType?: string } export interface TouchableWithoutFeedbackIOSProperties { /** * Provides additional traits to screen reader. * By default no traits are provided unless specified otherwise in element * * @enum('none', 'button', 'link', 'header', 'search', 'image', 'selected', 'plays', 'key', 'text','summary', 'disabled', 'frequentUpdates', 'startsMedia', 'adjustable', 'allowsDirectInteraction', 'pageTurn') */ accessibilityTraits?: string | string[]; } /** * @see https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html#props */ export interface TouchableWithoutFeedbackProperties extends TouchableWithoutFeedbackAndroidProperties, TouchableWithoutFeedbackIOSProperties { /** * Called when the touch is released, but not if cancelled (e.g. by a scroll that steals the responder lock). */ accessible?: boolean /** * Delay in ms, from onPressIn, before onLongPress is called. */ delayLongPress?: number; /** * Delay in ms, from the start of the touch, before onPressIn is called. */ delayPressIn?: number; /** * Delay in ms, from the release of the touch, before onPressOut is called. */ delayPressOut?: number; /** * Invoked on mount and layout changes with * {nativeEvent: {layout: {x, y, width, height}}} */ onLayout?: ( event: LayoutChangeEvent ) => void onLongPress?: () => void; /** * Called when the touch is released, * but not if cancelled (e.g. by a scroll that steals the responder lock). */ onPress?: () => void; onPressIn?: () => void; onPressOut?: () => void; /** * //FIXME: not in doc but available in exmaples */ style?: ViewStyle } export interface TouchableWithoutFeedbackProps extends TouchableWithoutFeedbackProperties, React.Props { } /** * Do not use unless you have a very good reason. * All the elements that respond to press should have a visual feedback when touched. * This is one of the primary reason a "web" app doesn't feel "native". * * @see https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html */ export interface TouchableWithoutFeedbackStatic extends React.ComponentClass { } /** * @see https://facebook.github.io/react-native/docs/touchablehighlight.html#props */ export interface TouchableHighlightProperties extends TouchableWithoutFeedbackProperties, React.Props { /** * Determines what the opacity of the wrapped view should be when touch is active. */ activeOpacity?: number /** * * Called immediately after the underlay is hidden */ onHideUnderlay?: () => void /** * Called immediately after the underlay is shown */ onShowUnderlay?: () => void /** * @see https://facebook.github.io/react-native/docs/view.html#style */ style?: ViewStyle /** * The color of the underlay that will show through when the touch is active. */ underlayColor?: string } /** * A wrapper for making views respond properly to touches. * On press down, the opacity of the wrapped view is decreased, * which allows the underlay color to show through, darkening or tinting the view. * The underlay comes from adding a view to the view hierarchy, * which can sometimes cause unwanted visual artifacts if not used correctly, * for example if the backgroundColor of the wrapped view isn't explicitly set to an opaque color. * * NOTE: TouchableHighlight supports only one child * If you wish to have several child components, wrap them in a View. * * @see https://facebook.github.io/react-native/docs/touchablehighlight.html */ export interface TouchableHighlightStatic extends React.ComponentClass { } /** * @see https://facebook.github.io/react-native/docs/touchableopacity.html#props */ export interface TouchableOpacityProperties extends TouchableWithoutFeedbackProperties, React.Props { /** * Determines what the opacity of the wrapped view should be when touch is active. * Defaults to 0.2 */ activeOpacity?: number } /** * A wrapper for making views respond properly to touches. * On press down, the opacity of the wrapped view is decreased, dimming it. * This is done without actually changing the view hierarchy, * and in general is easy to add to an app without weird side-effects. * * @see https://facebook.github.io/react-native/docs/touchableopacity.html */ export interface TouchableOpacityStatic extends React.ComponentClass { } /** * @see https://facebook.github.io/react-native/docs/touchableopacity.html#props */ export interface TouchableNativeFeedbackProperties extends TouchableWithoutFeedbackProperties, React.Props { /** * Determines the type of background drawable that's going to be used to display feedback. * It takes an object with type property and extra data depending on the type. * It's recommended to use one of the following static methods to generate that dictionary: * 1) TouchableNativeFeedback.SelectableBackground() - will create object that represents android theme's default background for selectable elements (?android:attr/selectableItemBackground) * 2) TouchableNativeFeedback.SelectableBackgroundBorderless() - will create object that represent android theme's default background for borderless selectable elements (?android:attr/selectableItemBackgroundBorderless). Available on android API level 21+ * 3) TouchableNativeFeedback.Ripple(color, borderless) - will create object that represents ripple drawable with specified color (as a string). If property borderless evaluates to true the ripple will render outside of the view bounds (see native actionbar buttons as an example of that behavior). This background type is available on Android API level 21+ */ background?: any } /** * A wrapper for making views respond properly to touches (Android only). * On Android this component uses native state drawable to display touch feedback. * At the moment it only supports having a single View instance as a child node, * as it's implemented by replacing that View with another instance of RCTView node with some additional properties set. * * Background drawable of native feedback touchable can be customized with background property. * * @see https://facebook.github.io/react-native/docs/touchablenativefeedback.html#content */ export interface TouchableNativeFeedbackStatic extends React.ComponentClass { SelectableBackground: () => TouchableNativeFeedbackStatic SelectableBackgroundBorderless: () => TouchableNativeFeedbackStatic Ripple: ( color: string, borderless?: boolean ) => TouchableNativeFeedbackStatic } export interface LeftToRightGesture { //TODO: } export interface AnimationInterpolator { //TODO: } // see /NavigatorSceneConfigs.js export interface SceneConfig { // A list of all gestures that are enabled on this scene gestures: { pop: LeftToRightGesture, }, // Rebound spring parameters when transitioning FROM this scene springFriction: number; springTension: number; // Velocity to start at when transitioning without gesture defaultTransitionVelocity: number; // Animation interpolators for horizontal transitioning: animationInterpolators: { into: AnimationInterpolator, out: AnimationInterpolator }; } // see /NavigatorSceneConfigs.js export interface SceneConfigs { FloatFromBottom: SceneConfig; FloatFromRight: SceneConfig; PushFromRight: SceneConfig; FloatFromLeft: SceneConfig; HorizontalSwipeJump: SceneConfig; } export interface Route { component?: ComponentClass id?: string title?: string passProps?: Object; //anything else [key: string]: any //Commonly found properties backButtonTitle?: string content?: string message?: string; index?: number onRightButtonPress?: () => void rightButtonTitle?: string sceneConfig?: SceneConfig wrapperStyle?: any } /** * @see https://facebook.github.io/react-native/docs/navigator.html#content */ export interface NavigatorProperties extends React.Props { /** * Optional function that allows configuration about scene animations and gestures. * Will be invoked with the route and should return a scene configuration object * @param route */ configureScene?: ( route: Route ) => SceneConfig /** * Specify a route to start on. * A route is an object that the navigator will use to identify each scene to render. * initialRoute must be a route in the initialRouteStack if both props are provided. * The initialRoute will default to the last item in the initialRouteStack. */ initialRoute?: Route /** * Provide a set of routes to initially mount. * Required if no initialRoute is provided. * Otherwise, it will default to an array containing only the initialRoute */ initialRouteStack?: Route[] /** * Optionally provide a navigation bar that persists across scene transitions */ navigationBar?: React.ReactElement /** * Optionally provide the navigator object from a parent Navigator */ navigator?: Navigator /** * @deprecated Use navigationContext.addListener('willfocus', callback) instead. */ onDidFocus?: Function /** * @deprecated Use navigationContext.addListener('willfocus', callback) instead. */ onWillFocus?: Function /** * Required function which renders the scene for a given route. * Will be invoked with the route and the navigator object * @param route * @param navigator */ renderScene?: ( route: Route, navigator: Navigator ) => React.ReactElement /** * Styles to apply to the container of each scene */ sceneStyle?: ViewStyle /** * //FIXME: not found in doc but found in examples */ debugOverlay?: boolean } /** * Use Navigator to transition between different scenes in your app. * To accomplish this, provide route objects to the navigator to identify each scene, * and also a renderScene function that the navigator can use to render the scene for a given route. * * To change the animation or gesture properties of the scene, provide a configureScene prop to get the config object for a given route. * See Navigator.SceneConfigs for default animations and more info on scene config options. * @see https://facebook.github.io/react-native/docs/navigator.html */ export interface NavigatorStatic extends React.ComponentClass { SceneConfigs: SceneConfigs; NavigationBar: NavigatorStatic.NavigationBarStatic; BreadcrumbNavigationBar: NavigatorStatic.BreadcrumbNavigationBarStatic getContext( self: any ): NavigatorStatic; /** * returns the current list of routes */ getCurrentRoutes(): Route[]; /** * Jump backward without unmounting the current scen */ jumpBack(): void; /** * Jump forward to the next scene in the route stack */ jumpForward(): void; /** * Transition to an existing scene without unmounting */ jumpTo( route: Route ): void; /** * Navigate forward to a new scene, squashing any scenes that you could jumpForward to */ push( route: Route ): void; /** * Transition back and unmount the current scene */ pop(): void; /** * Replace the current scene with a new route */ replace( route: Route ): void; /** * Replace a scene as specified by an index */ replaceAtIndex( route: Route, index: number ): void; /** * Replace the previous scene */ replacePrevious( route: Route ): void; /** * Reset every scene with an array of routes */ immediatelyResetRouteStack( routes: Route[] ): void; /** * Pop to a particular scene, as specified by its route. All scenes after it will be unmounted */ popToRoute( route: Route ): void; /** * Pop to the first scene in the stack, unmounting every other scene */ popToTop(): void; } namespace NavigatorStatic { export interface NavState { routeStack: Route[] idStack: number[] presentedIndex: number } export interface NavigationBarStyle { //TODO @see NavigationBarStyle.ios.js } export interface NavigationBarRouteMapper { Title: ( route: Route, nav: Navigator, index: number, navState: NavState ) => React.ReactElement; LeftButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; RightButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; } /** * @see NavigatorNavigationBar.js */ export interface NavigationBarProperties extends React.Props { navigator?: Navigator routeMapper?: NavigationBarRouteMapper navState?: NavState style?: ViewStyle } export interface NavigationBarStatic extends React.ComponentClass { Styles: NavigationBarStyle } export type NavigationBar = NavigationBarStatic export var NavigationBar: NavigationBarStatic export interface BreadcrumbNavigationBarStyle { //TODO &see NavigatorBreadcrumbNavigationBar.js } export interface BreadcrumbNavigationBarRouteMapper { rightContentForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement titleContentForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement iconForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement //in samples... separatorForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement } /** * @see NavigatorNavigationBar.js */ export interface BreadcrumbNavigationBarProperties extends React.Props { navigator?: Navigator routeMapper?: BreadcrumbNavigationBarRouteMapper navState?: NavState style?: ViewStyle } export interface BreadcrumbNavigationBarStatic extends React.ComponentClass { Styles: BreadcrumbNavigationBarStyle } export type BreadcrumbNavigationBar = BreadcrumbNavigationBarStatic var BreadcrumbNavigationBar: BreadcrumbNavigationBarStatic } export interface StyleSheetStatic extends React.ComponentClass { create( styles: T ): T; } /** * //FIXME: Could not find docs. Inferred from examples and jscode : ListViewDataSource.js */ export interface DataSourceAssetCallback { rowHasChanged?: ( r1: any, r2: any ) => boolean sectionHeaderHasChanged?: ( h1: any, h2: any ) => boolean getRowData?: ( dataBlob: any, sectionID: number | string, rowID: number | string ) => T getSectionHeaderData?: ( dataBlob: any, sectionID: number | string ) => T } /** * //FIXME: Could not find docs. Inferred from examples and js showapi_res_code: ListViewDataSource.js */ export interface ListViewDataSource { new( onAsset: DataSourceAssetCallback ): ListViewDataSource; /** * Clones this `ListViewDataSource` with the specified `dataBlob` and * `rowIdentities`. The `dataBlob` is just an aribitrary blob of data. At * construction an extractor to get the interesting informatoin was defined * (or the default was used). * * The `rowIdentities` is is a 2D array of identifiers for rows. * ie. [['a1', 'a2'], ['b1', 'b2', 'b3'], ...]. If not provided, it's * assumed that the keys of the section data are the row identities. * * Note: This function does NOT clone the data in this data source. It simply * passes the functions defined at construction to a new data source with * the data specified. If you wish to maintain the existing data you must * handle merging of old and new data separately and then pass that into * this function as the `dataBlob`. */ cloneWithRows( dataBlob: Array | {[key: string ]: any}, rowIdentities?: Array ): ListViewDataSource /** * This performs the same function as the `cloneWithRows` function but here * you also specify what your `sectionIdentities` are. If you don't care * about sections you should safely be able to use `cloneWithRows`. * * `sectionIdentities` is an array of identifiers for sections. * ie. ['s1', 's2', ...]. If not provided, it's assumed that the * keys of dataBlob are the section identities. * * Note: this returns a new object! */ cloneWithRowsAndSections( dataBlob: Array | {[key: string]: any}, sectionIdentities?: Array, rowIdentities?: Array> ): ListViewDataSource getRowCount(): number /** * Gets the data required to render the row. */ getRowData( sectionIndex: number, rowIndex: number ): any /** * Gets the rowID at index provided if the dataSource arrays were flattened, * or null of out of range indexes. */ getRowIDForFlatIndex( index: number ): string /** * Gets the sectionID at index provided if the dataSource arrays were flattened, * or null for out of range indexes. */ getSectionIDForFlatIndex( index: number ): string /** * Returns an array containing the number of rows in each section */ getSectionLengths(): Array /** * Returns if the section header is dirtied and needs to be rerendered */ sectionHeaderShouldUpdate( sectionIndex: number ): boolean /** * Gets the data required to render the section header */ getSectionHeaderData( sectionIndex: number ): any } /** * @see https://facebook.github.io/react-native/docs/tabbarios-item.html#props */ export interface TabBarItemProperties extends React.Props { /** * Little red bubble that sits at the top right of the icon. */ badge?: string | number /** * A custom icon for the tab. It is ignored when a system icon is defined. */ icon?: {uri: string} | string /** * Callback when this tab is being selected, * you should change the state of your component to set selected={true}. */ onPress?: () => void /** * It specifies whether the children are visible or not. If you see a blank content, you probably forgot to add a selected one. */ selected?: boolean /** * A custom icon when the tab is selected. * It is ignored when a system icon is defined. If left empty, the icon will be tinted in blue. */ selectedIcon?: {uri: string} | string; /** * React style object. */ style?: ViewStyle /** * Items comes with a few predefined system icons. * Note that if you are using them, the title and selectedIcon will be overridden with the system ones. * * enum('bookmarks', 'contacts', 'downloads', 'favorites', 'featured', 'history', 'more', 'most-recent', 'most-viewed', 'recents', 'search', 'top-rated') */ systemIcon: string /** * Text that appears under the icon. It is ignored when a system icon is defined. */ title?: string } export interface TabBarItemStatic extends React.ComponentClass { } /** * @see https://facebook.github.io/react-native/docs/tabbarios.html#props */ export interface TabBarIOSProperties extends React.Props { /** * Background color of the tab bar */ barTintColor?: string style?: ViewStyle /** * Color of the currently selected tab icon */ tintColor?: string /** * A Boolean value that indicates whether the tab bar is translucent */ translucent?: boolean } export interface TabBarIOSStatic extends React.ComponentClass { Item: TabBarItemStatic; } export interface PixelRatioStatic { get(): number; } export interface DeviceEventSubscriptionStatic { remove(): void; } export interface DeviceEventEmitterStatic { addListener( type: string, onReceived: ( data: T ) => void ): DeviceEventSubscription; } // Used by Dimensions below export interface ScaledSize { width: number; height: number; scale: number; } export interface InteractionManagerStatic { runAfterInteractions( fn: () => void ): void; } export interface ScrollViewStyle extends FlexStyle, TransformsStyle { backfaceVisibility?:string //enum('visible', 'hidden') backgroundColor?: string borderColor?: string borderTopColor?: string borderRightColor?: string borderBottomColor?: string borderLeftColor?: string borderRadius?: number borderTopLeftRadius?: number borderTopRightRadius?: number borderBottomLeftRadius?: number borderBottomRightRadius?: number borderStyle?: string //enum('solid', 'dotted', 'dashed') borderWidth?: number borderTopWidth?: number borderRightWidth?: number borderBottomWidth?: number borderLeftWidth?: number opacity?: number overflow?: string //enum('visible', 'hidden') shadowColor?: string shadowOffset?: {width: number; height: number} shadowOpacity?: number shadowRadius?: number } export interface ScrollViewIOSProperties { /** * When true the scroll view bounces horizontally when it reaches the end * even if the content is smaller than the scroll view itself. The default * value is true when `horizontal={true}` and false otherwise. */ alwaysBounceHorizontal?: boolean /** * When true the scroll view bounces vertically when it reaches the end * even if the content is smaller than the scroll view itself. The default * value is false when `horizontal={true}` and true otherwise. */ alwaysBounceVertical?: boolean /** * Controls whether iOS should automatically adjust the content inset for scroll views that are placed behind a navigation bar or tab bar/ toolbar. * The default value is true. */ automaticallyAdjustContentInsets?: boolean // true /** * When true the scroll view bounces when it reaches the end of the * content if the content is larger then the scroll view along the axis of * the scroll direction. When false it disables all bouncing even if * the `alwaysBounce*` props are true. The default value is true. */ bounces?: boolean /** * When true gestures can drive zoom past min/max and the zoom will animate * to the min/max value at gesture end otherwise the zoom will not exceed * the limits. */ bouncesZoom?: boolean /** * When false once tracking starts won't try to drag if the touch moves. * The default value is true. */ canCancelContentTouches?: boolean /** * When true the scroll view automatically centers the content when the * content is smaller than the scroll view bounds; when the content is * larger than the scroll view this property has no effect. The default * value is false. */ centerContent?: boolean /** * The amount by which the scroll view content is inset from the edges of the scroll view. * Defaults to {0, 0, 0, 0}. */ contentInset?: Insets // zeros /** * Used to manually set the starting scroll offset. * The default value is {x: 0, y: 0} */ contentOffset?: PointProperties // zeros /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. Reasonable choices include * - Normal: 0.998 (the default) * - Fast: 0.9 */ decelerationRate?: number /** * When true the ScrollView will try to lock to only vertical or horizontal * scrolling while dragging. The default value is false. */ directionalLockEnabled?: boolean /** * The maximum allowed zoom scale. The default value is 1.0. */ maximumZoomScale?: number /** * The minimum allowed zoom scale. The default value is 1.0. */ minimumZoomScale?: number /** * Called when a scrolling animation ends. */ onScrollAnimationEnd?: () => void /** * When true the scroll view stops on multiples of the scroll view's size * when scrolling. This can be used for horizontal pagination. The default * value is false. */ pagingEnabled?: boolean /** * When false, the content does not scroll. The default value is true */ scrollEnabled?: boolean // true /** * This controls how often the scroll event will be fired while scrolling (in events per seconds). * A higher number yields better accuracy for showapi_res_code that is tracking the scroll position, * but can lead to scroll performance problems due to the volume of information being send over the bridge. * The default value is zero, which means the scroll event will be sent only once each time the view is scrolled. */ scrollEventThrottle?: number // null /** * The amount by which the scroll view indicators are inset from the edges of the scroll view. * This should normally be set to the same value as the contentInset. * Defaults to {0, 0, 0, 0}. */ scrollIndicatorInsets?: Insets //zeroes /** * When true the scroll view scrolls to top when the status bar is tapped. * The default value is true. */ scrollsToTop?: boolean /** * When snapToInterval is set, snapToAlignment will define the relationship of the the snapping to the scroll view. * - start (the default) will align the snap at the left (horizontal) or top (vertical) * - center will align the snap in the center * - end will align the snap at the right (horizontal) or bottom (vertical) */ snapToAlignment?: string /** * When set, causes the scroll view to stop at multiples of the value of snapToInterval. * This can be used for paginating through children that have lengths smaller than the scroll view. * Used in combination with snapToAlignment. */ snapToInterval?: number /** * An array of child indices determining which children get docked to the * top of the screen when scrolling. For example passing * `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the * top of the scroll view. This property is not supported in conjunction * with `horizontal={true}`. */ stickyHeaderIndices?: number[] /** * The current scale of the scroll view content. The default value is 1.0. */ zoomScale?: number } export interface ScrollViewProperties extends ScrollViewIOSProperties, Touchable { /** * These styles will be applied to the scroll view content container which * wraps all of the child views. Example: * * return ( * * * ); * ... * var styles = StyleSheet.create({ * contentContainer: { * paddingVertical: 20 * } * }); */ contentContainerStyle?: ViewStyle /** * When true the scroll view's children are arranged horizontally in a row * instead of vertically in a column. The default value is false. */ horizontal?: boolean /** * Determines whether the keyboard gets dismissed in response to a drag. * - 'none' (the default) drags do not dismiss the keyboard. * - 'onDrag' the keyboard is dismissed when a drag begins. * - 'interactive' the keyboard is dismissed interactively with the drag * and moves in synchrony with the touch; dragging upwards cancels the * dismissal. */ keyboardDismissMode?: string /** * When false tapping outside of the focused text input when the keyboard * is up dismisses the keyboard. When true the scroll view will not catch * taps and the keyboard will not dismiss automatically. The default value * is false. */ keyboardShouldPersistTaps?: boolean /** * Fires at most once per frame during scrolling. * The frequency of the events can be contolled using the scrollEventThrottle prop. */ onScroll?: (event?: { nativeEvent: NativeScrollEvent }) => void /** * Experimental: When true offscreen child views (whose `overflow` value is * `hidden`) are removed from their native backing superview when offscreen. * This canimprove scrolling performance on long lists. The default value is * false. */ removeClippedSubviews?: boolean /** * When true, shows a horizontal scroll indicator. */ showsHorizontalScrollIndicator?: boolean /** * When true, shows a vertical scroll indicator. */ showsVerticalScrollIndicator?: boolean /** * Style */ style?: ScrollViewStyle } export interface ScrollViewProps extends ScrollViewProperties, React.Props { } interface ScrollViewStatic extends React.ComponentClass { } export interface NativeScrollRectangle { left: number; top: number; bottom: number; right: number; } export interface NativeScrollPoint { x: number; y: number; } export interface NativeScrollSize { height: number; width: number; } export interface NativeScrollEvent { contentInset: NativeScrollRectangle; contentOffset: NativeScrollPoint; contentSize: NativeScrollSize; layoutMeasurement: NativeScrollSize; zoomScale: number; } ////////////////////////////////////////////////////////////////////////// // // A P I s // ////////////////////////////////////////////////////////////////////////// /** * //FIXME: no documentation - inferred from RCTACtionSheetManager.m */ export interface ActionSheetIOSOptions { title?: string options?: string[] cancelButtonIndex?: number destructiveButtonIndex?: number } /** * //FIXME: no documentation - inferred from RCTACtionSheetManager.m */ export interface ShareActionSheetIOSOptions { message?: string url?: string } /** * @see https://facebook.github.io/react-native/docs/actionsheetios.html#content * //FIXME: no documentation - inferred from RCTACtionSheetManager.m */ export interface ActionSheetIOSStatic { showActionSheetWithOptions: ( options: ActionSheetIOSOptions, callback: ( buttonIndex: number ) => void ) => void showShareActionSheetWithOptions: ( options: ShareActionSheetIOSOptions, failureCallback: ( error: Error ) => void, successCallback: ( success: boolean, method: string ) => void ) => void } /** * //FIXME: No documentation - inferred from RCTAdSupport.m */ export interface AdSupportIOSStatic { getAdvertisingId: ( onSuccess: ( deviceId: string ) => void, onFailure: ( err: Error ) => void ) => void getAdvertisingTrackingEnabled: ( onSuccess: ( hasTracking: boolean ) => void, onFailure: ( err: Error ) => void ) => void } interface AlertIOSButton { text: string onPress?: () => void } /** * Launches an alert dialog with the specified title and message. * * Optionally provide a list of buttons. * Tapping any button will fire the respective onPress callback and dismiss the alert. * By default, the only button will be an 'OK' button * * The last button in the list will be considered the 'Primary' button and it will appear bold. * * @see https://facebook.github.io/react-native/docs/alertios.html#content */ export interface AlertIOSStatic { alert: ( title: string, message?: string, buttons?: Array, type?: string ) => void prompt: ( title: string, value?: string, buttons?: Array, callback?: ( value?: string ) => void ) => void } /** * AppStateIOS can tell you if the app is in the foreground or background, * and notify you when the state changes. * * AppStateIOS is frequently used to determine the intent and proper behavior * when handling push notifications. * * iOS App States * active - The app is running in the foreground * background - The app is running in the background. The user is either in another app or on the home screen * inactive - This is a transition state that currently never happens for typical React Native apps. * * For more information, see Apple's documentation: https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html * * @see https://facebook.github.io/react-native/docs/appstateios.html#content */ export interface AppStateIOSStatic { currentState: string addEventListener( type: string, listener: ( state: string ) => void ): void removeEventListener( type: string, listener: ( state: string ) => void ): void } /** * AsyncStorage is a simple, asynchronous, persistent, key-value storage system that is global to the app. * It should be used instead of LocalStorage. * * It is recommended that you use an abstraction on top of AsyncStorage * instead of AsyncStorage directly for anything more than light usage since it operates globally. * * @see https://facebook.github.io/react-native/docs/asyncstorage.html#content */ export interface AsyncStorageStatic { /** * Fetches key and passes the result to callback, along with an Error if there is any. */ getItem( key: string, callback?: ( error?: Error, result?: string ) => void ): Promise /** * Sets value for key and calls callback on completion, along with an Error if there is any */ setItem( key: string, value: string, callback?: ( error?: Error ) => void ): Promise removeItem( key: string, callback?: ( error?: Error ) => void ): Promise /** * Merges existing value with input value, assuming they are stringified json. Returns a Promise object. * Not supported by all native implementation */ mergeItem( key: string, value: string, callback?: ( error?: Error ) => void ): Promise /** * Erases all AsyncStorage for all clients, libraries, etc. You probably don't want to call this. * Use removeItem or multiRemove to clear only your own keys instead. */ clear( callback?: ( error?: Error ) => void ): Promise /** * Gets all keys known to the app, for all callers, libraries, etc */ getAllKeys( callback?: ( error?: Error, keys?: string[] ) => void ): Promise /** * multiGet invokes callback with an array of key-value pair arrays that matches the input format of multiSet */ multiGet( keys: string[], callback?: ( errors?: Error[], result?: string[][] ) => void ): Promise /** * multiSet and multiMerge take arrays of key-value array pairs that match the output of multiGet, * * multiSet([['k1', 'val1'], ['k2', 'val2']], cb); */ multiSet( keyValuePairs: string[][], callback?: ( errors?: Error[] ) => void ): Promise /** * Delete all the keys in the keys array. */ multiRemove( keys: string[], callback?: ( errors?: Error[] ) => void ): Promise /** * Merges existing values with input values, assuming they are stringified json. * Returns a Promise object. * * Not supported by all native implementations. */ multiMerge( keyValuePairs: string[][], callback?: ( errors?: Error[] ) => void ): Promise } export interface CameraRollFetchParams { first: number; after?: string; groupTypes: string; // 'Album','All','Event','Faces','Library','PhotoStream','SavedPhotos' groupName?: string assetType?: string } export interface CameraRollNodeInfo { image: Image; group_name: string; timestamp: number; location: any; } export interface CameraRollEdgeInfo { node: CameraRollNodeInfo; } export interface CameraRollAssetInfo { edges: CameraRollEdgeInfo[]; page_info: { has_next_page: boolean; end_cursor: string; }; } /** * CameraRoll provides access to the local camera roll / gallery. */ export interface CameraRollStatic { GroupTypesOptions: string[] //'Album','All','Event','Faces','Library','PhotoStream','SavedPhotos' /** * Saves the image to the camera roll / gallery. * * The CameraRoll API is not yet implemented for Android. * * @tag On Android, this is a local URI, such as "file:///sdcard/img.png". * On iOS, the tag can be one of the following: * local URI * assets-library tag * a tag not maching any of the above, which means the image data will be stored in memory (and consume memory as long as the process is alive) * * @param successCallback Invoked with the value of tag on success. * @param errorCallback Invoked with error message on error. */ saveImageWithTag( tag: string, successCallback: ( tag?: string ) => void, errorCallback: ( error: Error ) => void ): void /** * Invokes callback with photo identifier objects from the local camera roll of the device matching shape defined by getPhotosReturnChecker. * * @param {object} params See getPhotosParamChecker. * @param {function} callback Invoked with arg of shape defined by getPhotosReturnChecker on success. * @param {function} errorCallback Invoked with error message on error. */ getPhotos( fetch: CameraRollFetchParams, callback: ( assetInfo: CameraRollAssetInfo ) => void, errorCallback: ( error: Error )=> void ): void; } export interface FetchableListenable { fetch: () => Promise /** * eventName is expected to be `change` * //FIXME: No doc - inferred from NetInfo.js */ addEventListener: ( eventName: string, listener: ( result: T ) => void ) => void /** * eventName is expected to be `change` * //FIXME: No doc - inferred from NetInfo.js */ removeEventListener: ( eventName: string, listener: ( result: T ) => void ) => void } /** * NetInfo exposes info about online/offline status * * Asynchronously determine if the device is online and on a cellular network. * * - `none` - device is offline * - `wifi` - device is online and connected via wifi, or is the iOS simulator * - `cell` - device is connected via Edge, 3G, WiMax, or LTE * - `unknown` - error case and the network status is unknown * @see https://facebook.github.io/react-native/docs/netinfo.html#content */ export interface NetInfoStatic extends FetchableListenable { /** * * Available on all platforms. * Asynchronously fetch a boolean to determine internet connectivity. */ isConnected: FetchableListenable //FIXME: Documentation missing isConnectionMetered: any } export interface PanResponderGestureState { /** * ID of the gestureState- persisted as long as there at least one touch on */ stateID: number /** * the latest screen coordinates of the recently-moved touch */ moveX: number /** * the latest screen coordinates of the recently-moved touch */ moveY: number /** * the screen coordinates of the responder grant */ x0: number /** * the screen coordinates of the responder grant */ y0: number /** * accumulated distance of the gesture since the touch started */ dx: number /** * accumulated distance of the gesture since the touch started */ dy: number /** * current velocity of the gesture */ vx: number /** * current velocity of the gesture */ vy: number /** * Number of touches currently on screeen */ numberActiveTouches: number // All `gestureState` accounts for timeStamps up until: _accountsForMovesUpTo: number } /** * @see documentation of GestureResponderHandlers */ export interface PanResponderCallbacks { onMoveShouldSetPanResponder?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => boolean onStartShouldSetPanResponder?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => void onPanResponderGrant?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => void onPanResponderMove?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => void onPanResponderRelease?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => void onPanResponderTerminate?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => void onMoveShouldSetPanResponderCapture?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => boolean onStartShouldSetPanResponderCapture?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => boolean onPanResponderReject?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => void onPanResponderStart?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => void onPanResponderEnd?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => void onPanResponderTerminationRequest?: ( e: GestureResponderEvent, gestureState: PanResponderGestureState ) => boolean } export interface PanResponderInstance { panHandlers: GestureResponderHandlers } /** * PanResponder reconciles several touches into a single gesture. * It makes single-touch gestures resilient to extra touches, * and can be used to recognize simple multi-touch gestures. * * It provides a predictable wrapper of the responder handlers provided by the gesture responder system. * For each handler, it provides a new gestureState object alongside the normal event. */ export interface PanResponderStatic { /** * @param config Enhanced versions of all of the responder callbacks * that provide not only the typical `ResponderSyntheticEvent`, but also the * `PanResponder` gesture state. Simply replace the word `Responder` with * `PanResponder` in each of the typical `onResponder*` callbacks. For * example, the `config` object would look like: * * - `onMoveShouldSetPanResponder: (e, gestureState) => {...}` * - `onMoveShouldSetPanResponderCapture: (e, gestureState) => {...}` * - `onStartShouldSetPanResponder: (e, gestureState) => {...}` * - `onStartShouldSetPanResponderCapture: (e, gestureState) => {...}` * - `onPanResponderReject: (e, gestureState) => {...}` * - `onPanResponderGrant: (e, gestureState) => {...}` * - `onPanResponderStart: (e, gestureState) => {...}` * - `onPanResponderEnd: (e, gestureState) => {...}` * - `onPanResponderRelease: (e, gestureState) => {...}` * - `onPanResponderMove: (e, gestureState) => {...}` * - `onPanResponderTerminate: (e, gestureState) => {...}` * - `onPanResponderTerminationRequest: (e, gestureState) => {...}` * * In general, for events that have capture equivalents, we update the * gestureState once in the capture phase and can use it in the bubble phase * as well. * * Be careful with onStartShould* callbacks. They only reflect updated * `gestureState` for start/end events that bubble/capture to the Node. * Once the node is the responder, you can rely on every start/end event * being processed by the gesture and `gestureState` being updated * accordingly. (numberActiveTouches) may not be totally accurate unless you * are the responder. */ create( config: PanResponderCallbacks ): PanResponderInstance } export interface PushNotificationPermissions { alert?: boolean badge?: boolean sound?: boolean } export interface PushNotification { /** * An alias for `getAlert` to get the notification's main message string */ getMessage(): string | Object /** * Gets the sound string from the `aps` object */ getSound(): string /** * Gets the notification's main message from the `aps` object */ getAlert(): string | Object /** * Gets the badge count number from the `aps` object */ getBadgeCount(): number /** * Gets the data object on the notif */ getData(): Object } /** * Handle push notifications for your app, including permission handling and icon badge number. * @see https://facebook.github.io/react-native/docs/pushnotificationios.html#content * * //FIXME: BGR: The documentation seems completely off compared to the actual js implementation. I could never get the example to run */ export interface PushNotificationIOSStatic { /** * Sets the badge number for the app icon on the home screen */ setApplicationIconBadgeNumber( number: number ): void /** * Gets the current badge number for the app icon on the home screen */ getApplicationIconBadgeNumber( callback: ( badge: number ) => void ): void /** * Attaches a listener to remote notifications while the app is running in the * foreground or the background. * * The handler will get be invoked with an instance of `PushNotificationIOS` * * The type MUST be 'notification' */ addEventListener( type: string, handler: ( notification: PushNotification ) => void ):void /** * Requests all notification permissions from iOS, prompting the user's * dialog box. */ requestPermissions(): void /** * See what push permissions are currently enabled. `callback` will be * invoked with a `permissions` object: * * - `alert` :boolean * - `badge` :boolean * - `sound` :boolean */ checkPermissions( callback: ( permissions: PushNotificationPermissions ) => void ): void /** * Removes the event listener. Do this in `componentWillUnmount` to prevent * memory leaks */ removeEventListener( type: string, handler: ( notification: PushNotification ) => void ): void /** * An initial notification will be available if the app was cold-launched * from a notification. * * The first caller of `popInitialNotification` will get the initial * notification object, or `null`. Subsequent invocations will return null. */ popInitialNotification(): PushNotification } /** * @enum('default', 'light-content') */ export type StatusBarStyle = string /** * @enum('none','fade', 'slide') */ type StatusBarAnimation = string /** * //FIXME: No documentation is available (although this is self explanatory) * * @see https://facebook.github.io/react-native/docs/statusbarios.html#content */ export interface StatusBarIOSStatic { setStyle(style: StatusBarStyle, animated?: boolean): void setHidden(hidden: boolean, animation?: StatusBarAnimation): void setNetworkActivityIndicatorVisible(visible: boolean): void } /** * The Vibration API is exposed at VibrationIOS.vibrate(). * On iOS, calling this function will trigger a one second vibration. * The vibration is asynchronous so this method will return immediately. * * There will be no effect on devices that do not support Vibration, eg. the iOS simulator. * * Vibration patterns are currently unsupported. * * @see https://facebook.github.io/react-native/docs/vibrationios.html#content */ export interface VibrationIOSStatic { vibrate(): void } ////////////////////////////////////////////////////////////////////////// // // R E - E X P O R T S // ////////////////////////////////////////////////////////////////////////// // export var AppRegistry: AppRegistryStatic; export var ActivityIndicatorIOS: ActivityIndicatorIOSStatic export type ActivityIndicatorIOS = ActivityIndicatorIOSStatic export var DatePickerIOS: DatePickerIOSStatic export type DatePickerIOS = DatePickerIOSStatic export var Image: ImageStatic export type Image = ImageStatic export var LayoutAnimation: LayoutAnimationStatic export type LayoutAnimation = LayoutAnimationStatic export var ListView: ListViewStatic export type ListView = ListViewStatic export var MapView: MapViewStatic export type MapView = MapViewStatic export var Navigator: NavigatorStatic export type Navigator = NavigatorStatic export var NavigatorIOS: NavigatorIOSStatic export type NavigatorIOS = NavigatorIOSStatic export var PickerIOS: PickerIOSStatic export type PickerIOS = PickerIOSStatic export var SliderIOS: SliderIOSStatic export type SliderIOS = SliderIOSStatic export var ScrollView: ScrollViewStatic export type ScrollView = ScrollViewStatic export var StyleSheet: StyleSheetStatic export type StyleSheet = StyleSheetStatic export var SwitchIOS: SwitchIOSStatic export type SwitchIOS = SwitchIOSStatic export var TabBarIOS: TabBarIOSStatic export type TabBarIOS = TabBarIOSStatic export var Text: TextStatic export type Text = TextStatic export var TextInput: TextInputStatic export type TextInput = TextInputStatic export var TouchableHighlight: TouchableHighlightStatic export type TouchableHighlight = TouchableHighlightStatic export var TouchableNativeFeedback: TouchableNativeFeedbackStatic export type TouchableNativeFeedback = TouchableNativeFeedbackStatic export var TouchableOpacity: TouchableOpacityStatic export type TouchableOpacity = TouchableOpacityStatic export var TouchableWithoutFeedback: TouchableWithoutFeedbackStatic export type TouchableWithoutFeedback= TouchableWithoutFeedbackStatic export var View: ViewStatic export type View = ViewStatic export var WebView: WebViewStatic export type WebView = WebViewStatic //////////// APIS ////////////// export var ActionSheetIOS: ActionSheetIOSStatic export type ActionSheetIOS = ActionSheetIOSStatic export var AdSupportIOS: AdSupportIOSStatic export type AdSupportIOS = AdSupportIOSStatic export var AlertIOS: AlertIOSStatic export type AlertIOS = AlertIOSStatic export var AppStateIOS: AppStateIOSStatic export type AppStateIOS = AppStateIOSStatic export var AsyncStorage: AsyncStorageStatic export type AsyncStorage = AsyncStorageStatic export var CameraRoll: CameraRollStatic export type CameraRoll = CameraRollStatic export var NetInfo: NetInfoStatic export type NetInfo = NetInfoStatic export var PanResponder: PanResponderStatic export type PanResponder = PanResponderStatic export var PushNotificationIOS: PushNotificationIOSStatic export type PushNotificationIOS = PushNotificationIOSStatic export var StatusBarIOS: StatusBarIOSStatic export type StatusBarIOS = StatusBarIOSStatic export var VibrationIOS: VibrationIOSStatic export type VibrationIOS = VibrationIOSStatic // // /TODO: BGR: These are leftovers of the initial port that must be revisited // export var SegmentedControlIOS: React.ComponentClass export var PixelRatio: PixelRatioStatic export var DeviceEventEmitter: DeviceEventEmitterStatic export var DeviceEventSubscription: DeviceEventSubscriptionStatic export type DeviceEventSubscription = DeviceEventSubscriptionStatic export var InteractionManager: InteractionManagerStatic ////////////////////////////////////////////////////////////////////////// // // Additional ( and controversial) // ////////////////////////////////////////////////////////////////////////// export function __spread( target: any, ...sources: any[] ): any; export interface GlobalStatic { /** * Accepts a function as its only argument and calls that function before the next repaint. * It is an essential building block for animations that underlies all of the JavaScript-based animation APIs. * In general, you shouldn't need to call this yourself - the animation API's will manage frame updates for you. * @see https://facebook.github.io/react-native/docs/animations.html#requestanimationframe */ requestAnimationFrame( fn: () => void ) : void; } // // Add-Ons // namespace addons { //FIXME: Documentation ? export interface TestModuleStatic { verifySnapshot: ( done: ( indicator?: any ) => void ) => void markTestPassed: ( indicator: any ) => void markTestCompleted: () => void } export var TestModule: TestModuleStatic export type TestModule = TestModuleStatic } } declare module "react-native" { import ReactNative = __React export = ReactNative } declare var global: __React.GlobalStatic declare function require( name: string ): any //TODO: BGR: this is a left-over from the initial port. Not sure it makes any sense declare module "Dimensions" { import * as React from 'react-native'; interface Dimensions { get( what: string ): React.ScaledSize; } var ExportDimensions: Dimensions; export = ExportDimensions; } ================================================ FILE: README.md ================================================ # Hot this is a hot project 这是一个用MVP+Rxjava+Retrofit构建项目,是个微信头条的分享。 ## Screenshot ![image](https://github.com/zj-wukewei/Hot/blob/master/screenshot/1.png)![image](https://github.com/zj-wukewei/Hot/blob/master/screenshot/2.png) ## Update >* 6月25日 加入了缓存功能。 >* 7月11日 加入Datamanager来统一管理数据来源 >* 7月20日 加入Dagger2 >* 9月12日 完成了用react-native实现的体育新闻列表 >* 9月13日 加入materialsearchview库完成搜索功能,关于界面的入口改变 ## Welcome >* Star >* Fork >* PR >* Issue ================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt' apply plugin: 'me.tatarka.retrolambda' android { compileSdkVersion rootProject.ext.android.compileSdkVersion buildToolsVersion rootProject.ext.android.buildToolsVersion defaultConfig { applicationId rootProject.ext.android.applicationId minSdkVersion rootProject.ext.android.minSdkVersion targetSdkVersion rootProject.ext.android.targetSdkVersion versionCode rootProject.ext.android.versionCode versionName rootProject.ext.android.versionName ndk { abiFilters "armeabi-v7a", "x86" } } compileOptions { sourceCompatibility rootProject.ext.android.javaVersion sourceCompatibility rootProject.ext.android.javaVersion } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' compile rootProject.ext.dependencies["appcompat-v7"] compile rootProject.ext.dependencies["cardview"] compile rootProject.ext.dependencies["design"] compile rootProject.ext.dependencies["recyclerview-v7"] compile rootProject.ext.dependencies["retrofit"] compile rootProject.ext.dependencies["logging-interceptor"] compile rootProject.ext.dependencies["rxandroid"] compile rootProject.ext.dependencies["converter-gson"] compile rootProject.ext.dependencies["adapter-rxjava"] compile rootProject.ext.dependencies["gson"] compile rootProject.ext.dependencies["react-native-preloader"] compile rootProject.ext.dependencies["butterknife"] compile rootProject.ext.dependencies["dagger"] compile rootProject.ext.dependencies["react-native"] compile rootProject.ext.dependencies["materialsearchview"] apt rootProject.ext.dependencies["dagger-compiler"] provided rootProject.ext.dependencies["glassfish"] compile project(':common_lib') } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/wukewei/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 # http://developer.android.com/guide/developing/tools/proguard.html # 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 *; #} ================================================ FILE: app/src/androidTest/java/com/wkw/hot/ApplicationTest.java ================================================ package com.wkw.hot; import android.app.Application; import android.test.ApplicationTestCase; /** * Testing Fundamentals */ public class ApplicationTest extends ApplicationTestCase { public ApplicationTest() { super(Application.class); } } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/com/wkw/hot/adapter/FragmentAdapter.java ================================================ package com.wkw.hot.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.ArrayList; import java.util.List; /** * Created by wukewei on 16/5/26. */ public class FragmentAdapter extends FragmentPagerAdapter { private List mFragments; private List mTitles; public FragmentAdapter(FragmentManager fm) { super(fm); mFragments = new ArrayList<>(); mTitles = new ArrayList<>(); } public void addFragment(Fragment fragment, String title) { mFragments.add(fragment); mTitles.add(title); } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return mTitles.get(position); } } ================================================ FILE: app/src/main/java/com/wkw/hot/base/BaseActivity.java ================================================ package com.wkw.hot.base; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.wkw.common_lib.utils.AppManager; import com.wkw.hot.navigator.Navigator; import com.wkw.hot.reject.component.AppComponent; import com.wkw.hot.reject.module.ActivityModule; import com.wkw.hot.ui.App; import javax.inject.Inject; import butterknife.ButterKnife; /** * Created by wukewei on 16/5/26. */ public abstract class BaseActivity extends AppCompatActivity implements IView { @Inject protected T mPresenter; protected Activity mContext; @Inject protected Navigator navigator; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayout()); ButterKnife.bind(this); mContext = this; setupActivityComponent(App.getAppComponent(),new ActivityModule(this)); if (mPresenter != null) mPresenter.attachView(this); initEventAndData(); AppManager.getAppManager().addActivity(this); } protected void setCommonBackToolBack(Toolbar toolbar, String title) { toolbar.setTitle(title); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); toolbar.setNavigationOnClickListener(v -> onBackPressed()); } @Override protected void onDestroy() { super.onDestroy(); AppManager.getAppManager().removeActivity(this); ButterKnife.unbind(this); if (mPresenter != null) mPresenter.detachView(); } /** * 依赖注入的入口 * @param appComponent appComponent */ protected abstract void setupActivityComponent(AppComponent appComponent, ActivityModule activityModule); protected abstract int getLayout(); protected abstract void initEventAndData(); } ================================================ FILE: app/src/main/java/com/wkw/hot/base/BaseFragment.java ================================================ package com.wkw.hot.base; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.wkw.hot.reject.component.AppComponent; import com.wkw.hot.reject.module.ActivityModule; import com.wkw.hot.reject.module.FragmentModule; import com.wkw.hot.ui.App; import javax.inject.Inject; import butterknife.ButterKnife; /** * Created by wukewei on 16/5/30. */ public abstract class BaseFragment extends Fragment implements IView{ @Inject protected T mPresenter; protected View mView; protected Activity mContext; @Override public void onAttach(Activity activity) { if (activity instanceof BaseActivity) { mContext = activity; } super.onAttach(activity); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mView = inflater.inflate(getLayoutId(), null); setupActivityComponent(App.getAppComponent(),new FragmentModule(this)); return mView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mPresenter.attachView(this); ButterKnife.bind(this, view); initEventAndData(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onDestroy() { super.onDestroy(); if (mPresenter != null) mPresenter.detachView(); } /** * 依赖注入的入口 * @param appComponent appComponent */ protected abstract void setupActivityComponent(AppComponent appComponent, FragmentModule fragmentModule); protected abstract int getLayoutId(); protected abstract void initEventAndData(); } ================================================ FILE: app/src/main/java/com/wkw/hot/base/BaseLazyFragment.java ================================================ package com.wkw.hot.base; import android.os.Bundle; import android.support.v4.app.Fragment; import java.lang.reflect.Field; /** * Created by wukewei on 16/7/26. */ public abstract class BaseLazyFragment extends BaseFragment{ private boolean isFirstResume = true; private boolean isFirstVisible = true; private boolean isFirstInvisible = true; private boolean isPrepared; @Override public void onDetach() { super.onDetach(); // for bug ---> java.lang.IllegalStateException: Activity has been destroyed try { Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager"); childFragmentManager.setAccessible(true); childFragmentManager.set(this, null); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initPrepare(); } @Override public void onResume() { super.onResume(); if (isFirstResume) { isFirstResume = false; return; } if (getUserVisibleHint()) { onUserVisible(); } } @Override public void onPause() { super.onPause(); if (getUserVisibleHint()) { onUserInvisible(); } } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { if (isFirstVisible) { isFirstVisible = false; initPrepare(); } else { onUserVisible(); } } else { if (isFirstInvisible) { isFirstInvisible = false; onFirstUserInvisible(); } else { onUserInvisible(); } } } private synchronized void initPrepare() { if (isPrepared) { onFirstUserVisible(); } else { isPrepared = true; } } /** * when fragment is visible for the first time, here we can do some initialized work or refresh data only once */ protected abstract void onFirstUserVisible(); /** * this method like the fragment's lifecycle method onResume() */ protected abstract void onUserVisible(); /** * when fragment is invisible for the first time */ private void onFirstUserInvisible() { // here we do not recommend do something } /** * this method like the fragment's lifecycle method onPause() */ protected abstract void onUserInvisible(); } ================================================ FILE: app/src/main/java/com/wkw/hot/base/BaseLoadMoreAdapter.java ================================================ package com.wkw.hot.base; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.wkw.hot.R; import com.wkw.hot.common.Constants; import java.util.ArrayList; import java.util.List; /** * Created by wukewei on 16/6/1. */ public abstract class BaseLoadMoreAdapter extends RecyclerView.Adapter { public static final int TYPE_FOOTER = Integer.MAX_VALUE; public static final int ITEM_TYPE = 0; private final List mList = new ArrayList<>(); private boolean hasMore = true, isLoading = true; public static class FooterViewHolder extends RecyclerView.ViewHolder { public final ProgressBar progressBar; public final TextView textView; public FooterViewHolder(View itemView) { super(itemView); progressBar = (ProgressBar) itemView.findViewById(R.id.progress_view); textView = (TextView) itemView.findViewById(R.id.tv_content); } } public void setLoading(boolean loading) { isLoading = loading; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof FooterViewHolder) { if (hasMore) { ((FooterViewHolder)holder).progressBar.setVisibility(View.VISIBLE); ((FooterViewHolder)holder).textView.setText("正在加载..."); } else { ((FooterViewHolder)holder).progressBar.setVisibility(View.GONE); ((FooterViewHolder)holder).textView.setText("已全部加载"); } } else { onBindItemViewHolder((VH)holder, mList.get(position), position); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_FOOTER) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_loading_footer_view, parent, false); return new FooterViewHolder(view); } else { return onCreateItemViewHolder(parent, viewType); } } public abstract void onBindItemViewHolder(VH holder, T data, int position); public abstract VH onCreateItemViewHolder(ViewGroup parent, int viewType); @Override public int getItemViewType(int position) { if (position == mList.size()) { return TYPE_FOOTER; } else { return ITEM_TYPE; } } @Override public int getItemCount() { return mList.size() + 1; } public void addLoadMoreData(List data) { if (data == null) return; this.mList.addAll(data); this.hasMore = data.size() == Constants.PAGE_SIZE; this.isLoading = false; notifyDataSetChanged(); } public void addRefreshData(List data) { if (data == null) return; this.mList.clear(); this.mList.addAll(data); this.hasMore = data.size() == Constants.PAGE_SIZE; this.isLoading = false; notifyDataSetChanged(); } public boolean canLoadMore() { return hasMore && !isLoading; } } ================================================ FILE: app/src/main/java/com/wkw/hot/base/BaseOnScrollListener.java ================================================ package com.wkw.hot.base; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; /** * Created by wukewei on 16/6/1. */ public abstract class BaseOnScrollListener extends RecyclerView.OnScrollListener { protected int lastVisibleItem; @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); lastVisibleItem = ((LinearLayoutManager)recyclerView.getLayoutManager()).findLastVisibleItemPosition(); } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == recyclerView.getAdapter().getItemCount()) { onLoadMore(); } } public abstract void onLoadMore(); } ================================================ FILE: app/src/main/java/com/wkw/hot/base/BasePresenter.java ================================================ package com.wkw.hot.base; import android.app.Activity; import com.wkw.common_lib.utils.ToashUtils; import com.wkw.hot.data.DataManager; import com.wkw.common_lib.rx.error.ErrorHanding; import rx.Subscription; import rx.subscriptions.CompositeSubscription; /** * Created by wukewei on 16/5/26. */ public abstract class BasePresenter implements IPresenter { protected T mView; protected CompositeSubscription mCompositeSubscription; @Override public void attachView(T view) { this.mView = view; } protected void unSubscribe() { if (mCompositeSubscription != null) { mCompositeSubscription.unsubscribe(); } } protected void addSubscribe(Subscription subscription) { if (mCompositeSubscription == null) { mCompositeSubscription = new CompositeSubscription(); } mCompositeSubscription.add(subscription); } @Override public void detachView() { this.mView = null; unSubscribe(); } } ================================================ FILE: app/src/main/java/com/wkw/hot/base/ILoadingView.java ================================================ package com.wkw.hot.base; import android.content.Context; /** * Created by wukewei on 16/6/1. */ public interface ILoadingView extends IView { void showLoading(); void showContent(); void showNotData(); void showError(String msg); Context context(); } ================================================ FILE: app/src/main/java/com/wkw/hot/base/IPresenter.java ================================================ package com.wkw.hot.base; /** * Created by wukewei on 16/5/26. */ public interface IPresenter { void attachView(T view); void detachView(); } ================================================ FILE: app/src/main/java/com/wkw/hot/base/IView.java ================================================ package com.wkw.hot.base; /** * Created by wukewei on 16/5/26. */ public interface IView { } ================================================ FILE: app/src/main/java/com/wkw/hot/base/page/BaseLazyPageFragment.java ================================================ package com.wkw.hot.base.page; import android.os.Bundle; import android.support.v4.app.Fragment; import com.wkw.hot.base.BaseFragment; import com.wkw.hot.base.IPresenter; import java.lang.reflect.Field; /** * Created by wukewei on 16/7/26. */ public abstract class BaseLazyPageFragment extends BasePageFragment{ private boolean isFirstResume = true; private boolean isFirstVisible = true; private boolean isFirstInvisible = true; private boolean isPrepared; @Override public void onDetach() { super.onDetach(); // for bug ---> java.lang.IllegalStateException: Activity has been destroyed try { Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager"); childFragmentManager.setAccessible(true); childFragmentManager.set(this, null); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initPrepare(); } @Override public void onResume() { super.onResume(); if (isFirstResume) { isFirstResume = false; return; } if (getUserVisibleHint()) { onUserVisible(); } } @Override public void onPause() { super.onPause(); if (getUserVisibleHint()) { onUserInvisible(); } } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { if (isFirstVisible) { isFirstVisible = false; initPrepare(); } else { onUserVisible(); } } else { if (isFirstInvisible) { isFirstInvisible = false; onFirstUserInvisible(); } else { onUserInvisible(); } } } private synchronized void initPrepare() { if (isPrepared) { onFirstUserVisible(); } else { isPrepared = true; } } /** * when fragment is visible for the first time, here we can do some initialized work or refresh data only once */ protected abstract void onFirstUserVisible(); /** * this method like the fragment's lifecycle method onResume() */ protected abstract void onUserVisible(); /** * when fragment is invisible for the first time */ private void onFirstUserInvisible() { // here we do not recommend do something } /** * this method like the fragment's lifecycle method onPause() */ protected abstract void onUserInvisible(); } ================================================ FILE: app/src/main/java/com/wkw/hot/base/page/BaseListAdapter.java ================================================ package com.wkw.hot.base.page; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; /** * Created by wukewei on 16/12/6. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public abstract class BaseListAdapter extends RecyclerView.Adapter { protected List mData = new ArrayList(); @Override public int getItemCount() { return mData.size(); } public void addLoadMoreData(List data) { if (data == null) return; this.mData.addAll(data); notifyDataSetChanged(); } public void addRefreshData(List data) { if (data == null) return; this.mData.clear(); this.mData.addAll(data); notifyDataSetChanged(); } } ================================================ FILE: app/src/main/java/com/wkw/hot/base/page/BasePageFragment.java ================================================ package com.wkw.hot.base.page; import android.content.Context; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import butterknife.Bind; import com.wkw.common_lib.widget.ProgressLayout; import com.wkw.common_lib.widget.loadmore.OnLoadMoreListener; import com.wkw.common_lib.widget.loadmore.RecyclerViewWithFooter; import com.wkw.hot.R; import com.wkw.hot.base.BaseFragment; import com.wkw.hot.base.ILoadingView; import com.wkw.hot.base.IPresenter; import com.wkw.hot.common.Constants; import java.util.List; /** * Created by wukewei on 16/12/6. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public abstract class BasePageFragment extends BaseFragment implements IDataVIew { @Bind(R.id.recycler_view) RecyclerViewWithFooter mRecyclerViewWithFooter; @Bind(R.id.swipe_refresh_layout) SwipeRefreshLayout mSwipeRefreshLayout; @Bind(R.id.progress_layout) ProgressLayout mProgressLayout; public int mCurrentPage = 1; public boolean mIsFetching = false; public boolean isInit = true; @Override protected void initEventAndData() { mSwipeRefreshLayout.setOnRefreshListener(mOnRefreshListener); mRecyclerViewWithFooter.setOnLoadMoreListener(mLoadMoreListener); mRecyclerViewWithFooter.setAdapter(getAdapter()); mRecyclerViewWithFooter.setLayoutManager(getLayoutManager()); } @Override protected int getLayoutId() { return R.layout.fragment_list; } public OnLoadMoreListener mLoadMoreListener = () -> { mCurrentPage++; fetchData(mCurrentPage); }; public SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = () -> { if (!mIsFetching && mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) { mCurrentPage = 1; mRecyclerViewWithFooter.setPullToLoad(); } }; @Override public void showContent() { if (mProgressLayout != null) { mProgressLayout.showContent(); } } @Override public void showLoading() { mIsFetching = true; if (mCurrentPage == 1 && isInit) { if (mProgressLayout != null) { mProgressLayout.showLoading(); } } isInit = false; } @Override public void showError(String msg) { mIsFetching = false; setOnRefresh(); if (mCurrentPage == 1 && mProgressLayout != null) { mProgressLayout.showError(msg, v -> fetchData(mCurrentPage)); } } public void setOnRefresh() { if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.postDelayed(() -> mSwipeRefreshLayout.setRefreshing(false), 800); } } @Override public void showNotData() { if (mProgressLayout != null) { mProgressLayout.showNotData(v -> fetchData(mCurrentPage)); } if (mCurrentPage == 1) { setOnRefresh(); } mIsFetching = false; } public void setData(List data) { if (data == null) { showNotData(); return; } if (mCurrentPage == 1) { getAdapter().addRefreshData(data); } else { getAdapter().addLoadMoreData(data); } if (data.size() < Constants.PAGE_SIZE) { mRecyclerViewWithFooter.setEnd(); } else { mRecyclerViewWithFooter.setPullToLoad(); } RecyclerView.Adapter adapter = mRecyclerViewWithFooter.getAdapter(); if (mCurrentPage == 1 && mRecyclerViewWithFooter != null && adapter != null && (adapter.getItemCount() == 0 || (adapter.getItemCount() == 1 && (adapter.getItemViewType(0) == RecyclerViewWithFooter. LoadMoreAdapter.LOAD_MORE_VIEW_TYPE || adapter.getItemViewType(0) == RecyclerViewWithFooter. LoadMoreAdapter.EMPTY_VIEW_TYPE)))) { isInit = true; showNotData(); return; } if (mProgressLayout != null) { mProgressLayout.showContent(); } if (mCurrentPage == 1) { setOnRefresh(); } mCurrentPage++; mIsFetching = false; } @Override public Context context() { return getActivity(); } protected abstract void fetchData(int currentPageIndex); protected abstract BaseListAdapter getAdapter(); protected abstract RecyclerView.LayoutManager getLayoutManager(); } ================================================ FILE: app/src/main/java/com/wkw/hot/base/page/IDataVIew.java ================================================ package com.wkw.hot.base.page; import android.content.Context; import com.wkw.hot.base.IView; /** * Created by wukewei on 16/12/6. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public interface IDataVIew extends IView{ void showLoading(); void showContent(); void showNotData(); void showError(String msg); Context context(); } ================================================ FILE: app/src/main/java/com/wkw/hot/cache/CacheLoader.java ================================================ package com.wkw.hot.cache; import android.app.Application; import android.content.Context; import android.util.Log; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; /** * Created by wukewei on 16/6/19. */ public class CacheLoader { private static Application application; public static Application getApplication() { return application; } private ICache mMemoryCache, mDiskCache; private CacheLoader() { mMemoryCache = new MemoryCache(); mDiskCache = new DiskCache(); } private static CacheLoader loader; public static CacheLoader getInstance(Context context) { application = (Application) context.getApplicationContext(); if (loader == null) { synchronized (CacheLoader.class) { if (loader == null) { loader = new CacheLoader(); } } } return loader; } public Observable asDataObservable(String key, Class cls, NetworkCache networkCache) { Observable observable = Observable.concat( memory(key, cls), disk(key, cls), network(key, cls, networkCache)) .first(new Func1() { @Override public Boolean call(T t) { return t != null; } }); return observable; } private Observable memory(String key, Class cls) { return mMemoryCache.get(key, cls).doOnNext(new Action1() { @Override public void call(T t) { if (null != t) { Log.d("我是来自内存","我是来自内存"); } } }); } private Observable disk(final String key, Class cls) { return mDiskCache.get(key, cls) .doOnNext(new Action1() { @Override public void call(T t) { if (null != t) { Log.d("我是来自磁盘","我是来自磁盘"); mMemoryCache.put(key, t); } } }); } public void upNewData(final String key, T t) { Observable.just(t) .doOnNext(new Action1() { @Override public void call(T t) { if (null != t) { Log.d("更新数据","更新数据"); mDiskCache.put(key, t); mMemoryCache.put(key, t); } } }).subscribe(); } private Observable network(final String key, Class cls , NetworkCache networkCache) { return networkCache.get(key, cls) .doOnNext(new Action1() { @Override public void call(T t) { if (null != t) { Log.d("我是来自网络","我是来自网络"); mDiskCache.put(key, t); mMemoryCache.put(key, t); } } }); } public void clearMemory(String key) { ((MemoryCache)mMemoryCache).clearMemory(key); } public void clearMemoryDisk(String key) { ((MemoryCache)mMemoryCache).clearMemory(key); ((DiskCache)mDiskCache).clearDisk(key); } } ================================================ FILE: app/src/main/java/com/wkw/hot/cache/DiskCache.java ================================================ package com.wkw.hot.cache; import android.util.Log; import com.wkw.hot.ui.App; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by wukewei on 16/6/19. */ public class DiskCache implements ICache{ private static final String NAME = ".db"; public static long OTHER_CACHE_TIME = 10 * 60 * 1000; public static long WIFI_CACHE_TIME = 30 * 60 * 1000; File fileDir; public DiskCache() { fileDir = CacheLoader.getApplication().getCacheDir(); } @Override public Observable get(final String key, final Class cls) { return Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { T t = (T) getDiskData(key + NAME); if (subscriber.isUnsubscribed()) { return; } if (t == null) { subscriber.onNext(null); } else { subscriber.onNext(t); } subscriber.onCompleted(); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } @Override public void put(final String key, final T t) { Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { boolean isSuccess = isSave(key + NAME, t); if (!subscriber.isUnsubscribed() && isSuccess) { subscriber.onNext(t); subscriber.onCompleted(); } } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); } /** * 保存数据 */ private boolean isSave(String fileName, T t) { File file = new File(fileDir, fileName); ObjectOutputStream objectOut = null; boolean isSuccess = false; try { FileOutputStream out = new FileOutputStream(file); objectOut = new ObjectOutputStream(out); objectOut.writeObject(t); objectOut.flush(); isSuccess=true; } catch (IOException e) { Log.e("写入缓存错误",e.getMessage()); } catch (Exception e) { Log.e("写入缓存错误",e.getMessage()); } finally { closeSilently(objectOut); } return isSuccess; } /** * 获取保存的数据 */ private Object getDiskData(String fileName) { File file = new File(fileDir, fileName); if (!file.exists()) { return null; } if (isCacheDataFailure(file)) { return null; } Object o = null; ObjectInputStream read = null; try { read = new ObjectInputStream(new FileInputStream(file)); o = read.readObject(); } catch (StreamCorruptedException e) { Log.e("读取错误", e.getMessage()); } catch (IOException e) { Log.e("读取错误", e.getMessage()); } catch (ClassNotFoundException e) { Log.e("错误", e.getMessage()); } finally { closeSilently(read); } return o; } private void closeSilently(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (Exception ignored) { } } } /** * 判断缓存是否已经失效 */ private boolean isCacheDataFailure(File dataFile) { if (!dataFile.exists()) { return true; } long existTime = System.currentTimeMillis() - dataFile.lastModified(); boolean failure = false; if (!App.ExtImpl.g().isAvailable()) { return failure; } if (App.ExtImpl.g().isWifi()) { failure = existTime > WIFI_CACHE_TIME ? true : false; } else { failure = existTime > OTHER_CACHE_TIME ? true : false; } return failure; } public void clearDisk(String key) { File file = new File(fileDir, key + NAME); if (file.exists()) file.delete(); } } ================================================ FILE: app/src/main/java/com/wkw/hot/cache/ICache.java ================================================ package com.wkw.hot.cache; import rx.Observable; /** * Created by wukewei on 16/6/19. */ public interface ICache { Observable get(String key, Class cls); void put(String key, T t); } ================================================ FILE: app/src/main/java/com/wkw/hot/cache/MemoryCache.java ================================================ package com.wkw.hot.cache; import android.text.TextUtils; import android.util.LruCache; import com.google.gson.Gson; import java.io.UnsupportedEncodingException; import rx.Observable; import rx.Subscriber; /** * Created by wukewei on 16/6/19. */ public class MemoryCache implements ICache{ private LruCache mCache; public MemoryCache() { final int maxMemory = (int) Runtime.getRuntime().maxMemory(); final int cacheSize = maxMemory / 8; mCache = new LruCache(cacheSize) { @Override protected int sizeOf(String key, String value) { try { return value.getBytes("UTF-8").length; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return value.getBytes().length; } } }; } @Override public Observable get(final String key, final Class cls) { return Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { String result = mCache.get(key); if (subscriber.isUnsubscribed()) { return; } if (TextUtils.isEmpty(result)) { subscriber.onNext(null); } else { T t = new Gson().fromJson(result, cls); subscriber.onNext(t); } subscriber.onCompleted(); } }); } @Override public void put(String key, T t) { if (null != t) { mCache.put(key, new Gson().toJson(t)); } } public void clearMemory(String key) { mCache.remove(key); } } ================================================ FILE: app/src/main/java/com/wkw/hot/cache/NetworkCache.java ================================================ package com.wkw.hot.cache; import rx.Observable; /** * Created by wukewei on 16/6/19. */ public abstract class NetworkCache { public abstract Observable get(String key, final Class cls); } ================================================ FILE: app/src/main/java/com/wkw/hot/common/Constants.java ================================================ package com.wkw.hot.common; /** * Created by wukewei on 16/5/26. */ public class Constants { public static final String Base_Url = "http://route.showapi.com/"; public static final String Api_Key = "c12cf1979a384b119ebe7583f5dea18c"; public static final String Showapi_appid = "37613"; public static final String NEW_LIST = "new_list"; public static final int HTTP_CONNECT_TIMEOUT = 16000; public static final int PAGE_SIZE = 20; } ================================================ FILE: app/src/main/java/com/wkw/hot/data/DataManager.java ================================================ package com.wkw.hot.data; import com.wkw.hot.cache.CacheLoader; import com.wkw.hot.cache.NetworkCache; import com.wkw.hot.common.Constants; import com.wkw.hot.data.api.HotApi; import com.wkw.hot.entity.ListPopularEntity; import com.wkw.hot.entity.PagePopularEntity; import com.wkw.hot.entity.PopularEntity; import com.wkw.common_lib.rx.RxResultHelper; import com.wkw.common_lib.rx.SchedulersCompat; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.Subscriber; import rx.functions.Func1; /** * Created by wukewei on 16/7/12. * 这个类是管理app的数据来源无论从网络获取.内存.还是磁盘 */ public class DataManager { private HotApi mHotApi; private CacheLoader cacheLoader; @Inject public DataManager(HotApi hotApi, CacheLoader cacheLoader) { this.mHotApi = hotApi; this.cacheLoader = cacheLoader; } /*** * 获取分类的类型 * @param * @param * @return */ public List getTabs() { List tabs = new ArrayList<>(); tabs.add("科技"); tabs.add("美女"); tabs.add("生活"); tabs.add("娱乐"); tabs.add("搞笑"); tabs.add("宅男"); return tabs; } /*** * 获取列表 * @param pn 页码 * @param type 类别名称 * @return */ public Observable> getPopular(int pn, String type) { return mHotApi.getPopular(pn, type, Constants.Showapi_appid, Constants.Api_Key) .compose(SchedulersCompat.applyIoSchedulers()) .compose(RxResultHelper.handleResult()) .doOnNext(populars -> { if (pn == 1) { ListPopularEntity popular = new ListPopularEntity(populars.getPagebean().getContentlist()); cacheLoader.upNewData(type, popular); } }) .flatMap(new Func1>>() { @Override public Observable> call(PagePopularEntity pagePopularEntity) { return Observable.just(pagePopularEntity.getPagebean().getContentlist()); } }); } /*** * 获取缓存信息 默认只缓存第一页 * @param type 类别名称 * @param * @return */ public Observable> getCachePopular(String type) { NetworkCache networkCache = new NetworkCache() { @Override public Observable get(String key, Class cls) { return getPopular(1, type) .flatMap(populars -> { ListPopularEntity popular = new ListPopularEntity(populars); return Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { if (subscriber.isUnsubscribed()) return; subscriber.onNext(popular); subscriber.onCompleted(); } }); }); } }; return cacheLoader.asDataObservable(Constants.NEW_LIST + type, ListPopularEntity.class, networkCache) .map(listPopular -> listPopular.data); } } ================================================ FILE: app/src/main/java/com/wkw/hot/data/api/HotApi.java ================================================ package com.wkw.hot.data.api; import com.wkw.common_lib.rx.ApiResponse; import com.wkw.hot.entity.PagePopularEntity; import retrofit2.http.GET; import retrofit2.http.Query; import rx.Observable; /** * Created by wukewei on 16/5/26. */ public interface HotApi { @GET("582-2") Observable> getPopular(@Query("page") int page, @Query("key") String word, @Query("showapi_appid") String showapi_appid, @Query("showapi_sign") String showapi_sign); } ================================================ FILE: app/src/main/java/com/wkw/hot/entity/ListPopularEntity.java ================================================ package com.wkw.hot.entity; import java.io.Serializable; import java.util.List; /** * Created by wukewei on 16/6/25. */ public class ListPopularEntity implements Serializable { public List data; public ListPopularEntity(List data) { this.data = data; } } ================================================ FILE: app/src/main/java/com/wkw/hot/entity/PagePopularEntity.java ================================================ package com.wkw.hot.entity; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by wukewei on 17/5/8. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class PagePopularEntity { @SerializedName("ret_code") private int retCode; @SerializedName("pagebean") private Pagebean pagebean; public int getRetCode() { return retCode; } public void setRetCode(int retCode) { this.retCode = retCode; } public Pagebean getPagebean() { return pagebean; } public void setPagebean(Pagebean pagebean) { this.pagebean = pagebean; } public static class Pagebean { @SerializedName("allPages") private int allPages; @SerializedName("contentlist") private List contentlist; @SerializedName("currentPage") private int currentPage; @SerializedName("allNum") private int allNum; @SerializedName("maxResult") private int maxResult; public int getMaxResult() { return maxResult; } public void setMaxResult(int maxResult) { this.maxResult = maxResult; } public int getAllPages() { return allPages; } public void setAllPages(int allPages) { this.allPages = allPages; } public List getContentlist() { return contentlist; } public void setContentlist(List contentlist) { this.contentlist = contentlist; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getAllNum() { return allNum; } public void setAllNum(int allNum) { this.allNum = allNum; } } } ================================================ FILE: app/src/main/java/com/wkw/hot/entity/PopularEntity.java ================================================ package com.wkw.hot.entity; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by wukewei on 16/5/26. */ public class PopularEntity implements Serializable{ @Override public String toString() { return "Popular{" + "ctime='" + ctime + '\'' + ", title='" + title + '\'' + ", description='" + description + '\'' + ", picUrl='" + picUrl + '\'' + ", url='" + url + '\'' + '}'; } /** * ctime : 2016-05-25 * title : 李仁港怎么注入ROCK范儿?井宝如何撒野?《盗墓笔记》的方方面面请看这里! * description : 南都全娱乐 * picUrl : http://zxpic.gtimg.com/infonew/0/wechat_pics_-5707820.jpg/640 * url : http://mp.weixin.qq.com/s?__biz=MjM5MTE1ODI2MA==&idx=2&mid=2651787931&sn=009a0d9df1accebef2adba14cc61ac9d */ @SerializedName("date") private String ctime; @SerializedName("title") private String title; @SerializedName("userName") private String description; @SerializedName("contentImg") private String picUrl; @SerializedName("url") private String url; public String getCtime() { return ctime; } public void setCtime(String ctime) { this.ctime = ctime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } ================================================ FILE: app/src/main/java/com/wkw/hot/mapper/PopularModelDataMapper.java ================================================ package com.wkw.hot.mapper; import com.wkw.hot.entity.PopularEntity; import com.wkw.hot.model.PopularModel; import com.wkw.hot.reject.PerActivity; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; /** * Created by wukewei on 16/12/2. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class PopularModelDataMapper { @Inject public PopularModelDataMapper() { } public PopularModel transform(PopularEntity popularEntity) { if (popularEntity == null) { throw new IllegalArgumentException("Cannot transform a null value"); } PopularModel popularModel = new PopularModel(); popularModel.setCtime(popularEntity.getCtime()); popularModel.setDescription(popularEntity.getDescription()); popularModel.setPicUrl(popularEntity.getPicUrl()); popularModel.setTitle(popularEntity.getTitle()); popularModel.setUrl(popularEntity.getUrl()); return popularModel; } public List transform(List popularList) { List popularModelsList = new ArrayList<>(); if (popularList != null && !popularList.isEmpty()) { for (PopularEntity popularEntity : popularList) { popularModelsList.add(transform(popularEntity)); } } return popularModelsList; } } ================================================ FILE: app/src/main/java/com/wkw/hot/model/PopularModel.java ================================================ package com.wkw.hot.model; /** * Created by wukewei on 16/12/2. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class PopularModel { private String ctime; private String title; private String description; private String picUrl; private String url; @Override public String toString() { return "PopularModel{" + "ctime='" + ctime + '\'' + ", title='" + title + '\'' + ", description='" + description + '\'' + ", picUrl='" + picUrl + '\'' + ", url='" + url + '\'' + '}'; } public String getCtime() { return ctime; } public void setCtime(String ctime) { this.ctime = ctime; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } ================================================ FILE: app/src/main/java/com/wkw/hot/navigator/Navigator.java ================================================ package com.wkw.hot.navigator; import android.content.Context; import android.content.Intent; import com.wkw.hot.ui.AboutActivity; import com.wkw.hot.ui.react.MyReactActivity; import javax.inject.Inject; /** * Created by wukewei on 16/9/14. */ public class Navigator { @Inject public Navigator() { } public void navigateToAbout(Context context) { if (context != null) { Intent intent = new Intent(context, AboutActivity.class); context.startActivity(intent); } } public void navigateToMyReact(Context context) { if (context != null) { Intent intent = new Intent(context, MyReactActivity.class); context.startActivity(intent); } } } ================================================ FILE: app/src/main/java/com/wkw/hot/reject/ContextLife.java ================================================ package com.wkw.hot.reject; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import javax.inject.Qualifier; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Created by wukewei on 16/7/19. */ @Qualifier @Documented @Retention(RUNTIME) public @interface ContextLife { String value() default "Application"; } ================================================ FILE: app/src/main/java/com/wkw/hot/reject/PerActivity.java ================================================ package com.wkw.hot.reject; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; import javax.inject.Scope; /** * Created by wukewei on 16/7/19. */ @Scope @Retention(RUNTIME) public @interface PerActivity { } ================================================ FILE: app/src/main/java/com/wkw/hot/reject/PerFragment.java ================================================ package com.wkw.hot.reject; import java.lang.annotation.Retention; import javax.inject.Scope; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Created by wukewei on 16/7/19. */ @Scope @Retention(RUNTIME) public @interface PerFragment { } ================================================ FILE: app/src/main/java/com/wkw/hot/reject/component/ActivityComponent.java ================================================ package com.wkw.hot.reject.component; import android.app.Activity; import com.wkw.hot.data.DataManager; import com.wkw.hot.reject.PerActivity; import com.wkw.hot.reject.module.ActivityModule; import com.wkw.hot.ui.main.MainActivity; import com.wkw.hot.ui.search.SearchActivity; import com.wkw.hot.ui.web.WebActivity; import dagger.Component; /** * Created by wukewei on 16/7/19. */ @PerActivity @Component(dependencies = AppComponent.class, modules = ActivityModule.class) public interface ActivityComponent { DataManager getDataManager(); Activity getActivity(); void inject(MainActivity mainActivity); void inject(WebActivity webActivity); } ================================================ FILE: app/src/main/java/com/wkw/hot/reject/component/AppComponent.java ================================================ package com.wkw.hot.reject.component; import com.wkw.hot.data.DataManager; import com.wkw.hot.reject.ContextLife; import com.wkw.hot.reject.module.AppModule; import com.wkw.hot.ui.App; import javax.inject.Singleton; import dagger.Component; /** * Created by wukewei on 16/7/19. */ @Singleton @Component(modules = AppModule.class) public interface AppComponent { @ContextLife("Application") App getContext(); DataManager getDataManager(); } ================================================ FILE: app/src/main/java/com/wkw/hot/reject/component/FragmentComponent.java ================================================ package com.wkw.hot.reject.component; import android.app.Activity; import com.wkw.hot.data.DataManager; import com.wkw.hot.reject.PerFragment; import com.wkw.hot.reject.module.FragmentModule; import com.wkw.hot.ui.item.ItemFragment; import dagger.Component; /** * Created by wukewei on 16/7/19. */ @PerFragment @Component(dependencies = AppComponent.class, modules = FragmentModule.class) public interface FragmentComponent { DataManager getDataManager(); Activity getActivity(); void inject(ItemFragment itemFragment); } ================================================ FILE: app/src/main/java/com/wkw/hot/reject/module/ActivityModule.java ================================================ package com.wkw.hot.reject.module; import android.app.Activity; import com.wkw.hot.reject.PerActivity; import dagger.Module; import dagger.Provides; /** * Created by wukewei on 16/7/19. */ @Module public class ActivityModule { private Activity mActivity; public ActivityModule(Activity activity) { this.mActivity = activity; } @Provides @PerActivity public Activity provideActivity() { return mActivity; } } ================================================ FILE: app/src/main/java/com/wkw/hot/reject/module/AppModule.java ================================================ package com.wkw.hot.reject.module; import com.wkw.hot.cache.CacheLoader; import com.wkw.hot.common.Constants; import com.wkw.hot.data.DataManager; import com.wkw.hot.data.api.HotApi; import com.wkw.hot.navigator.Navigator; import com.wkw.hot.reject.ContextLife; import com.wkw.hot.ui.App; import java.io.File; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by wukewei on 16/7/19. */ @Module public class AppModule { private App application; public AppModule(App application) { this.application = application; } @Provides @Singleton @ContextLife("Application") public App provideApp() { return application; } @Provides @Singleton OkHttpClient provideOkHttpClient() { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); Interceptor apikey = chain -> chain.proceed(chain.request().newBuilder() .addHeader("apikey", Constants.Api_Key).build()); OkHttpClient okHttpClient = new OkHttpClient.Builder() .readTimeout(Constants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS) .connectTimeout(Constants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS) .addInterceptor(apikey) .addInterceptor(loggingInterceptor) .build(); return okHttpClient; } @Provides @Singleton HotApi provideHotApi(OkHttpClient okHttpClient) { Retrofit retrofit1 = new Retrofit.Builder() .baseUrl(Constants.Base_Url) .client(okHttpClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); HotApi hotApi = retrofit1.create(HotApi.class); return hotApi; } @Provides @Singleton Navigator provideNavigator(Navigator navigator) { return navigator; } @Provides @Singleton CacheLoader provideCacheLoader() { return CacheLoader.getInstance(application); } @Provides @Singleton DataManager provideDataManager(HotApi hotApi, CacheLoader cacheLoader) { return new DataManager(hotApi, cacheLoader); } } ================================================ FILE: app/src/main/java/com/wkw/hot/reject/module/FragmentModule.java ================================================ package com.wkw.hot.reject.module; import android.app.Activity; import android.support.v4.app.Fragment; import com.wkw.hot.reject.PerActivity; import com.wkw.hot.reject.PerFragment; import dagger.Module; import dagger.Provides; /** * Created by wukewei on 16/7/19. */ @Module public class FragmentModule { private Fragment fragment; public FragmentModule(Fragment fragment) { this.fragment = fragment; } @Provides @PerFragment public Activity provideActivity() { return fragment.getActivity(); } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/AboutActivity.java ================================================ package com.wkw.hot.ui; import android.content.Context; import android.content.Intent; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.wkw.hot.BuildConfig; import com.wkw.hot.R; import com.wkw.hot.base.BaseActivity; import com.wkw.hot.reject.component.AppComponent; import com.wkw.hot.reject.module.ActivityModule; import butterknife.Bind; /** * Created by wukewei on 16/7/25. */ public class AboutActivity extends BaseActivity { @Bind(R.id.tv_version) TextView mVersionTv; @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.about_collapsing_tool) CollapsingToolbarLayout mCollapsingToolbarLayout; public static void startActivity(Context context) { Intent intent = new Intent(context, AboutActivity.class); context.startActivity(intent); } @Override protected void setupActivityComponent(AppComponent appComponent, ActivityModule activityModule) { } @Override protected int getLayout() { return R.layout.activity_about; } @Override protected void initEventAndData() { mCollapsingToolbarLayout.setTitle(getString(R.string.app_name)); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mToolbar.setNavigationOnClickListener(v -> AboutActivity.this.onBackPressed()); mVersionTv.setText("Version " + BuildConfig.VERSION_NAME); } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/App.java ================================================ package com.wkw.hot.ui; import android.app.Application; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.wkw.common_lib.Ext; import com.wkw.common_lib.image.ImageLoader; import com.wkw.common_lib.image.glide.GlideImageLoaderStrategy; import com.wkw.common_lib.network.Network; import com.wkw.common_lib.utils.ProcessUtils; import com.wkw.common_lib.utils.ViewUtils; import com.wkw.hot.BuildConfig; import com.wkw.hot.reject.component.AppComponent; import com.wkw.hot.reject.component.DaggerAppComponent; import com.wkw.hot.reject.module.AppModule; import java.util.Arrays; import java.util.List; /** * Created by wukewei on 16/5/26. */ public class App extends Application implements ReactApplication{ private static App appContext; private static AppComponent mAppComponent; private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { return Arrays.asList( new MainReactPackage() ); } }; @Override public void onCreate() { super.onCreate(); appContext = this; if (!ProcessUtils.isMainProcess(this)) { return; } mAppComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); initImageLoader(); initExtension(); } private void initImageLoader() { ImageLoader.getInstance().setImageLoaderStragety(new GlideImageLoaderStrategy()); } private void initExtension() { Ext.init(this, new ExtImpl()); } @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } public static final class ExtImpl extends Ext { @Override public String getCurOpenId() { return null; } @Override public String getDeviceInfo() { return null; } @Override public String getPackageNameForResource() { return "com.wkw.hot"; } @Override public int getScreenHeight() { return ViewUtils.getScreenHeight(); } @Override public int getScreenWidth() { return ViewUtils.getScreenWidth(); } @Override public boolean isAvailable() { return Network.isAvailable(); } @Override public boolean isWap() { return Network.isWap(); } @Override public boolean isMobile() { return Network.isMobile(); } @Override public boolean is2G() { return Network.is2G(); } @Override public boolean is3G() { return Network.is3G(); } @Override public boolean isWifi() { return Network.isWifi(); } @Override public boolean isEthernet() { return Network.isEthernet(); } } public static AppComponent getAppComponent() { return mAppComponent; } public static App getAppContext() { return appContext; } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/item/ItemAdapter.java ================================================ package com.wkw.hot.ui.item; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.wkw.common_lib.image.ImageLoader; import com.wkw.common_lib.image.glide.GlideImageConfig; import com.wkw.hot.R; import com.wkw.hot.base.BaseLoadMoreAdapter; import com.wkw.hot.entity.PopularEntity; import com.wkw.hot.model.PopularModel; import com.wkw.hot.utils.GlideManager; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by wukewei on 16/6/1. */ public class ItemAdapter extends BaseLoadMoreAdapter { private OnItemClickListener listener; public void setOnItemClickListener(OnItemClickListener listener) { this.listener = listener; } @Override public void onBindItemViewHolder(ViewHolder holder, PopularModel data, int position) { ImageLoader.getInstance().displayImage(holder.imgItem.getContext(), GlideImageConfig.builder() .url(data.getPicUrl()) .imagerView(holder.imgItem) .build()); //GlideManager.loadListImageView(holder.imgItem.getContext(), data.getPicUrl(), holder.imgItem); holder.tvTitle.setText(data.getTitle()); holder.tvDate.setText("来自:"+data.getDescription()); holder.mPopular = data; } @Override public ViewHolder onCreateItemViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item, parent, false); return new ViewHolder(view); } public class ViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.img_item) ImageView imgItem; @Bind(R.id.tv_title) TextView tvTitle; @Bind(R.id.tv_date) TextView tvDate; @Bind(R.id.card_view) CardView cardView; PopularModel mPopular; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); cardView.setOnClickListener(v -> { if (listener != null) { listener.onItemClick(mPopular.getUrl(), mPopular.getTitle()); } }); } } public interface OnItemClickListener { void onItemClick(String url, String title); } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/item/ItemContract.java ================================================ package com.wkw.hot.ui.item; import com.wkw.hot.base.ILoadingView; import com.wkw.hot.base.IPresenter; import com.wkw.hot.entity.PopularEntity; import com.wkw.hot.model.PopularModel; import java.util.List; /** * Created by wukewei on 16/5/30. */ public class ItemContract { interface View extends ILoadingView { void addLoadMoreData(List data); void addRefreshData(List data); } interface Presenter extends IPresenter { void getListData(String type); void getCacheData(String type); } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/item/ItemFragment.java ================================================ package com.wkw.hot.ui.item; import android.content.Context; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.LinearLayout; import com.wkw.common_lib.network.Network; import com.wkw.common_lib.network.NetworkState; import com.wkw.common_lib.network.NetworkStateListener; import com.wkw.hot.R; import com.wkw.hot.base.BaseLazyFragment; import com.wkw.hot.base.BaseOnScrollListener; import com.wkw.hot.model.PopularModel; import com.wkw.hot.reject.component.AppComponent; import com.wkw.hot.reject.component.DaggerFragmentComponent; import com.wkw.hot.reject.module.FragmentModule; import com.wkw.hot.ui.web.WebActivity; import com.wkw.common_lib.widget.ProgressLayout; import java.util.List; import butterknife.Bind; import butterknife.OnClick; /** * Created by wukewei on 16/5/30. */ public class ItemFragment extends BaseLazyFragment implements ItemContract.View { public static final String TYPE = "type"; protected String type; @Bind(R.id.recycler_view) RecyclerView recyclerView; @Bind(R.id.swipe_refresh_layout) SwipeRefreshLayout swipeRefreshLayout; @Bind(R.id.progress_layout) ProgressLayout progressLayout; View.OnClickListener tryClick; @Bind(R.id.llyt_network) LinearLayout llytNetwork; private ItemAdapter mAdapter; public static ItemFragment newInstance(String type) { ItemFragment fragment = new ItemFragment(); Bundle bundle = new Bundle(); bundle.putString(TYPE, type); fragment.setArguments(bundle); return fragment; } private NetworkChangeListener mNetworkChangeListener; @Override protected void onFirstUserVisible() { mPresenter.getCacheData(type); } @Override protected void onUserVisible() { } @Override protected void onUserInvisible() { } class NetworkChangeListener implements NetworkStateListener { @Override public void onNetworkStateChanged(NetworkState lastState, NetworkState newState) { if (!newState.isConnected()) { showNetWorkLayout(); } else { hideNetWorkLayout(); } } } @Override protected void setupActivityComponent(AppComponent appComponent, FragmentModule fragmentModule) { DaggerFragmentComponent.builder() .appComponent(appComponent) .fragmentModule(fragmentModule) .build() .inject(this); } @Override protected int getLayoutId() { return R.layout.fragment_item; } @Override protected void initEventAndData() { mNetworkChangeListener = new NetworkChangeListener(); Network.addListener(mNetworkChangeListener); tryClick = v -> { mPresenter.replacePn(); mPresenter.getListData(type); }; mAdapter = new ItemAdapter(); mAdapter.setOnItemClickListener((url, title) -> { WebActivity.startActivity(mContext, url, title); }); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setLayoutManager(new LinearLayoutManager(mContext)); recyclerView.setAdapter(mAdapter); type = getArguments().getString(TYPE); recyclerView.addOnScrollListener(new BaseOnScrollListener() { @Override public void onLoadMore() { if (mAdapter.canLoadMore()) { mAdapter.setLoading(true); mPresenter.pn++; mPresenter.getListData(type); } } }); swipeRefreshLayout.setOnRefreshListener(() -> { mPresenter.replacePn(); mPresenter.getListData(type); }); } @Override public void addLoadMoreData(List data) { mAdapter.addLoadMoreData(data); } @Override public void addRefreshData(List data) { hideRefreshLayout(); mAdapter.addRefreshData(data); } @Override public void showLoading() { if (!progressLayout.isContent()) progressLayout.showLoading(); } private void hideRefreshLayout() { if (swipeRefreshLayout.isRefreshing()) { swipeRefreshLayout.postDelayed(() -> { swipeRefreshLayout.setRefreshing(false); }, 800); } } @Override public void showContent() { if (!progressLayout.isContent()) progressLayout.showContent(); } @Override public void showNotData() { progressLayout.showNotData(tryClick); } @Override public void showError(String msg) { hideRefreshLayout(); progressLayout.showError(msg, tryClick); } @Override public Context context() { return getActivity().getApplication(); } @OnClick(value = R.id.img_delete) public void onDelete(View view) { hideNetWorkLayout(); } private void showNetWorkLayout() { if (llytNetwork.getVisibility() == View.GONE) { llytNetwork.setVisibility(View.VISIBLE); } } private void hideNetWorkLayout() { if (llytNetwork.getVisibility() == View.VISIBLE) { llytNetwork.setVisibility(View.GONE); } } @Override public void onDestroy() { Network.removeListener(mNetworkChangeListener); super.onDestroy(); } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/item/ItemPresenter.java ================================================ package com.wkw.hot.ui.item; import com.wkw.common_lib.rx.RxSubscriber; import com.wkw.hot.base.BasePresenter; import com.wkw.hot.data.DataManager; import com.wkw.hot.entity.PopularEntity; import com.wkw.hot.mapper.PopularModelDataMapper; import com.wkw.hot.model.PopularModel; import java.util.List; import javax.inject.Inject; import rx.Subscription; /** * Created by wukewei on 16/5/30. */ public class ItemPresenter extends BasePresenter implements ItemContract.Presenter { protected int pn = 1; private final DataManager mDataManager; private final PopularModelDataMapper mPopularModelDataMapper; protected void replacePn() { pn = 1; } private boolean isRefresh() { return pn == 1; } @Inject public ItemPresenter(DataManager dataManager, PopularModelDataMapper popularModelDataMapper) { mDataManager = dataManager; mPopularModelDataMapper = popularModelDataMapper; } @Override public void getListData(String type) { mView.showLoading(); Subscription subscription = mDataManager.getPopular(pn, type) .map(popularEntityList -> mPopularModelDataMapper.transform(popularEntityList)) .subscribe(new RxSubscriber>() { @Override public void _noNext(List populars) { mView.showContent(); if (isRefresh()) { if (populars.size() == 0) mView.showNotData(); mView.addRefreshData(populars); } else { mView.addLoadMoreData(populars); } } @Override public void _onError(String msg) { if (isRefresh()) mView.showError(msg); } }); addSubscribe(subscription); } @Override public void getCacheData(String type) { mView.showLoading(); Subscription subscription = mDataManager.getCachePopular(type) .map(popularEntityList -> mPopularModelDataMapper.transform(popularEntityList)) .subscribe(new RxSubscriber>() { @Override public void _noNext(List populars) { mView.showContent(); mView.addLoadMoreData(populars); } @Override public void _onError(String msg) { mView.showError(msg); } }); addSubscribe(subscription); } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/main/MainActivity.java ================================================ package com.wkw.hot.ui.main; import android.content.Intent; import android.speech.RecognizerIntent; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import com.github.markzhai.react.preloader.ReactPreLoader; import com.miguelcatalan.materialsearchview.MaterialSearchView; import com.wkw.common_lib.utils.ToashUtils; import com.wkw.hot.R; import com.wkw.hot.adapter.FragmentAdapter; import com.wkw.hot.base.BaseActivity; import com.wkw.hot.reject.component.AppComponent; import com.wkw.hot.reject.component.DaggerActivityComponent; import com.wkw.hot.reject.module.ActivityModule; import com.wkw.hot.ui.AboutActivity; import com.wkw.hot.ui.item.ItemFragment; import com.wkw.hot.ui.react.MyReactActivity; import com.wkw.hot.ui.search.SearchActivity; import java.util.ArrayList; import java.util.List; import butterknife.Bind; public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, MainContract.View { @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.drawer_layout) DrawerLayout drawer; @Bind(R.id.tabs) TabLayout tabLayout; @Bind(R.id.viewpager) ViewPager viewpager; @Bind(R.id.nav_view) NavigationView navView; @Bind(R.id.search_view) MaterialSearchView searchView; protected FragmentAdapter mAdapter; @Override protected void setupActivityComponent(AppComponent appComponent, ActivityModule activityModule) { DaggerActivityComponent.builder() .appComponent(appComponent) .activityModule(activityModule) .build() .inject(this); } @Override protected int getLayout() { return R.layout.activity_main; } @Override protected void initEventAndData() { setSupportActionBar(toolbar); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); mPresenter.getTabs(); navView.setNavigationItemSelectedListener(this); ReactPreLoader.init(this, MyReactActivity.reactInfo); searchView.setVoiceSearch(false); searchView.setCursorDrawable(R.drawable.custom_cursor); searchView.setEllipsize(true); searchView.setHint(getString(R.string.search)); searchView.setSuggestions(getResources().getStringArray(R.array.query_suggestions)); searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { SearchActivity.startActivity(mContext, query); return false; } @Override public boolean onQueryTextChange(String newText) { //Do some magic return false; } }); searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() { @Override public void onSearchViewShown() { //Do some magic } @Override public void onSearchViewClosed() { //Do some magic } }); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { if (searchView.isSearchOpen()) { searchView.closeSearch(); } else { super.onBackPressed(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); MenuItem item = menu.findItem(R.id.action_search); searchView.setMenuItem(item); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); int id = item.getItemId(); if (id == R.id.nav_sports) { navigator.navigateToMyReact(mContext); } else if (id == R.id.nav_about) { navigator.navigateToAbout(mContext); } return true; } @Override public void addTabs(List tabs) { mAdapter = new FragmentAdapter(getSupportFragmentManager()); for (String tab : tabs) { ItemFragment fragment = ItemFragment.newInstance(tab); mAdapter.addFragment(fragment, tab); } viewpager.setAdapter(mAdapter); tabLayout.setupWithViewPager(viewpager); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == RESULT_OK) { ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); if (matches != null && matches.size() > 0) { String searchWrd = matches.get(0); if (!TextUtils.isEmpty(searchWrd)) { searchView.setQuery(searchWrd, false); } } return; } super.onActivityResult(requestCode, resultCode, data); } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/main/MainContract.java ================================================ package com.wkw.hot.ui.main; import com.wkw.hot.base.IPresenter; import com.wkw.hot.base.IView; import java.util.List; /** * Created by wukewei on 16/5/26. */ public interface MainContract { interface View extends IView { void addTabs(List tabs); } interface Presenter extends IPresenter { void getTabs(); } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/main/MainPresenter.java ================================================ package com.wkw.hot.ui.main; import com.wkw.hot.base.BasePresenter; import com.wkw.hot.data.DataManager; import javax.inject.Inject; /** * Created by wukewei on 16/5/26. */ public class MainPresenter extends BasePresenter implements MainContract.Presenter { private final DataManager mDataManager; @Inject public MainPresenter(DataManager dataManager) { mDataManager = dataManager; } @Override public void getTabs() { //类型暂时先写死 mView.addTabs(mDataManager.getTabs()); } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/react/MyReactActivity.java ================================================ package com.wkw.hot.ui.react; import com.github.markzhai.react.preloader.MrReactActivity; import com.github.markzhai.react.preloader.ReactInfo; /** * Created by wukewei on 16/8/15. */ public class MyReactActivity extends MrReactActivity { public static final ReactInfo reactInfo = new ReactInfo("MyHot", null); @Override protected String getMainComponentName() { return reactInfo.getMainComponentName(); } @Override public ReactInfo getReactInfo() { return reactInfo; } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/search/SearchActivity.java ================================================ package com.wkw.hot.ui.search; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import butterknife.Bind; import com.wkw.hot.R; import com.wkw.hot.base.BaseActivity; import com.wkw.hot.reject.component.AppComponent; import com.wkw.hot.reject.module.ActivityModule; import com.wkw.hot.ui.item.ItemFragment; /** * Created by wukewei on 16/9/14. */ public class SearchActivity extends BaseActivity { public static final String TYPE = "TYPE"; @Bind(R.id.toolbar) Toolbar toolbar; private String type; public static void startActivity(Context context, String type) { Intent intent = new Intent(context, SearchActivity.class); intent.putExtra(TYPE, type); context.startActivity(intent); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); type = getIntent().getStringExtra(TYPE); setCommonBackToolBack(toolbar, type); if (savedInstanceState == null) { ItemFragment fragment = ItemFragment.newInstance(type); loadFragment(fragment); } } private void loadFragment(Fragment fragment) { getSupportFragmentManager().beginTransaction() .add(R.id.container, fragment, fragment.getClass().getName()) .commit(); fragment.setUserVisibleHint(true); } @Override protected void setupActivityComponent(AppComponent appComponent, ActivityModule activityModule) { } @Override protected int getLayout() { return R.layout.activity_search; } @Override protected void initEventAndData() { } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/web/WebActivity.java ================================================ package com.wkw.hot.ui.web; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import com.wkw.common_lib.utils.AndroidUtils; import com.wkw.hot.R; import com.wkw.hot.base.BaseActivity; import com.wkw.hot.base.IPresenter; import com.wkw.hot.reject.component.AppComponent; import com.wkw.hot.reject.component.DaggerActivityComponent; import com.wkw.hot.reject.module.ActivityModule; import com.wkw.hot.ui.AboutActivity; import butterknife.Bind; /** * Created by wukewei on 16/6/2. */ public class WebActivity extends BaseActivity implements WebContract.View { private static final String URL = "url"; private static final String TITLE = "title"; @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.webView) WebView webView; @Bind(R.id.progress_bar) ProgressBar progressBar; private String url, title; public static void startActivity(Context context, String url, String title) { Intent intent = new Intent(context,WebActivity.class); intent.putExtra(URL, url); intent.putExtra(TITLE, title); context.startActivity(intent); } @Override protected int getLayout() { return R.layout.activity_web; } @Override protected void initEventAndData() { url = getIntent().getStringExtra(URL); title = getIntent().getStringExtra(TITLE); setCommonBackToolBack(toolbar, title); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); settings.setLoadWithOverviewMode(true); settings.setAppCacheEnabled(true); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); settings.setSupportZoom(true); webView.setWebChromeClient(new ChromeClient()); webView.setWebViewClient(new Client()); webView.loadUrl(url); } @Override protected void onResume() { super.onResume(); if (webView != null) webView.onResume(); } @Override protected void onPause() { super.onPause(); if (webView != null) webView.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (webView.canGoBack()) { webView.goBack(); } else { finish(); } return true; } } return super.onKeyDown(keyCode, event); } @Override protected void setupActivityComponent(AppComponent appComponent, ActivityModule activityModule) { DaggerActivityComponent.builder() .appComponent(appComponent) .activityModule(activityModule) .build() .inject(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_web, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_other_browser: AndroidUtils.openBrowser(mContext, url); return true; case R.id.action_cory_url: AndroidUtils.copyToClipBoard(mContext, webView.getUrl()); return true; case R.id.action_share: AndroidUtils.showSystemShareOption(mContext, getString(R.string.share_title), url); return true; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { super.onDestroy(); if (webView != null) { webView.removeAllViews(); webView.destroy(); } } private class ChromeClient extends WebChromeClient { @Override public void onProgressChanged(WebView view, int newProgress) { progressBar.setProgress(newProgress); if (newProgress == 100) { progressBar.setVisibility(View.GONE); } else { progressBar.setVisibility(View.VISIBLE); } super.onProgressChanged(view, newProgress); } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); } } private class Client extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url!=null) view.loadUrl(url); return true; } } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/web/WebContract.java ================================================ package com.wkw.hot.ui.web; import com.wkw.hot.base.IPresenter; import com.wkw.hot.base.IView; /** * Created by wukewei on 16/5/30. */ public class WebContract { interface View extends IView { } interface Presenter extends IPresenter { } } ================================================ FILE: app/src/main/java/com/wkw/hot/ui/web/WebPresenter.java ================================================ package com.wkw.hot.ui.web; import com.wkw.hot.base.BasePresenter; import com.wkw.hot.data.DataManager; import javax.inject.Inject; /** * Created by wukewei on 16/5/30. */ public class WebPresenter extends BasePresenter implements WebContract.Presenter { @Inject public WebPresenter() { } } ================================================ FILE: app/src/main/java/com/wkw/hot/utils/GlideManager.java ================================================ package com.wkw.hot.utils; import android.content.Context; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; /** * Created by wukewei on 16/6/30. */ public class GlideManager { public static void loadListImageView(Context context, String url, ImageView imageView) { Glide.with(context) .load(url) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imageView); } } ================================================ FILE: app/src/main/java/com/wkw/hot/utils/Logger.java ================================================ package com.wkw.hot.utils; import android.util.Log; /** * Created by wukewei on 16/6/1. */ public class Logger { public static boolean isDebug = true; public static final String TAG = "HOT_TAG"; public static void d(String msg) { if (isDebug) Log.d(TAG, msg); } public static void i(String msg) { if (isDebug) Log.i(TAG, msg); } public static void e(String msg) { if (isDebug) Log.e(TAG, msg); } public static void w(String msg) { if (isDebug) Log.w(TAG, msg); } public static void v(String msg) { if (isDebug) Log.v(TAG, msg); } } ================================================ FILE: app/src/main/res/drawable/custom_cursor.xml ================================================ ================================================ FILE: app/src/main/res/drawable/progress_bar_bg.xml ================================================ ================================================ FILE: app/src/main/res/drawable/side_nav_bar.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v21/ic_menu_camera.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v21/ic_menu_gallery.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v21/ic_menu_manage.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v21/ic_menu_send.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v21/ic_menu_share.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v21/ic_menu_slideshow.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_about.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_search.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_web.xml ================================================ ================================================ FILE: app/src/main/res/layout/app_bar_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_item.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_list.xml ================================================ ================================================ FILE: app/src/main/res/layout/layout_item.xml ================================================ ================================================ FILE: app/src/main/res/layout/layout_toolbar_view.xml ================================================ ================================================ FILE: app/src/main/res/layout/nav_header_main.xml ================================================ ================================================ FILE: app/src/main/res/menu/activity_main_drawer.xml ================================================ ================================================ FILE: app/src/main/res/menu/main.xml ================================================ ================================================ FILE: app/src/main/res/menu/menu_web.xml ================================================ ================================================ FILE: app/src/main/res/values/arrays.xml ================================================ 科技 美女 生活 娱乐 搞笑 宅男 ================================================ FILE: app/src/main/res/values/colors.xml ================================================ #3F51B5 #303F9F #FF4081 #EED6CC #FFFFFF ================================================ FILE: app/src/main/res/values/dimens.xml ================================================ 16dp 160dp 16dp 16dp 16dp 8dp 18dp 230dp 12dp 8dp 0dp ================================================ FILE: app/src/main/res/values/drawables.xml ================================================ @android:drawable/ic_menu_camera @android:drawable/ic_menu_gallery @android:drawable/ic_menu_slideshow @android:drawable/ic_menu_manage @android:drawable/ic_menu_share @android:drawable/ic_menu_send ================================================ FILE: app/src/main/res/values/strings.xml ================================================ Hot Open navigation drawer Close navigation drawer Settings 关于 https://github.com/zj-wukewei/Hot 网络不可用,请检查网络设置 头条&Hot - 每日热门分享 用浏览器打开 复杂链接 分享 请输入搜索类型 微信热门分享 我是个毕业于三流的本科学校,还是个android小菜鸟,通过不断的学习和不断的看些大牛的源码进行成长,代码之路还很遥远还要不断的努力,希望通过自己的不断学习能早日的入android的门 "com.android.support:appcompat-v7:23.2.0"\n "com.android.support:design:23.2.0"\n "com.android.support:cardview-v7:23.2.0"\n "com.android.support:recyclerview-v7:23.2.0"\n "com.squareup.retrofit2:retrofit:2.0.2"\n "com.squareup.okhttp3:logging-interceptor:3.3.0"\n "io.reactivex:rxandroid:1.2.0"\n "com.squareup.retrofit2:converter-gson:2.0.2"\n "com.squareup.retrofit2:adapter-rxjava:2.0.2"\n "com.google.showapi_res_code.gson:gson:2.6.2"\n "com.github.bumptech.glide:glide:3.7.0"\n "com.jakewharton:butterknife:7.0.1"\n "com.google.dagger:dagger:2.0"\n "com.google.dagger:dagger-compiler:2.0"\n "org.glassfish:javax.annotation:10.0-b28" 这是一个关于微信热门头条分享的app,每天都会更新不同的热门分享\n\n数据来源于百度开放者平台的api,只要去申请 个apikey即可,里面有很多其它api可以供大家使用\n\n 项目采用的技术是 MVP+Rxjava+Retrofit+Dagger2来实现的,这个项目是我在学习新的技术 的时候来练习的一个项目,我像一个产品级的app来对待的\n\n本项目中common_lib下的有些是参考大帅的代码,这里非常的感谢大神的开源项目,让我学习到了很多\n\n 项目Github地址:https://github.com/zj-wukewei/Hot欢迎star ================================================ FILE: app/src/main/res/values/styles.xml ================================================ ================================================ FILE: app/src/main/res/values-v21/styles.xml ================================================ ================================================ FILE: app/src/main/res/values-w820dp/dimens.xml ================================================ 64dp ================================================ FILE: app/src/test/java/com/wkw/hot/ExampleUnitTest.java ================================================ package com.wkw.hot; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } } ================================================ FILE: build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. apply from: "version.gradle" buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.2' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' classpath 'me.tatarka:gradle-retrolambda:3.2.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() jcenter() maven { // All of React Native (JS, Android binaries) is installed from npm url "$rootDir/node_modules/react-native/android" } } } task clean(type: Delete) { delete rootProject.buildDir } ================================================ FILE: common_lib/.gitignore ================================================ /build ================================================ FILE: common_lib/build.gradle ================================================ apply plugin: 'com.android.library' android { compileSdkVersion rootProject.ext.android.compileSdkVersion buildToolsVersion rootProject.ext.android.buildToolsVersion defaultConfig { minSdkVersion rootProject.ext.android.minSdkVersion targetSdkVersion rootProject.ext.android.targetSdkVersion versionCode rootProject.ext.android.versionCode versionName rootProject.ext.android.versionName } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile rootProject.ext.dependencies["appcompat-v7"] compile rootProject.ext.dependencies["recyclerview-v7"] compile rootProject.ext.dependencies["glide"] compile rootProject.ext.dependencies["rxandroid"] } ================================================ FILE: common_lib/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/wukewei/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 # http://developer.android.com/guide/developing/tools/proguard.html # 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 *; #} ================================================ FILE: common_lib/src/androidTest/java/com/wkw/common_lib/ApplicationTest.java ================================================ package com.wkw.common_lib; import android.app.Application; import android.test.ApplicationTestCase; /** * Testing Fundamentals */ public class ApplicationTest extends ApplicationTestCase { public ApplicationTest() { super(Application.class); } } ================================================ FILE: common_lib/src/main/AndroidManifest.xml ================================================ ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/Ext.java ================================================ package com.wkw.common_lib; import android.app.Application; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; /** * Created by wukewei on 16/7/24. */ public abstract class Ext { private static final String TAG = "Ext"; private static Context sContext = null; private static Application sApplication = null; private static String sPackageName; private static String sVersionName; private static String sBuildNumber; private static int sVersionCode = 0; private static Ext sInstance = null; public static Ext g() { if (sInstance == null) { throw new RuntimeException("Ext 没有初始化!"); } return sInstance; } public static void init(Application app, Ext instance) { sContext = app.getApplicationContext(); sApplication = app; sInstance = instance; sPackageName = sApplication.getPackageName(); initVersionCodeAndName(sApplication); } private static void initVersionCodeAndName(Context context) { String version = ""; try { PackageInfo info = context.getPackageManager().getPackageInfo(sPackageName, 0); sVersionCode = info.versionCode; version = info.versionName; } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "initVersionCodeAndName"); } sVersionName = version.substring(0, version.lastIndexOf('.')); sBuildNumber = version.substring(version.lastIndexOf('.') + 1, version.length()); } public static Context getContext() { return sContext; } public static Application getApplication() { return sApplication; } public abstract String getCurOpenId(); public abstract String getDeviceInfo(); public abstract String getPackageNameForResource(); public String getPackageName() { return sPackageName; } public int getVersionCode() { return sVersionCode; } public String getVersionName() { return sVersionName; } public String getBuilderNumber() { return sBuildNumber; } public abstract int getScreenHeight(); public abstract int getScreenWidth(); // Network public abstract boolean isAvailable(); public abstract boolean isWap(); public abstract boolean isMobile(); public abstract boolean is2G(); public abstract boolean is3G(); public abstract boolean isWifi(); public abstract boolean isEthernet(); } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/image/ImageConfig.java ================================================ package com.wkw.common_lib.image; import android.widget.ImageView; /** * Created by wukewei on 16/12/22. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class ImageConfig { protected ImageView imageView; protected String url; protected int placeholder; protected int errorPic; public String getUrl() { return url; } public ImageView getImageView() { return imageView; } public int getPlaceholder() { return placeholder; } public int getErrorPic() { return errorPic; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/image/ImageLoader.java ================================================ package com.wkw.common_lib.image; import android.content.Context; import com.wkw.common_lib.image.glide.GlideImageConfig; import static com.wkw.common_lib.image.glide.GlideImageConfig.*; /** * Created by wukewei on 16/12/22. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class ImageLoader { private ImageLoaderStrategy mImageLoaderStrategy; public ImageLoader() { } public void setImageLoaderStragety(ImageLoaderStrategy imageLoaderStrategy) { this.mImageLoaderStrategy = imageLoaderStrategy; } public void displayImage(Context context, T config) { this.mImageLoaderStrategy.loadImage(context, config); } public static ImageLoader getInstance() { return ImageLoaderInstance.mImageLoader; } public static class ImageLoaderInstance { private final static ImageLoader mImageLoader = new ImageLoader(); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/image/ImageLoaderStrategy.java ================================================ package com.wkw.common_lib.image; import android.content.Context; /** * Created by wukewei on 16/12/22. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public interface ImageLoaderStrategy { void loadImage(Context context, T t); } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/image/glide/GlideImageConfig.java ================================================ package com.wkw.common_lib.image.glide; import android.widget.ImageView; import com.wkw.common_lib.image.ImageConfig; /** * Created by wukewei on 16/12/22. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class GlideImageConfig extends ImageConfig { private int cacheStrategy; public GlideImageConfig(Builder builder) { this.url = builder.url; this.imageView = builder.imageView; this.placeholder = builder.placeholder; this.errorPic = builder.errorPic; this.cacheStrategy = builder.cacheStrategy; } public int getCacheStrategy() { return cacheStrategy; } public void setCacheStrategy(int cacheStrategy) { this.cacheStrategy = cacheStrategy; } public static Builder builder() { return new Builder(); } public static final class Builder { private String url; private ImageView imageView; private int placeholder; private int errorPic; private int cacheStrategy;//0对应DiskCacheStrategy.all,1对应DiskCacheStrategy.NONE,2对应DiskCacheStrategy.SOURCE,3对应DiskCacheStrategy.RESULT private Builder() { } public Builder url(String url) { this.url = url; return this; } public Builder placeholder(int placeholder) { this.placeholder = placeholder; return this; } public Builder errorPic(int errorPic){ this.errorPic = errorPic; return this; } public Builder imagerView(ImageView imageView) { this.imageView = imageView; return this; } public Builder cacheStrategy(int cacheStrategy) { this.cacheStrategy = cacheStrategy; return this; } public GlideImageConfig build() { if (url == null) throw new IllegalStateException("url is required"); if (imageView == null) throw new IllegalStateException("imageview is required"); return new GlideImageConfig(this); } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/image/glide/GlideImageLoaderStrategy.java ================================================ package com.wkw.common_lib.image.glide; import android.app.Activity; import android.content.Context; import com.bumptech.glide.DrawableRequestBuilder; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.wkw.common_lib.image.ImageLoaderStrategy; /** * Created by wukewei on 16/12/22. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class GlideImageLoaderStrategy implements ImageLoaderStrategy { @Override public void loadImage(Context context, GlideImageConfig imageConfig) { RequestManager manager; if (context instanceof Activity) { manager = Glide.with((Activity) context); } else { manager = Glide.with(context); } DrawableRequestBuilder request = manager.load(imageConfig.getUrl()) .crossFade() .centerCrop(); switch (imageConfig.getCacheStrategy()) { case 0: request.diskCacheStrategy(DiskCacheStrategy.ALL); break; case 1: request.diskCacheStrategy(DiskCacheStrategy.NONE); break; case 2: request.diskCacheStrategy(DiskCacheStrategy.SOURCE); break; case 3: request.diskCacheStrategy(DiskCacheStrategy.RESULT); break; default: break; } if (imageConfig.getPlaceholder() != 0) { request.placeholder(imageConfig.getPlaceholder()); } if (imageConfig.getErrorPic() != 0) { request.error(imageConfig.getErrorPic()); } request.into(imageConfig.getImageView()); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/network/AccessPoint.java ================================================ package com.wkw.common_lib.network; import com.wkw.common_lib.utils.StringUtils; import java.util.HashMap; /** * Created by wukewei on 16/7/25. */ enum AccessPoint { /** * 接入点不可用,通常是无网络或者非移动网络 */ NONE(StringUtils.EMPTY, ServiceProvider.NONE, false), /** * 未知的接入点 */ NEVER_HEARD("I don't know", ServiceProvider.NEVER_HEARD, false), // 未知接入点 /** * 中国移动 cmnet */ CMNET("cmnet", ServiceProvider.CHINA_MOBILE, false), // 中国移动 NET /** * 中国移动 cmwap */ CMWAP("cmwap", ServiceProvider.CHINA_MOBILE, true), // 中国移动 WAP /** * 中国联通 2G uninet */ UNINET("uninet", ServiceProvider.CHINA_UNICOM, false), // 中国联通 2G NET /** * 中国联通 2G uniwap */ UNIWAP("uniwap", ServiceProvider.CHINA_UNICOM, true), // 中国联通 2G WAP /** * 中国联通 3G 3gnet */ _3GNET("3gnet", ServiceProvider.CHINA_UNICOM, false), // 中国联通 3G NET /** * 中国联通 3G 3gwap */ _3GWAP("3gwap", ServiceProvider.CHINA_UNICOM, true), // 中国联通 3G WAP /** * 中国电信 ctnet */ CTNET("ctnet", ServiceProvider.CHINA_TELECOM, false), // 中国电信 NET /** * 中国电信 ctwap */ CTWAP("ctwap", ServiceProvider.CHINA_TELECOM, true), // 中国电信 WAP /** * 中国电信 #777 */ SHARP777("#777", ServiceProvider.CHINA_TELECOM, false), // 中国电信 #777 ; private static HashMap ACCESS_POINT_MAP = new HashMap(); static { // 初始化所有已知的接入点 for (AccessPoint accessPoint : AccessPoint.values()) { ACCESS_POINT_MAP.put(accessPoint.getName(), accessPoint); } } private String name; private ServiceProvider provider; private boolean wap; AccessPoint(String name, ServiceProvider provider, boolean isWap) { setName(name); setProvider(provider); setWap(isWap); } /** * 获得对应的接入点对象 * * @param name 接入点名称 * @return 接入点枚举对象
*
* 如果名称为空,得到{@link AccessPoint}.NONE
* 如果并非此枚举中的范围,得到{@link AccessPoint}.NEVER_HEARD */ public static AccessPoint forName(String name) { if (name == null) { return NONE; } AccessPoint accessPoint = ACCESS_POINT_MAP.get(name.toLowerCase()); return ((accessPoint == null) ? NEVER_HEARD : accessPoint); } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * 获取接入点所属于的服务运营商 * * @return 运营商枚举 */ public ServiceProvider getProvider() { return provider; } public void setProvider(ServiceProvider provider) { this.provider = provider; } /** * 判断是否是WAP接入点 * * @return 是否是WAP接入点 */ public boolean isWap() { return wap; } public void setWap(boolean wap) { this.wap = wap; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/network/Network.java ================================================ package com.wkw.common_lib.network; import android.support.annotation.RequiresPermission; import com.wkw.common_lib.Ext; import com.wkw.common_lib.utils.NetWorkUtils; /** * Created by wukewei on 16/7/25. */ public class Network extends NetworkDash { /** * 系统代理信息 */ public static abstract class Proxy { public static int getPort() { return android.net.Proxy.getDefaultPort(); } public static String getHost() { return android.net.Proxy.getDefaultHost(); } } /** * WIFI网卡信息 */ public static class Wifi extends WifiDash { } public static class Dns { @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE) public static NetWorkUtils.DNS getDNS() { return NetWorkUtils.getDNS(Ext.getContext()); } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/network/NetworkDash.java ================================================ package com.wkw.common_lib.network; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import com.wkw.common_lib.Ext; import com.wkw.common_lib.utils.NetWorkUtils; import com.wkw.common_lib.utils.StringUtils; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * Created by wukewei on 16/7/25. */ class NetworkDash { private static final String TAG = "NetworkDash"; private static final List> OBSERVER_LIST = new ArrayList>(); private static NetworkState currState; private static NetworkState lastState; private static Handler mainHandler; /** * IMSI的运营商,为了减少IPC通信,只在网络变更的时候更新它 */ private static ServiceProvider imsiProvider = null; private static final NetworkObserver OBSERVER = new NetworkObserver() { @Override public void onNetworkChanged() { updateNetworkState(); } }; static { // 初始化当前网络状态 updateNetworkState(); // 开始监听网络变化 OBSERVER.startListen(); } /** * 判断当前网络是否可用,这将刷新当前网络信息 * * @return 网络是否已经连接上 */ public static boolean isAvailable() { updateNetworkState(); NetworkState state = getCurrState(); return state != null && state.isConnected(); } /** * 比 {@link #isAvailable()}快 * * @return 网络是否已经连接上 */ public static boolean isAvailableFast() { NetworkState state = getCurrState(); return state != null && state.isConnected(); } /** * 获得当前移动网络的接入点
*
* 如果无网络/并非移动网络,得到{@link AccessPoint}.NONE
* 如果并非{@link AccessPoint}枚举中的范围,得到{@link AccessPoint}.NEVER_HEARD * * @return 接入点枚举 * @see AccessPoint */ public static AccessPoint getAccessPoint() { NetworkState state = getCurrState(); if (state != null) { return state.getAccessPoint(); } else { return AccessPoint.NONE; } } /** * 获得当前本地IP */ public static String getLocalIP() { return NetWorkUtils.getLocalIP(); } /** * 获得当前的网络类型 * * @return 网络类型枚举 * @see NetworkType */ public static NetworkType getType() { NetworkState state = getCurrState(); if (state != null) { return state.getType(); } else { return NetworkType.NONE; } } /** * 获得当前的接入点名称 *

* 建议只在需要未知接入点或者具体接入点名称时使用,若要对接入点进行逻辑分支, * 请使用getAccessPoint()方法 * * @return 接入点名称 * @see AccessPoint */ public static String getApnName() { NetworkState state = getCurrState(); if (state != null) { return state.getApnName(); } else { return StringUtils.EMPTY; } } /** * 获得接入点名字或者"wifi"字样 * * @return 接入点名字或者"wifi" */ public static String getApnNameOrWifi() { if (!isAvailable()) { return StringUtils.EMPTY; } else { if (isWifi()) { return "wifi"; } else { return getApnName(); } } } /** * 获得接入点名字或者"wifi"字样或者"ethernet"字样 */ public static String getApnNameOrWifiOrEthernet() { if (!isAvailable()) { return StringUtils.EMPTY; } else { if (isWifi()) { return "wifi"; } else if (isEthernet()) { return "ethernet"; } else { return getApnName(); } } } /** * 获得当前的运营商,使用APN * * @return 运营商 * @see ServiceProvider */ public static ServiceProvider getProvider() { NetworkState state = getCurrState(); if (state != null) { return state.getAccessPoint().getProvider(); } else { return ServiceProvider.NONE; } } /** * 获得当前的运营商 * * @param useIMSIFirst 优先使用IMSI判断 * @return 运营商 * @see ServiceProvider */ public static ServiceProvider getProvider(boolean useIMSIFirst) { ServiceProvider provider = ServiceProvider.NONE; if (useIMSIFirst) { provider = getIMSIProvider(); if (!ServiceProvider.NONE.equals(provider)) { return provider; } } provider = getProvider(); return provider; } /** * 获得当前的运营商,根据IMSI中的MNC和MCC记录,即可刷新 */ public static ServiceProvider updateIMSIProvider() { // 防止权限问题和IPC通信问题 try { synchronized (NetworkDash.class) { String IMSI = getIMSI(); imsiProvider = ServiceProvider.fromIMSI(IMSI); Log.v(TAG, IMSI + " => " + imsiProvider); return imsiProvider; } } catch (Exception e) { return ServiceProvider.NONE; } } public static String getIMSI() { try { TelephonyManager telephonyManager = (TelephonyManager) Ext.getContext().getSystemService(Context.TELEPHONY_SERVICE); String IMSI1 = telephonyManager.getSimOperator(); // 处理双卡手机 if (TextUtils.isEmpty(IMSI1)) { IMSI1 = getDeviceIdBySlot(Ext.getContext(), 0); } if (TextUtils.isEmpty(IMSI1)) { IMSI1 = getDeviceIdBySlot(Ext.getContext(), 1); } Log.v(TAG, "imsi: " + IMSI1); return IMSI1; } catch (Exception e) { return null; } } // 获取双卡双待IMEI public static String getDeviceIdBySlot(Context context, int slotID) { Log.v(TAG, "isDeviceIdBySlot:" + slotID); if (context == null) return null; if (slotID < 0 || slotID > 1) return null; String imei = null; try { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); Class mLoadClass = Class.forName("android.telephony.TelephonyManager"); Class[] parameter = new Class[1]; parameter[0] = int.class; Method getSimStateGemini = mLoadClass.getMethod("getSimOperatorGemini", parameter); Object[] obParameter = new Object[1]; obParameter[0] = slotID; Object ob_phone = getSimStateGemini.invoke(telephonyManager, obParameter); if (ob_phone != null) { imei = ob_phone.toString(); } } catch (Exception e) { Log.w(TAG, "getDeviceIdBySlot", e); } return imei; } /** * 获得当前的运营商,根据IMSI中的MNC和MCC记录 * * @return the imsiProvider */ public static ServiceProvider getIMSIProvider() { if (imsiProvider == null) { updateIMSIProvider(); } return imsiProvider; } /** * 判断当前是否是WAP网络 * * @return 若是移动网络且接入点是WAP接入点,返回true,否则返回false,包括非wap网络、非移动网络和无网络 */ public static boolean isWap() { return getAccessPoint().isWap(); } /** * 判断当前是否是移动网络 * * @return 若是移动网络,返回true,否则返回false,包括非移动网络和无网络 */ public static boolean isMobile() { NetworkType type = getType(); return NetworkType.MOBILE_4G.equals(type) || NetworkType.MOBILE_3G.equals(type) || NetworkType.MOBILE_2G.equals(type); } public static boolean is2G() { NetworkType type = getType(); return NetworkType.MOBILE_2G.equals(type); } public static boolean is3G() { NetworkType type = getType(); return NetworkType.MOBILE_3G.equals(type); } /** * 判断当前是否是WIFI网络 * * @return 若是WIFI网络,返回true,否则返回false,包括非WIFI网络和无网络 */ public static boolean isWifi() { return NetworkType.WIFI.equals(getType()); } /** * 判断当时是否是有线网络 * * @return 若是有线网络,返回true,否则返回flase */ public static boolean isEthernet() { return NetworkType.ETHERNET.equals(getType()); } /** * 获得手机信号格数,和状态栏的提示理论上保持一致
*
* 支持GSM/CDMA/EVDO网络,会自动处理
* 至少需要Android 2.1及以上的API Level (7) * * @return 从弱到强 0..4
* 如果不支持或者尚未获得,返回 -1 */ public static int getCellLevel() { return OBSERVER.getCellLevel(); } /** * 添加网络状态变化监听器 * * @param listener 监听器 */ public static void addListener(NetworkStateListener listener) { synchronized (OBSERVER_LIST) { OBSERVER_LIST.add(new WeakReference(listener)); } } /** * 移除网络状态变化监听器 * * @param listener 监听器 */ public static void removeListener(NetworkStateListener listener) { synchronized (OBSERVER_LIST) { WeakReference reference = null; for (WeakReference weakReference : OBSERVER_LIST) { NetworkStateListener realListener = weakReference.get(); if (realListener != null) { if (realListener.equals(listener)) { reference = weakReference; break; } } } OBSERVER_LIST.remove(reference); } } private static void notifyNetworkStateChange() { if (OBSERVER_LIST == null) { return; } synchronized (OBSERVER_LIST) { for (WeakReference listener : OBSERVER_LIST) { NetworkStateListener realListener = listener.get(); if (realListener != null) { realListener.onNetworkStateChanged(getLastState(), getCurrState()); } } } } /** * 刷新网络信息
* * @return 网络信息是否变化 */ public static boolean updateNetworkState() { synchronized (NetworkDash.class) { NetworkInfo info = null; try { ConnectivityManager manager = (ConnectivityManager) Ext.getContext() .getSystemService(Context.CONNECTIVITY_SERVICE); if (manager == null) { return false; } info = manager.getActiveNetworkInfo(); } catch (Error e1) { info = null; } catch (Exception e) { info = null; } boolean changed = setCurrState(NetworkState.fromNetworkInfo(info)); if (changed) { // 网络变动时,更新IMSI信息 updateIMSIProvider(); if (mainHandler == null) { mainHandler = new Handler(Ext.getContext().getMainLooper()); } mainHandler.post(new Runnable() { @Override public void run() { notifyNetworkStateChange(); } }); } return changed; } } /** * 获得当前的网络状态信息 * * @return 网络状态信息 * @see NetworkState */ public static NetworkState getCurrState() { return currState; } protected static NetworkState getLastState() { return lastState; } /** * 更新当前的状态 * * @return 若状态变化,则返回true; 否则返回false */ protected static boolean setCurrState(NetworkState newState) { synchronized (NetworkDash.class) { boolean changed = false; if (currState == null) { NetworkDash.lastState = null; NetworkDash.currState = newState; changed = true; } else if (!currState.equals(newState)) { NetworkDash.lastState = NetworkDash.currState; NetworkDash.currState = newState; changed = true; } if (changed) { Log.v(TAG, "LAST -> " + lastState); Log.v(TAG, "CURR -> " + currState); } return changed; } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/network/NetworkObserver.java ================================================ package com.wkw.common_lib.network; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.telephony.PhoneStateListener; import android.telephony.SignalStrength; import android.telephony.TelephonyManager; import android.util.Log; import com.wkw.common_lib.Ext; /** * Created by wukewei on 16/7/25. */ abstract class NetworkObserver extends BroadcastReceiver{ private static final String TAG = "NetworkObserver"; private final boolean cellListenEnabled = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ECLAIR_MR1); private PhoneStateListener signalListener; private volatile int cellLevel = -1; /** * 当网络发生变化时回调 */ public abstract void onNetworkChanged(); public void startListen() { IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); try { Ext.getContext().registerReceiver(this, intentFilter); } catch (Exception e) { Log.w(TAG, "startListen failed"); } } public void stopListen() { Ext.getContext().unregisterReceiver(this); } /** * 获得手机信号格数,和状态栏的提示理论上保持一致 *

* 至少需要Android 2.1及以上的API Level (7) * * @return 从弱到强 0..4,如果不支持或者尚未获得,返回 -1 */ public int getCellLevel() { return cellLevel; } @Override public void onReceive(Context context, Intent intent) { if (cellListenEnabled) { if (signalListener == null) { synchronized (this) { if (signalListener == null) { initSignalListen(); } } } } if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { onNetworkChanged(); } } @SuppressLint("InlinedApi") private void initSignalListen() { if (!cellListenEnabled) { return; } signalListener = new PhoneStateListener() { @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { cellLevel = getCellLevel(signalStrength); super.onSignalStrengthsChanged(signalStrength); } }; TelephonyManager telephonyManager = (TelephonyManager) Ext.getContext().getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { telephonyManager.listen(signalListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); } else { // 监听失败 signalListener = null; } } private int getCellLevel(SignalStrength signalStrength) { int level = 0; if (signalStrength == null) { return -1; } if (signalStrength.isGsm()) { level = getGsmLevel(signalStrength); } else { int cdmaLevel = getCdmaLevel(signalStrength); int evdoLevel = getEvdoLevel(signalStrength); if (evdoLevel == 0) { level = cdmaLevel; } else if (cdmaLevel == 0) { level = evdoLevel; } else { level = evdoLevel > cdmaLevel ? cdmaLevel : evdoLevel; } } return level; } private int getGsmLevel(SignalStrength signalStrength) { int asu = signalStrength.getGsmSignalStrength(); // ASU ranges from 0 to 31 - TS 27.007 Sec 8.5 // asu = 0 (-113dB or less) is very weak // signal, its better to show 0 bars to the user in such cases. // asu = 99 is a special case, where the signal strength is unknown. if (asu <= 2 || asu == 99) return 0; else if (asu >= 12) return 4; else if (asu >= 8) return 3; else if (asu >= 5) return 2; else return 1; } // CDMA信号显示 private int getCdmaLevel(SignalStrength signalStrength) { final int cdmaDbm = signalStrength.getCdmaDbm(); final int cdmaEcio = signalStrength.getCdmaEcio(); int levelDbm = 0; int levelEcio = 0; if (cdmaDbm >= -75) levelDbm = 4; else if (cdmaDbm >= -85) levelDbm = 3; else if (cdmaDbm >= -95) levelDbm = 2; else if (cdmaDbm >= -100) levelDbm = 1; else levelDbm = 0; // Ec/Io are in dB*10 if (cdmaEcio >= -90) levelEcio = 4; else if (cdmaEcio >= -110) levelEcio = 3; else if (cdmaEcio >= -130) levelEcio = 2; else if (cdmaEcio >= -150) levelEcio = 1; else levelEcio = 0; return (levelDbm < levelEcio) ? levelDbm : levelEcio; } // EVDO网络显示 CDMA2000 3G信号显示(例如电信天翼3G) private int getEvdoLevel(SignalStrength signalStrength) { int evdoDbm = signalStrength.getEvdoDbm(); int evdoSnr = signalStrength.getEvdoSnr(); int levelEvdoDbm = 0; int levelEvdoSnr = 0; if (evdoDbm >= -65) levelEvdoDbm = 4; else if (evdoDbm >= -75) levelEvdoDbm = 3; else if (evdoDbm >= -90) levelEvdoDbm = 2; else if (evdoDbm >= -105) levelEvdoDbm = 1; else levelEvdoDbm = 0; if (evdoSnr >= 7) levelEvdoSnr = 4; else if (evdoSnr >= 5) levelEvdoSnr = 3; else if (evdoSnr >= 3) levelEvdoSnr = 2; else if (evdoSnr >= 1) levelEvdoSnr = 1; else levelEvdoSnr = 0; return (levelEvdoDbm < levelEvdoSnr) ? levelEvdoDbm : levelEvdoSnr; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/network/NetworkState.java ================================================ package com.wkw.common_lib.network; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.wkw.common_lib.utils.StringUtils; /** * Created by wukewei on 16/7/25. */ public class NetworkState { private static final NetworkState NONE = new NetworkState(false, null, AccessPoint.NONE, NetworkType.NONE); /** * 移动网络子类型常量 */ private static final int NETWORK_TYPE_UNKNOWN = 0; private static final int NETWORK_TYPE_GPRS = 1; private static final int NETWORK_TYPE_EDGE = 2; private static final int NETWORK_TYPE_UMTS = 3; private static final int NETWORK_TYPE_CDMA = 4; private static final int NETWORK_TYPE_EVDO_0 = 5; private static final int NETWORK_TYPE_EVDO_A = 6; private static final int NETWORK_TYPE_1xRTT = 7; private static final int NETWORK_TYPE_HSDPA = 8; private static final int NETWORK_TYPE_HSUPA = 9; private static final int NETWORK_TYPE_HSPA = 10; private static final int NETWORK_TYPE_IDEN = 11; private static final int NETWORK_TYPE_EVDO_B = 12; private static final int NETWORK_TYPE_LTE = 13; private static final int NETWORK_TYPE_EHRPD = 14; private static final int NETWORK_TYPE_HSPAP = 15; private boolean connected = false; private String apnName = null; private NetworkType type = NetworkType.NONE; private AccessPoint accessPoint = AccessPoint.NONE; private NetworkInfo moreInfo; private NetworkState(boolean conn, String apn, AccessPoint ap, NetworkType tp) { setConnected(conn); setApnName(apn); setAccessPoint(ap); setType(tp); } private NetworkState() { } /** * 从{@link android.net.NetworkInfo}构造网络状态信息 * * @param info NetworkInfo对象 * @return 网络状态 */ public static NetworkState fromNetworkInfo(NetworkInfo info) { // 得不到信息,返回NONE对象 if (info == null) { return NetworkState.NONE; } NetworkState state = new NetworkState(); state.setConnected(info.isConnected()); state.setApnName(info.getExtraInfo()); state.setAccessPoint(AccessPoint.forName(state.getApnName())); switch (info.getType()) { // WIFI网络 case ConnectivityManager.TYPE_WIFI: { state.setType(NetworkType.WIFI); break; } // 有线网络 case ConnectivityManager.TYPE_ETHERNET: { state.setType(NetworkType.ETHERNET); break; } // 移动网络 case ConnectivityManager.TYPE_MOBILE: case ConnectivityManager.TYPE_MOBILE_MMS: case ConnectivityManager.TYPE_MOBILE_SUPL: case ConnectivityManager.TYPE_MOBILE_DUN: case ConnectivityManager.TYPE_MOBILE_HIPRI: { // 根据速度判定是否是3G网络 state.setType(convertMobileType(info.getSubtype())); break; } // 其他网络 default: state.setType(NetworkType.OTHERS); break; } // 保存额外的信息对象 state.setMoreInfo(info); return state; } private static NetworkType convertMobileType(int subType) { switch (subType) { case NETWORK_TYPE_1xRTT:// ~ 50-100 kbps case NETWORK_TYPE_CDMA:// ~ 14-64 kbps case NETWORK_TYPE_GPRS:// ~ 100 kbps case NETWORK_TYPE_EDGE:// ~ 50-100 kbps case NETWORK_TYPE_IDEN:// ~ 25 kbps case NETWORK_TYPE_UNKNOWN: return NetworkType.MOBILE_2G; case NETWORK_TYPE_EVDO_0:// ~ 400-1000 kbps case NETWORK_TYPE_EVDO_A:// ~ 600-1400 kbps case NETWORK_TYPE_HSDPA:// ~ 2-14 Mbps case NETWORK_TYPE_HSPA:// ~ 700-1700 kbps case NETWORK_TYPE_HSUPA:// ~ 1-23 Mbps case NETWORK_TYPE_UMTS: // ~ 400-7000 kbps case NETWORK_TYPE_EHRPD:// ~ 1-2 Mbps case NETWORK_TYPE_EVDO_B:// ~ 5 Mbps case NETWORK_TYPE_HSPAP:// ~ 10-20 Mbps return NetworkType.MOBILE_3G; case NETWORK_TYPE_LTE:// ~ 10+ Mbps return NetworkType.MOBILE_4G; default: return NetworkType.OTHERS; } } /** * 判断子类型是否是快速网络,姑且认为快速网络即为3G网络 * * @param type 网络子类型 * @return 3G网络,返回true; 2G网络或者未知网络,返回false */ @Deprecated private static boolean is3GMobileType(int type) { NetworkType t = convertMobileType(type); return (t == NetworkType.MOBILE_3G) || (t == NetworkType.MOBILE_4G); } @Override public boolean equals(Object o) { if (o == this) { return true; } return o instanceof NetworkState && (((NetworkState) o).isConnected() == this.isConnected()) // && (((NetworkState) o).getType().equals(this.getType())) // && (((NetworkState) o).getApnName().equals(this.getApnName())); } public boolean isConnected() { return connected; } public void setConnected(boolean connected) { this.connected = connected; } public boolean isAvailable() { return connected; } public String getApnName() { if (apnName == null) { return StringUtils.EMPTY; } else { return apnName; } } public void setApnName(String apnName) { this.apnName = apnName; } public NetworkType getType() { return type; } public void setType(NetworkType type) { this.type = type; } public AccessPoint getAccessPoint() { return accessPoint; } public void setAccessPoint(AccessPoint accessPoint) { this.accessPoint = accessPoint; } public NetworkInfo getMoreInfo() { return moreInfo; } public void setMoreInfo(NetworkInfo moreInfo) { this.moreInfo = moreInfo; } @Override public String toString() { return "NetworkState [connected=" + connected + ", apnName=" + apnName + ", type=" + type + ", accessPoint=" + accessPoint + "]"; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/network/NetworkStateListener.java ================================================ package com.wkw.common_lib.network; /** * Created by wukewei on 16/7/25. */ public interface NetworkStateListener { /** * 当网络状态变化时,触发该事件
*
* 该事件将在主线程中执行,不要执行耗时或阻塞操作,以免引发ANR * * @param lastState 之前的网络状态 * @param newState 现在的网络状态 */ void onNetworkStateChanged(NetworkState lastState, NetworkState newState); } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/network/NetworkType.java ================================================ package com.wkw.common_lib.network; /** * Created by wukewei on 16/7/25. */ public enum NetworkType { /** * 无网络,网络不可用 */ NONE("NONE", false), /** * Wifi网络 */ WIFI("WIFI", true), /** * 2G网络 / 低速移动网络 */ MOBILE_2G("2G", true), /** * 3G网络 / 高速移动网络 */ MOBILE_3G("3G", true), /** * 4G网络 / 超高速移动网络(Yeah!) */ MOBILE_4G("4G", true), /** * 有线网路 */ ETHERNET("ETHERNET", true), /** * 其他网络,含蓝牙、WIFI P2P等 */ OTHERS("UNKNOWN", true),; private String name; private boolean available; NetworkType(String friendlyName, boolean available) { setName(friendlyName); setAvailable(available); } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/network/ServiceProvider.java ================================================ package com.wkw.common_lib.network; import java.util.HashMap; import java.util.Map; /** * Created by wukewei on 16/7/25. */ public enum ServiceProvider { /** * 运营商不可用,非移动网络或无网络 */ NONE("N/A"), /** * 未知运营商,通常在未知接入点时 */ NEVER_HEARD("Unknown"), /** * 中国移动 China Mobile */ CHINA_MOBILE("China Mobile"), /** * 中国联通 China Unicom */ CHINA_UNICOM("China Unicom"), /** * 中国电信 China Telecom */ CHINA_TELECOM("China Telecom"),; private static final Map IMSI_PROVIDER_MAP = new HashMap(); static { // 中国移动 IMSI_PROVIDER_MAP.put("46000", CHINA_MOBILE); IMSI_PROVIDER_MAP.put("46002", CHINA_MOBILE); IMSI_PROVIDER_MAP.put("46007", CHINA_MOBILE); // 中国电信 IMSI_PROVIDER_MAP.put("46003", CHINA_TELECOM); IMSI_PROVIDER_MAP.put("46005", CHINA_TELECOM); // 中国联通 IMSI_PROVIDER_MAP.put("46001", CHINA_UNICOM); IMSI_PROVIDER_MAP.put("46006", CHINA_UNICOM); // 中国铁通,算作移动 IMSI_PROVIDER_MAP.put("46020", CHINA_MOBILE); } private String name; ServiceProvider(String name) { setName(name); } /** * 根据IMSI中的MNC和MCC记录,计算运营商 * * @return 运营商 */ public static ServiceProvider fromIMSI(String IMSI) { if (IMSI == null) { return ServiceProvider.NONE; } if (IMSI.length() < 5) { return ServiceProvider.NONE; } ServiceProvider provider = IMSI_PROVIDER_MAP.get(IMSI.substring(0, 5)); if (provider != null) { return provider; } else { return ServiceProvider.NEVER_HEARD; } } public String getName() { return name; } private void setName(String name) { this.name = name; } @Override public String toString() { return getName(); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/network/WifiDash.java ================================================ package com.wkw.common_lib.network; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import com.wkw.common_lib.Ext; import com.wkw.common_lib.utils.StringUtils; /** * Created by wukewei on 16/7/25. */ public class WifiDash { /** * 获得当前接入点的BSSID
*
* BSSID可以作为WIFI接入点的唯一标识 * * @return 形如MAC地址的字符串,{@code XX:XX:XX:XX:XX:XX} * @see android.net.wifi.WifiInfo */ public static String getBSSID() { WifiManager wifiManager = (WifiManager) Ext.getContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager == null) { return null; } WifiInfo wifiInfo = null; try { wifiInfo = wifiManager.getConnectionInfo(); } catch (Exception e) { wifiInfo = null; } if (wifiInfo == null) { return null; } String bssid = wifiInfo.getBSSID(); if (StringUtils.NOT_AVAILABLE.equals(bssid) || "00:00:00:00:00:00".equals(bssid) || "FF:FF:FF:FF:FF:FF".equalsIgnoreCase(bssid)) { return null; } else { return bssid; } } public static String getSSID() { WifiManager wifiManager = (WifiManager) Ext.getContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager == null) { return null; } WifiInfo wifiInfo = null; try { wifiInfo = wifiManager.getConnectionInfo(); } catch (Exception e) { wifiInfo = null; } if (wifiInfo == null) { return null; } return wifiInfo.getSSID(); } public static int getNetworkId() { WifiManager wifiManager = (WifiManager) Ext.getContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager == null) { return -1; } WifiInfo wifiInfo = null; try { wifiInfo = wifiManager.getConnectionInfo(); } catch (Exception e) { wifiInfo = null; } if (wifiInfo == null) { return -1; } return wifiInfo.getNetworkId(); } public static int getSignalLevel() { Object wifiInfo = queryWifiInfo(StringUtils.NOT_AVAILABLE); if (wifiInfo == StringUtils.NOT_AVAILABLE) { return -1; } return WifiManager.calculateSignalLevel(((WifiInfo) wifiInfo).getRssi(), 5); } private static Object queryWifiInfo(Object defValue) { WifiManager wifiManager = (WifiManager) Ext.getContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager == null) { return defValue; } WifiInfo wifiInfo = null; try { wifiInfo = wifiManager.getConnectionInfo(); } catch (Exception e) { wifiInfo = null; } if (wifiInfo == null) { return defValue; } return wifiInfo; } public static String getWifiInfo() { WifiManager wifiManager = (WifiManager) Ext.getContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager == null) { return "[-]"; } WifiInfo wifiInfo = null; try { wifiInfo = wifiManager.getConnectionInfo(); } catch (Exception e) { wifiInfo = null; } if (wifiInfo == null) { return "[-]"; } String ssid = wifiInfo.getSSID(); String signal = String.valueOf(WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5)); String speed = String.valueOf(wifiInfo.getLinkSpeed()) + " " + WifiInfo.LINK_SPEED_UNITS; String bssid = wifiInfo.getBSSID(); StringBuffer buffer = new StringBuffer(); buffer.append('[').append(signal).append(", ").append(ssid).append(", ").append(speed).append(", ") .append(bssid).append(']'); return buffer.toString(); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/ApiResponse.java ================================================ package com.wkw.common_lib.rx; /** * Created by wukewei on 16/5/26. */ public class ApiResponse { public static final int SUCCESS_CODE = 0; private int showapi_res_code; private String showapi_res_error; private T showapi_res_body; public int getShowapi_res_code() { return showapi_res_code; } public void setShowapi_res_code(int showapi_res_code) { this.showapi_res_code = showapi_res_code; } public String getShowapi_res_error() { return showapi_res_error; } public void setShowapi_res_error(String showapi_res_error) { this.showapi_res_error = showapi_res_error; } public T getNewsList() { return showapi_res_body; } public void setNewsList(T newsList) { this.showapi_res_body = newsList; } public boolean isSuccess() { if (this.showapi_res_code == SUCCESS_CODE) { return true; } else { return false; } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/ProgressSubscriber.java ================================================ package com.wkw.common_lib.rx; import android.app.ProgressDialog; import android.content.Context; import com.wkw.common_lib.rx.error.DefaultErrorBundle; import com.wkw.common_lib.rx.error.ErrorHanding; import com.wkw.common_lib.utils.DialogUtil; import rx.Subscriber; /** * Created by wukewei on 16/8/17. */ public abstract class ProgressSubscriber extends Subscriber { private ProgressDialog mProgressDialog; public ProgressSubscriber(Context context, String message) { mProgressDialog = DialogUtil.getWaitDialog(context, message); } @Override public void onStart() { super.onStart(); showProgress(); } @Override public void onCompleted() { dismissProgress(); } @Override public void onNext(T t) { _noNext(t); } @Override public void onError(Throwable e) { dismissProgress(); _onError(ErrorHanding.handleError(new DefaultErrorBundle((Exception) e))); } private void showProgress() { if (mProgressDialog != null) { mProgressDialog.show(); } } private void dismissProgress() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } public abstract void _noNext(T t); public abstract void _onError(String msg); } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/RxBus.java ================================================ package com.wkw.common_lib.rx; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; /** * Created by wukewei on 16/7/12. * http://www.jianshu.com/p/ca090f6e2fe2 */ public class RxBus { private static volatile RxBus defaultInstance; /* 主题 */ private final Subject bus; // PublishSubject只会把在订阅发生的时间点之后来自原始Observable的数据发射给观察者 public RxBus() { bus = new SerializedSubject<>(PublishSubject.create()); } // 单例RxBus public static RxBus getDefault() { RxBus rxBus = defaultInstance; if (defaultInstance == null) { synchronized (RxBus.class) { rxBus = defaultInstance; if (defaultInstance == null) { rxBus = new RxBus(); defaultInstance = rxBus; } } } return rxBus; } // 提供了一个新的事件 public void post (Object o) { bus.onNext(o); } // 根据传递的 eventType 类型返回特定类型(eventType)的 被观察者 public Observable toObserverable (Class eventType) { return bus.ofType(eventType); // 这里感谢小鄧子的提醒: ofType = filter + cast // return bus.filter(new Func1() { // @Override // public Boolean call(Object o) { // return eventType.isInstance(o); // } // }) .cast(eventType); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/RxResultHelper.java ================================================ package com.wkw.common_lib.rx; import com.wkw.common_lib.rx.error.NetworkConnectionException; import com.wkw.common_lib.rx.error.ServerException; import rx.Observable; import rx.Subscriber; import rx.functions.Func1; /** * Created by wukewei on 16/5/26. */ public class RxResultHelper { public static Observable.Transformer, T> handleResult() { return new Observable.Transformer, T>() { @Override public Observable call(Observable> apiResponseObservable) { return apiResponseObservable.flatMap( new Func1, Observable>() { @Override public Observable call(ApiResponse tApiResponse) { if (tApiResponse == null) { return Observable.error(new NetworkConnectionException()); } else if (tApiResponse.isSuccess()) { return createData(tApiResponse.getNewsList()); } else { return Observable.error(new ServerException(tApiResponse.getShowapi_res_code(),tApiResponse.getShowapi_res_error())); } } } ); } }; } public static Observable createData(final T t) { return Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { try { subscriber.onNext(t); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } } }); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/RxSubscriber.java ================================================ package com.wkw.common_lib.rx; import com.wkw.common_lib.rx.error.DefaultErrorBundle; import com.wkw.common_lib.rx.error.ErrorHanding; import rx.Subscriber; /** * Created by wukewei on 16/8/17. */ public abstract class RxSubscriber extends Subscriber { @Override public void onCompleted() { } @Override public void onNext(T t) { _noNext(t); } @Override public void onError(Throwable e) { _onError(ErrorHanding.handleError(new DefaultErrorBundle((Exception) e))); } public abstract void _noNext(T t); public abstract void _onError(String msg); } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/SchedulersCompat.java ================================================ package com.wkw.common_lib.rx; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by wukewei on 16/5/26. */ public class SchedulersCompat { private final static Observable.Transformer ioTransformer = new Observable.Transformer() { @Override public Object call(Object o) { return ((Observable)o).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); } }; public static Observable.Transformer applyIoSchedulers() { return (Observable.Transformer) ioTransformer; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/error/DefaultErrorBundle.java ================================================ package com.wkw.common_lib.rx.error; /** * Created by wukewei on 16/8/17. */ public class DefaultErrorBundle implements ErrorBundle { private static final String DEFAULT_ERROR_MSG = "Unknown error"; private final Exception exception; public DefaultErrorBundle(Exception exception) { this.exception = exception; } @Override public Exception getException() { return exception; } @Override public String getErrorMessage() { return (exception != null) ? this.exception.getMessage() : DEFAULT_ERROR_MSG; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/error/ErrorBundle.java ================================================ package com.wkw.common_lib.rx.error; /** * Created by wukewei on 16/8/17. */ public interface ErrorBundle { Exception getException(); String getErrorMessage(); } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/error/ErrorHanding.java ================================================ package com.wkw.common_lib.rx.error; import com.wkw.common_lib.Ext; import java.net.ConnectException; import java.net.SocketTimeoutException; /** * Created by wukewei on 16/6/1. */ public class ErrorHanding { public ErrorHanding() { } public static String handleError(ErrorBundle e) { e.getException().printStackTrace(); String message; Exception exception = e.getException(); if (!Ext.g().isAvailable()) { message = "网络中断,请检查您的网络状态"; } else if (exception instanceof SocketTimeoutException) { message = "网络中断,请检查您的网络状态"; } else if (exception instanceof ConnectException) { message = "网络中断,请检查您的网络状态"; } else if (exception instanceof NetworkConnectionException) { message = "网络中断,请检查您的网络状态"; } else if (exception instanceof ServerException) { int code = ((ServerException) exception).getCode(); //在这里你可以获取code来判断是什么类型 好比有些token失效了你就可以实现跳转到登录页面 message = e.getErrorMessage(); } else { message = "连接服务器失败,请稍后再试"; } return message; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/error/NetworkConnectionException.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wkw.common_lib.rx.error; /** * Exception throw by the application when a there is a * network connection exception. */ public class NetworkConnectionException extends Exception { public NetworkConnectionException() { super(); } public NetworkConnectionException(final String message) { super(message); } public NetworkConnectionException(final String message, final Throwable cause) { super(message, cause); } public NetworkConnectionException(final Throwable cause) { super(cause); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/rx/error/ServerException.java ================================================ package com.wkw.common_lib.rx.error; /** * Created by wukewei on 16/5/30. */ public class ServerException extends Exception { private int mCode; public ServerException(int code,String msg) { super(msg); this.mCode = code; } /*** * 这里可以获取code来判断具体是什么错误 * @param * @param * @return */ public int getCode() { return mCode; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/sp/Once.java ================================================ package com.wkw.common_lib.sp; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Date; import java.util.concurrent.TimeUnit; /** * Created by wukewei on 16/7/24. */ @TargetApi(Build.VERSION_CODES.GINGERBREAD) public class Once { public static final int THIS_APP_INSTALL = 0; public static final int THIS_APP_VERSION = 1; private static long lastAppUpdatedTime = -1; private static PersistedMap tagLastSeenMap; private Once() { } /** * 初始化Once * * @param context Application context */ public static void init(Context context) { if (tagLastSeenMap == null) { tagLastSeenMap = new PersistedMap(context, "TagLastSeenMap"); } PackageManager packageManager = context.getPackageManager(); try { PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); lastAppUpdatedTime = packageInfo.lastUpdateTime; } catch (PackageManager.NameNotFoundException ignored) { } } /** * 检查在给定scope内对应tag是否被标记过. * * @param scope 检查范围, {@code THIS_APP_INSTALL} 或 {@code THIS_APP_VERSION}. * @param tag 唯一性标识该操作的字符串. * @return {@code true} 如果和 {@code tag} 关联的操作在给定 {@code scope} 被标记过. */ public static boolean beenDone(@Scope int scope, String tag) { Long tagLastSeenDate = tagLastSeenMap.get(tag); if (tagLastSeenDate == null) { return false; } if (scope == THIS_APP_INSTALL) { return true; } return tagLastSeenDate > lastAppUpdatedTime; } /** * 检查某个tag是否在给定时间范围(如最近1小时)被标记过,如Once.beenDone(TimeUnit.HOURS, 1, "a") * * @param timeUnit 时间单位, 如@code TimeUnit.HOURS. * @param amount 时间单位的数量. * @param tag 唯一性标识该操作的字符串. * @return {@code true} 如果和 {@code tag} 关联的操作在给定最近时间段被标记过. */ public static boolean beenDone(TimeUnit timeUnit, long amount, String tag) { long timeInMillis = timeUnit.toMillis(amount); return beenDone(timeInMillis, tag); } /** * 检查某个tag是否在给定最近时间段内被标记过 * * @param timeSpanInMillis 最近时间,毫秒单位(millisecond). * @param tag 唯一性标识该操作的字符串. * @return {@code true} 如果和 {@code tag} 关联的操作在最近X毫秒内被标记过. */ public static boolean beenDone(long timeSpanInMillis, String tag) { Long timeTagSeen = tagLastSeenMap.get(tag); if (timeTagSeen == null) { return false; } long sinceSinceCheckTime = new Date().getTime() - timeSpanInMillis; return timeTagSeen > sinceSinceCheckTime; } /** * 标记某个tag为done. * * @param tag 唯一性标识该操作的字符串. */ public static void markDone(String tag) { tagLastSeenMap.put(tag, new Date().getTime()); } /** * 清掉给定tag的记录. 所有对该tag的{@link #beenDone}操作在再次标记前都会返回true. * * @param tag 唯一性标识该操作的字符串. */ public static void clearDone(String tag) { tagLastSeenMap.remove(tag); } /** * 清掉所有tag的记录. 所有{@link #beenDone}操作在再次标记前都会返回true. */ public static void clearAll() { tagLastSeenMap.clear(); } @Retention(RetentionPolicy.SOURCE) @IntDef({THIS_APP_INSTALL, THIS_APP_VERSION}) public @interface Scope { } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/sp/PersistedMap.java ================================================ package com.wkw.common_lib.sp; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Created by wukewei on 16/7/24. */ @TargetApi(Build.VERSION_CODES.GINGERBREAD) class PersistedMap { private static final long KEY_NOT_FOUND_VALUE = -1; private final SharedPreferences preferences; private Map map = new ConcurrentHashMap<>(); public PersistedMap(Context context, String mapName) { preferences = context.getSharedPreferences(PersistedMap.class.getSimpleName() + mapName, Context.MODE_PRIVATE); Map allPreferences = preferences.getAll(); for (String key : allPreferences.keySet()) { long value = preferences.getLong(key, KEY_NOT_FOUND_VALUE); if (value != KEY_NOT_FOUND_VALUE) { map.put(key, value); } } } public Long get(String tag) { return map.get(tag); } public void put(String tag, long timeSeen) { map.put(tag, timeSeen); SharedPreferences.Editor edit = preferences.edit(); edit.putLong(tag, timeSeen); edit.apply(); } public void remove(String tag) { map.remove(tag); SharedPreferences.Editor edit = preferences.edit(); edit.remove(tag); edit.apply(); } public void clear() { map.clear(); SharedPreferences.Editor edit = preferences.edit(); edit.clear(); edit.apply(); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/AndroidUtils.java ================================================ package com.wkw.common_lib.utils; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.wkw.common_lib.R; /** * Created by wukewei on 16/7/26. */ public class AndroidUtils { public static void copyToClipBoard(Context context, String text) { ClipData clipData = ClipData.newPlainText("common_copy", text); ClipboardManager manager = (ClipboardManager) context.getSystemService( Context.CLIPBOARD_SERVICE); manager.setPrimaryClip(clipData); ToashUtils.show(context, context.getString(R.string.copy_done)); } public static void openBrowser(Context context, String url) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); Uri uri = Uri.parse(url); intent.setData(uri); if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(intent); } else { ToashUtils.show(context, context.getString(R.string.open_failure)); } } /** * 调用系统安装了的应用分享 * * @param context * @param title * @param url */ public static void showSystemShareOption(Activity context, final String title, final String url) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, "分享:" + title); intent.putExtra(Intent.EXTRA_TEXT, title + " " + url); context.startActivity(Intent.createChooser(intent, "选择分享")); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/AppManager.java ================================================ package com.wkw.common_lib.utils; import android.app.Activity; import java.util.Stack; /** * Created by wukewei on 16/7/26. */ public class AppManager { private static Stack activityStack; private static AppManager mInstance; private AppManager() {} public static AppManager getAppManager() { if (mInstance == null) { synchronized (AppManager.class) { if (mInstance == null) { mInstance = new AppManager(); } } } return mInstance; } public void addActivity(Activity activity) { if (activityStack == null) { activityStack = new Stack<>(); } activityStack.add(activity); } public void removeActivity(Activity activity) { if (activity != null && activityStack.contains(activity)) { activityStack.remove(activity); } } public Activity curremtActivity() { Activity activity = activityStack.lastElement(); return activity; } public void finishActivity(Activity activity) { if (activity != null && activityStack.contains(activity) && !activity.isFinishing()) { activityStack.remove(activity); activity.finish(); } } public void finishAllActivity() { for (int i= 0, size = activityStack.size(); i < size; i++) { if (null != activityStack.get(i)) { activityStack.get(i).finish(); } } activityStack.clear(); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/AppUtils.java ================================================ package com.wkw.common_lib.utils; import android.app.ActivityManager; import android.app.KeyguardManager; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.text.TextUtils; import java.util.List; /** * Created by wukewei on 16/7/25. */ public final class AppUtils { private static Bundle sOwnAppMetaInfo; private AppUtils() { // static usage. } public static boolean isForeground(Context context) { if (isScreenLocked(context)) { return false; } ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List a = mActivityManager.getRunningTasks(1); return context.getPackageName().equals(a.get(0).baseActivity.getPackageName()) && context.getPackageName().equals(a.get(0).topActivity.getPackageName()); } private static boolean isScreenLocked(Context context) { KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); return mKeyguardManager.inKeyguardRestrictedInputMode(); } public static int getVersionCode(Context context) { if (context == null) { return 0; } try { PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return info.versionCode; } catch (Throwable e) { return 0; } } /** * 获取带有指定配置信息的ApplicationInfo * * @param flags 比如 {@link android.content.pm.PackageManager#GET_META_DATA} * @see #getSimpleAppInfo(android.content.Context) * @see why this method */ public static ApplicationInfo getAppInfoWithFlags(Context ctx, int flags) { try { return ctx == null ? null : ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } /** * 获取基本的applicationInfo * * @see #getAppInfoWithFlags(android.content.Context, int) */ public static ApplicationInfo getSimpleAppInfo(Context ctx) { return ctx == null ? null : ctx.getApplicationInfo(); } /** * Check whether corresponding package is installed. * * @param context Application context. * @param packageName Package name. * @return Whether corresponding package is installed. */ public static boolean isPackageInstalled(Context context, String packageName) { if (!TextUtils.isEmpty(packageName)) { try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0); return packageInfo != null; } catch (PackageManager.NameNotFoundException e) { // ignore. } } return false; } /** * Get application info of own package. * * @param context Application context. * @return Application info of own package. */ public static Bundle getApplicationMetaInfo(Context context) { if (sOwnAppMetaInfo == null) { synchronized (AppUtils.class) { if (sOwnAppMetaInfo == null) { sOwnAppMetaInfo = getApplicationMetaInfo(context, context.getPackageName()); } } } return sOwnAppMetaInfo != null ? new Bundle(sOwnAppMetaInfo) : null; } /** * Get application meta info of corresponding package. * * @param context Application context. * @param packageName Package name. * @return Application meta info of corresponding package. */ public static Bundle getApplicationMetaInfo(Context context, String packageName) { ApplicationInfo appInfo = packageName.equals(context.getPackageName()) ? context.getApplicationInfo() : null; Bundle metaInfo = appInfo != null ? appInfo.metaData : null; if (metaInfo == null) { try { appInfo = context.getPackageManager().getApplicationInfo( packageName, PackageManager.GET_META_DATA); metaInfo = appInfo.metaData; } catch (Throwable e) { // ignore. } } return metaInfo; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/DialogUtil.java ================================================ package com.wkw.common_lib.utils; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.text.Html; import android.text.TextUtils; /** * Created by wukewei on 16/8/17. */ public class DialogUtil { /*** * 获取一个dialog * @param context * @param * @return */ public static AlertDialog.Builder getDialog(Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); return builder; } public static ProgressDialog getWaitDialog(Context context, String message) { ProgressDialog waitDialog = new ProgressDialog(context); if (!TextUtils.isEmpty(message)) { waitDialog.setMessage(message); } return waitDialog; } /*** * 获取一个信息对话框,注意需要自己手动调用show方法显示 * @param context * @param message * @param onClickListener * @return */ public static AlertDialog.Builder getMessageDialog(Context context, String message, DialogInterface.OnClickListener onClickListener) { AlertDialog.Builder builder = getDialog(context); builder.setMessage(message); builder.setPositiveButton("确定", onClickListener); return builder; } public static AlertDialog.Builder getMessageDialog(Context context, String message) { return getMessageDialog(context, message, null); } public static AlertDialog.Builder getConfirmDialog(Context context, String message, DialogInterface.OnClickListener onClickListener) { AlertDialog.Builder builder = getDialog(context); builder.setMessage(Html.fromHtml(message)); builder.setPositiveButton("确定", onClickListener); builder.setNegativeButton("取消", null); return builder; } public static AlertDialog.Builder getConfirmDialog(Context context, String message, DialogInterface.OnClickListener onOkClickListener, DialogInterface.OnClickListener onCancleClickListener) { AlertDialog.Builder builder = getDialog(context); builder.setMessage(message); builder.setPositiveButton("确定", onOkClickListener); builder.setNegativeButton("取消", onCancleClickListener); return builder; } public static AlertDialog.Builder getConfirmDialog(Context context, String message, String okString, String cancleString, DialogInterface.OnClickListener onOkClickListener, DialogInterface.OnClickListener onCancleClickListener) { return getConfirmDialog(context, "", message, okString, cancleString, onOkClickListener, onCancleClickListener); } public static AlertDialog.Builder getConfirmDialog(Context context, String title, String message, String okString, String cancleString, DialogInterface.OnClickListener onOkClickListener, DialogInterface.OnClickListener onCancleClickListener) { AlertDialog.Builder builder = getDialog(context); if (!TextUtils.isEmpty(title)) { builder.setTitle(title); } builder.setMessage(message); builder.setPositiveButton(okString, onOkClickListener); builder.setNegativeButton(cancleString, onCancleClickListener); return builder; } public static AlertDialog.Builder getSelectDialog(Context context, String title, String[] arrays, DialogInterface.OnClickListener onClickListener) { AlertDialog.Builder builder = getDialog(context); builder.setItems(arrays, onClickListener); if (!TextUtils.isEmpty(title)) { builder.setTitle(title); } builder.setPositiveButton("取消", null); return builder; } public static AlertDialog.Builder getSelectDialog(Context context, String[] arrays, DialogInterface.OnClickListener onClickListener) { return getSelectDialog(context, "", arrays, onClickListener); } public static AlertDialog.Builder getSingleChoiceDialog(Context context, String title, String[] arrays, int selectIndex, DialogInterface.OnClickListener onClickListener) { AlertDialog.Builder builder = getDialog(context); builder.setSingleChoiceItems(arrays, selectIndex, onClickListener); if (!TextUtils.isEmpty(title)) { builder.setTitle(title); } builder.setNegativeButton("取消", null); return builder; } public static AlertDialog.Builder getSingleChoiceDialog(Context context, String[] arrays, int selectIndex, DialogInterface.OnClickListener onClickListener) { return getSingleChoiceDialog(context, "", arrays, selectIndex, onClickListener); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/HtmlUtils.java ================================================ package com.wkw.common_lib.utils; import java.util.regex.Pattern; /** * Created by wukewei on 16/7/25. */ public final class HtmlUtils { /** * 过滤html */ public static String filterHtml(String inputString) { String htmlStr = inputString; // 含html标签的字符串 String textStr = ""; Pattern p_script; java.util.regex.Matcher m_script; Pattern p_html; java.util.regex.Matcher m_html; try { String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 String regEx_script = "<[/s]*?script[^>]*?>[/s/S]*?<[/s]*?//[/s]*?script[/s]*?>"; // 定义script的正则表达式{或]*?>[/s/S]*? p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // 过滤html标签 textStr = htmlStr; } catch (Exception e) { System.err.println("Html2Text: " + e.getMessage()); } return textStr;// 返回文本字符串 } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/NetWorkUtils.java ================================================ package com.wkw.common_lib.utils; import android.content.Context; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.DhcpInfo; import android.net.NetworkInfo; import android.net.Proxy; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.Build; import android.support.annotation.RequiresPermission; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import com.wkw.common_lib.Ext; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; import java.util.HashMap; /** * Created by wukewei on 16/7/25. */ public final class NetWorkUtils { // ------------------ common ------------------- public final static int NETWORK_TYPE_NONE = -1; public final static int NETWORK_TYPE_UNKNOWN = 1; public final static int NETWORK_TYPE_UNKNOWN_MOBILE = 2; public final static int NETWORK_TYPE_2G = 3; public final static int NETWORK_TYPE_3G = 4; public final static int NETWORK_TYPE_4G = 5; public final static int NETWORK_TYPE_WIFI = 10; /** * WIFI的APN名字.. */ public final static String APN_NAME_WIFI = "wifi"; private final static String TAG = "NetworkUtil"; private final static Uri PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn"); private final static HashMap sAPNProxies = new HashMap(); static { sAPNProxies.put("cmwap", new NetworkProxy("10.0.0.172", 80)); sAPNProxies.put("3gwap", new NetworkProxy("10.0.0.172", 80)); sAPNProxies.put("uniwap", new NetworkProxy("10.0.0.172", 80)); sAPNProxies.put("ctwap", new NetworkProxy("10.0.0.200", 80)); } /** * 检查当前网络是否连接 */ public static boolean isNetworkConnected() { return isNetworkConnected(Ext.getContext()); } /** * 检查当前网络是否连接 * * @param context Application context. * @return 当前网络是否连接 */ public static boolean isNetworkConnected(Context context) { NetworkInfo info = getActiveNetworkInfo(context); return info != null && info.isConnected(); } public static boolean isWifiConnected() { return isWifiConnected(Ext.getContext()); } /** * 检查当前Wifi网络是否连接 * * @param context Application context. * @return Whether wifi network is connected. */ public static boolean isWifiConnected(Context context) { if (context == null) { return false; } NetworkInfo activeNetworkInfo = getActiveNetworkInfo(context); return activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI; } /** * 检查当前移动网络是否连接 * * @param context Application context. * @return Whether mobile network is connected. */ public static boolean isMobileConnected(Context context) { if (context == null) { return false; } NetworkInfo activeNetworkInfo = getActiveNetworkInfo(context); return activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE; } /** * Returns details about the currently active default data network. When * connected, this network is the default route for outgoing connections. * You should always check {@link NetworkInfo#isConnected()} before initiating * network traffic. This may return {@code null} when there is no default * network. * * @param context Application context. * @return a {@link NetworkInfo} object for the current default network * or {@code null} if no network default network is currently active *

*

This method requires the call to hold the permission * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}. */ public static NetworkInfo getActiveNetworkInfo(Context context) { try { ConnectivityManager connMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); return connMgr.getActiveNetworkInfo(); } catch (Throwable e) { Log.e(TAG, "fail to get active network info", e); return null; } } /** * 返回当前活动网络的类型. * * @param context Application context. * @return type of current active network, the alternation is {@link #NETWORK_TYPE_WIFI}, {@link #NETWORK_TYPE_4G}, * {@link #NETWORK_TYPE_3G}, {@link #NETWORK_TYPE_2G}, {@link #NETWORK_TYPE_UNKNOWN_MOBILE}, {@link #NETWORK_TYPE_UNKNOWN}, * {@link #NETWORK_TYPE_NONE}. */ public static int getActiveNetworkType(Context context) { return getNetworkType(context, getActiveNetworkInfo(context)); } /** * Returns type of corresponding network info. * * @param context Application context. * @param info Network info. * @return type of current active network, the alternation is {@link #NETWORK_TYPE_WIFI}, {@link #NETWORK_TYPE_4G}, * {@link #NETWORK_TYPE_3G}, {@link #NETWORK_TYPE_2G}, {@link #NETWORK_TYPE_UNKNOWN_MOBILE}, {@link #NETWORK_TYPE_UNKNOWN}, * {@link #NETWORK_TYPE_NONE}. */ public static int getNetworkType(Context context, NetworkInfo info) { if (info != null) { if (info.getType() == ConnectivityManager.TYPE_WIFI) { return NETWORK_TYPE_WIFI; } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) { int subType = info.getSubtype(); switch (subType) { // 2G case TelephonyManager.NETWORK_TYPE_EDGE: // ~25 kbps case TelephonyManager.NETWORK_TYPE_GPRS: // GPRS (2.5G) case TelephonyManager.NETWORK_TYPE_CDMA: // CDMA: Either IS95A or IS95B (2G) case TelephonyManager.NETWORK_TYPE_1xRTT: // 1xRTT (2G - Transitional) case TelephonyManager.NETWORK_TYPE_IDEN: // iDen (2G) return NETWORK_TYPE_2G; // 3G case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: // EVDO revision 0 (3G) case TelephonyManager.NETWORK_TYPE_HSPA: // HSPA (3G - Transitional) return NETWORK_TYPE_3G; // 3.5G case TelephonyManager.NETWORK_TYPE_EVDO_A: // EVDO revision A (3G - Transitional) case TelephonyManager.NETWORK_TYPE_EVDO_B: // EVDO revision A (3G - Transitional) case TelephonyManager.NETWORK_TYPE_HSPAP: // HSPA+ (3G - Transitional) case TelephonyManager.NETWORK_TYPE_HSDPA: // HSDPA (3G - Transitional) case TelephonyManager.NETWORK_TYPE_HSUPA: // HSUPA (3G - Transitional) return NETWORK_TYPE_3G; // 4G case TelephonyManager.NETWORK_TYPE_LTE: case TelephonyManager.NETWORK_TYPE_EHRPD: return NETWORK_TYPE_4G; default: return NETWORK_TYPE_UNKNOWN_MOBILE; } } return NETWORK_TYPE_UNKNOWN; } return NETWORK_TYPE_NONE; } /** * 获取网络代理,需要指定是否通过APN去获取. * * @param context Application context. * @param apnProxy Control whether determine the proxy by system interface or by current apn. * @return Current network proxy. */ public static NetworkProxy getProxy(Context context, boolean apnProxy) { return !apnProxy ? getProxy(context) : getProxyByAPN(context); } /** * 通过系统的接口获取网络代理. * * @param context Application context. * @return Current network proxy. */ public static NetworkProxy getProxy(Context context) { if (!isMobileConnected(context)) { return null; } String proxyHost = getProxyHost(context); int proxyPort = getProxyPort(context); if (!isEmpty(proxyHost) && proxyPort >= 0) { return new NetworkProxy(proxyHost, proxyPort); } return null; } @SuppressWarnings("deprecation") private static String getProxyHost(Context context) { String host = null; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { host = Proxy.getDefaultHost(); } else { host = System.getProperty("http.proxyHost"); } return host; } @SuppressWarnings("deprecation") private static int getProxyPort(Context context) { int port = -1; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { port = Proxy.getDefaultPort(); } else { String portStr = System.getProperty("http.proxyPort"); if (!isEmpty(portStr)) { try { port = Integer.parseInt(portStr); } catch (NumberFormatException e) { e.printStackTrace(); } } } if (port < 0 || port > 65535) { // ensure valid port. port = -1; } return port; } /** * 通过APN获取当前网络代理. * * @param context Application context. * @return Current network proxy. */ public static NetworkProxy getProxyByAPN(Context context) { if (!isMobileConnected(context)) { return null; } String apn = getAPN(context); NetworkProxy proxy = sAPNProxies.get(apn); return proxy == null ? null : proxy.copy(); } /** * 获得当前APN. * * @param context Application context. * @return Current apn. If device is connected to wifi, then it will be {@link #APN_NAME_WIFI}. */ public static String getAPN(Context context) { NetworkInfo activeNetInfo = getActiveNetworkInfo(context); if (activeNetInfo == null) { // no active network. return null; } String apn = null; if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { apn = APN_NAME_WIFI; } else if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) { Cursor cursor = null; try { cursor = context.getContentResolver().query(PREFERRED_APN_URI, null, null, null, null); while (cursor != null && cursor.moveToNext()) { apn = cursor.getString(cursor.getColumnIndex("apn")); } } catch (Throwable e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } } if (TextUtils.isEmpty(apn)) { apn = activeNetInfo.getExtraInfo(); } } if (apn != null) { // convert apn to lower case. apn = apn.toLowerCase(); } return apn; } /** * 获得当前DNS. * * @param context Application context. * @return 当前DNS. */ @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE) public static DNS getDNS(Context context) { DNS dns = new DNS(); if (context != null) { if (isWifiConnected(context)) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcpInfo = wifiManager.getDhcpInfo(); if (dhcpInfo != null) { dns.primary = int32ToIPStr(dhcpInfo.dns1); dns.secondary = int32ToIPStr(dhcpInfo.dns2); } } } if (dns.primary == null && dns.secondary == null) { // retrieve dns with property. dns.primary = PropertyUtils.get(PropertyUtils.PROPERTY_DNS_PRIMARY, null); dns.secondary = PropertyUtils.get(PropertyUtils.PROPERTY_DNS_SECONDARY, null); } return dns; } private static String int32ToIPStr(int ip) { StringBuffer buffer = new StringBuffer(); buffer.append(ip & 0xFF).append("."); buffer.append((ip >> 8) & 0xFF).append("."); buffer.append((ip >> 16) & 0xFF).append("."); buffer.append((ip >> 24) & 0xFF); return buffer.toString(); } /** * 获得当前本地IP */ public static String getLocalIP() { try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface ni = en.nextElement(); for (Enumeration enumIpAddr = ni.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (Throwable ex) { // ignore. } return null; } // ---------------- utils ------------------ private static boolean isEmpty(String str) { return str == null || str.length() == 0; } /** * 网络代理定义. */ public static class NetworkProxy implements Cloneable { public final String host; public final int port; NetworkProxy(String host, int port) { this.host = host; this.port = port; } final NetworkProxy copy() { try { return (NetworkProxy) clone(); } catch (CloneNotSupportedException e) { // ignore. } return null; } @Override public String toString() { return host + ":" + port; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj != null && obj instanceof NetworkProxy) { NetworkProxy proxy = (NetworkProxy) obj; if (TextUtils.equals(this.host, proxy.host) && this.port == proxy.port) return true; } return false; } } /** * DNS定义. */ public final static class DNS { public String primary; public String secondary; DNS() { } @Override public String toString() { return primary + "," + secondary; } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/ProcessUtils.java ================================================ package com.wkw.common_lib.utils; import android.app.ActivityManager; import android.content.Context; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Created by wukewei on 16/11/12. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class ProcessUtils { private final static int[] EMPTY_INT_ARRAY = new int[0]; private static volatile String sProcessName; private final static Object sNameLock = new Object(); private static volatile Boolean sMainProcess; private final static Object sMainLock = new Object(); private ProcessUtils() { // static usage. } /** * Returns the name of this process. * * @param context Application context. * @return The name of this process. */ public static String myProcessName(Context context) { if (sProcessName != null) { return sProcessName; } synchronized (sNameLock) { if (sProcessName != null) { return sProcessName; } return sProcessName = obtainProcessName(context); } } /** * Check whether this process is the main process (it's name equals to {@link Context#getPackageName()}). * * @param context Application context. * @return Whether this process is the main process. */ public static boolean isMainProcess(Context context) { if (sMainProcess != null) { return sMainProcess; } synchronized (sMainLock) { if (sMainProcess != null) { return sMainProcess; } final String processName = myProcessName(context); if (processName == null) { return false; } sMainProcess = processName.equals(context.getApplicationInfo().processName); return sMainProcess; } } /** * Kill this process itself. */ public void killSelf() { android.os.Process.killProcess(android.os.Process.myPid()); } /** * Kill all processes related this package. */ public static void killAll(Context context) { killAll(context, EMPTY_INT_ARRAY); } /** * Kill all process related this package. * * @param excludePid exclude pid of processes. */ public static void killAll(Context context, int... excludePid) { int myPid = android.os.Process.myPid(); Collection runningProcess = collectRunningProcessInfo(context); Set excludePidSet = collectUniqueSet(excludePid); // kill running process exclude required exception and self. if (runningProcess != null) { for (ActivityManager.RunningAppProcessInfo process : runningProcess) { if (excludePidSet != null && excludePidSet.contains(process.pid)) { // exclude process. continue; } if (myPid == process.pid) { // my pid, ignore here. continue; } android.os.Process.killProcess(process.pid); } } if (excludePidSet != null && excludePidSet.contains(myPid)) { // exclude self. return; } // kill self at last. android.os.Process.killProcess(myPid); } /** * Kill all process related this package. * * @param excludeName exclude name of processes. */ public static void killAll(Context context, String... excludeName) { int myPid = android.os.Process.myPid(); String myProcessName = null; Collection runningProcess = collectRunningProcessInfo(context); Set excludeNameSet = collectUniqueSet(excludeName); // kill running process exclude required exception and self. if (runningProcess != null) { for (ActivityManager.RunningAppProcessInfo process : runningProcess) { if (excludeNameSet != null && excludeNameSet.contains(process.processName)) { // exclude process. continue; } if (myPid == process.pid) { // my pid, ignore here. myProcessName = process.processName; continue; } android.os.Process.killProcess(process.pid); } } if (myProcessName != null && excludeNameSet != null && excludeNameSet.contains(myProcessName)) { // exclude self. return; } // kill self at last. android.os.Process.killProcess(myPid); } /** * Whether this process is foreground. * * @return true if foreground. */ public static boolean isForeground(Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List runningTasks = am.getRunningTasks(1); if (runningTasks == null || runningTasks.isEmpty()) { return false; } ActivityManager.RunningTaskInfo topTask = runningTasks.get(0); if (topTask == null) { return false; } String myPackageName = context.getPackageName(); return (myPackageName.equals(topTask.baseActivity.getPackageName())) || (myPackageName.equals(topTask.topActivity.getPackageName())); } private static Collection collectRunningProcessInfo(Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); Collection runningProcesses = am.getRunningAppProcesses(); // filter processes according to uid. if (runningProcesses != null) { int uid = android.os.Process.myUid(); Iterator iterator = runningProcesses.iterator(); while (iterator.hasNext()) { ActivityManager.RunningAppProcessInfo process = iterator.next(); if (process == null || process.uid != uid) { iterator.remove(); } } } return runningProcesses; } private static Set collectUniqueSet(V... values) { if (values == null || values.length == 0) { return null; } Set set = new HashSet(values.length); for (V value : values) { set.add(value); } return set; } private static Set collectUniqueSet(int... values) { if (values == null || values.length == 0) { return null; } Set set = new HashSet(values.length); for (int value : values) { set.add(value); } return set; } private static String obtainProcessName(Context context) { final int pid = android.os.Process.myPid(); ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List listTaskInfo = am.getRunningAppProcesses(); if (listTaskInfo != null && listTaskInfo.size() > 0) { for (ActivityManager.RunningAppProcessInfo proc : listTaskInfo) { if (proc != null && proc.pid == pid) { return proc.processName; } } } return null; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/PropertyUtils.java ================================================ package com.wkw.common_lib.utils; import android.text.TextUtils; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; /** * Created by wukewei on 16/7/25. */ public final class PropertyUtils { public final static String PROPERTY_DNS_PRIMARY = "net.dns1"; public final static String PROPERTY_DNS_SECONDARY = "net.dns2"; private final static String TAG = "PropertyUtils"; private final static String CMD_GET_PROP = "getprop"; private static Class sClassSystemProperties; private static Method sMethodGetString; static { try { sClassSystemProperties = Class.forName("android.os.SystemProperties"); sMethodGetString = sClassSystemProperties.getDeclaredMethod("get", String.class, String.class); } catch (Throwable e) { Log.w(TAG, e); } } private PropertyUtils() { // static usage. } /** * Get property of corresponding key. * * @param key Property key. * @param defValue Default value. * @return Property of corresponding key. */ public static String get(String key, String defValue) { if (TextUtils.isEmpty(key)) { return defValue; } String value = getWithReflect(key, null); if (TextUtils.isEmpty(value)) { value = getWithCmd(key, null); } if (TextUtils.isEmpty(value)) { value = defValue; } return value; } /** * Get property of corresponding key quickly (but provide less validity than {@link #get(String, String)}). * * @param key Property key. * @param defValue Default value. * @return Property of corresponding key. */ public static String getQuickly(String key, String defValue) { if (TextUtils.isEmpty(key)) { return defValue; } return getWithReflect(key, defValue); } private static String getWithReflect(String key, String defValue) { if (sClassSystemProperties == null || sMethodGetString == null) { return defValue; } String value = defValue; try { value = (String) sMethodGetString.invoke(sClassSystemProperties, key, defValue); } catch (Throwable e) { Log.w(TAG, e); } return value; } private static String getWithCmd(String key, String defValue) { String value = defValue; try { Process process = Runtime.getRuntime().exec(CMD_GET_PROP + " " + key); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } String readValue = builder.toString(); if (!TextUtils.isEmpty(readValue)) { // if read value is valid, use it. value = readValue; } } catch (IOException e) { // } finally { if (reader != null) { reader.close(); } } // clean job. process.destroy(); } catch (Throwable e) { Log.w(TAG, e); } return value; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/Singleton.java ================================================ package com.wkw.common_lib.utils; /** * Created by wukewei on 16/7/24. */ public abstract class Singleton { private volatile T mInstance; protected abstract T create(P p); public final T get(P p) { if (mInstance == null) { synchronized (this) { if (mInstance == null) { mInstance = create(p); } } } return mInstance; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/StringUtils.java ================================================ package com.wkw.common_lib.utils; import android.text.TextUtils; import android.text.format.Time; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.lang.reflect.Array; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; /** * Created by wukewei on 16/7/25. */ public class StringUtils { /** * 空字符串常量 */ public static final String EMPTY = ""; /** * "不可用"字符串常量 */ public static final String NOT_AVAILABLE = "N/A"; private static final int CACHE_SIZE = 4096; /** * 创建指定格式的时间格式化对象 * * @param pattern 时间格式,形如"yyyy-MM-dd HH-mm-ss.SSS" * @return Format 时间格式化对象 */ public static SimpleDateFormat createDataFormat(String pattern) { return new SimpleDateFormat(pattern); } /** * 将s中字符用delimiter分割连接起来 * * @param delimiter 分隔符 * @param segments 被连接的数据 * @return 返回连接号的字符串 * @see StringUtils#join(String, Object[]) */ public static String join(String delimiter, Collection segments) { StringBuilder stringBuilder = new StringBuilder(); if (segments != null) { appendCollectionObjectToStringBuilder(stringBuilder, delimiter, segments); } String outString = stringBuilder.toString(); if (outString.endsWith(delimiter)) { return outString.substring(0, outString.length() - delimiter.length()); } return outString; } /** * 将对象链接成一个字符串,使用delimiter传入的字符串分割, *

注意:如果前一个片段为字符串且以delimiter结束或者为空(null获取为""),将不会重复添加此字符串

*

字符串末尾不会自动添加delimiter字符串

*

如果没有传入参数,返回一个空字符串

* * @param delimiter 分割字符串 * @param segments 所有传入的部分 * @return 连接完毕后的字符串 */ public static String join(String delimiter, Object... segments) { StringBuilder stringBuilder = new StringBuilder(); if (segments != null) { int size = segments.length; if (size > 0) { for (Object segment : segments) { appendObjectToStringBuilder(stringBuilder, delimiter, segment); } } } String outString = stringBuilder.toString(); if (outString.endsWith(delimiter)) { return outString.substring(0, outString.length() - delimiter.length()); } return outString; } private static void appendArrayObjectToStringBuilder(StringBuilder stringBuilder, String delimiter, Object array) { int length = Array.getLength(array); for (int i = 0; i < length; i++) { appendObjectToStringBuilder(stringBuilder, delimiter, Array.get(array, i)); } } private static void appendCollectionObjectToStringBuilder(StringBuilder stringBuilder, String delimiter, Collection collection) { Iterator iterator = collection.iterator(); while (iterator.hasNext()) { appendObjectToStringBuilder(stringBuilder, delimiter, iterator.next()); } } private static void appendObjectToStringBuilder(StringBuilder stringBuilder, String delimiter, Object object) { if (object == null) { return; } if (object.getClass().isArray()) { appendArrayObjectToStringBuilder(stringBuilder, delimiter, object); } else if (object instanceof Collection) { appendCollectionObjectToStringBuilder(stringBuilder, delimiter, (Collection) object); } else { String objectString = object.toString(); stringBuilder.append(objectString); if (!isEmpty(objectString) && !objectString.endsWith(delimiter)) { stringBuilder.append(delimiter); } } } /** * 测试传入的字符串是否为空 * * @param string 需要测试的字符串 * @return 如果字符串为空(包括不为空但其中为空白字符串的情况)返回true,否则返回false */ public static boolean isEmpty(String string) { return string == null || string.trim().length() == 0; } /** * 测试传入的字符串是否为空 * * @param string 需要测试的字符串 * @return 如果字符串为空(包括不为空但其中为空白字符串的情况)返回false,否则返回true */ public static boolean isNotEmpty(String string) { return string != null && string.trim().length() > 0; } /** * 传入的字符串是否相等 * * @param a a字符串 * @param b b字符串 * @return 如果字符串相等(值比较)返回true,否则返回false */ public static boolean equal(String a, String b) { return a == b || (a != null && b != null && a.length() == b.length() && a.equals(b)); } /** * 将字符串用分隔符分割为long数组 *

只支持10进制的数值转换

*

如果格式错误,将抛出NumberFormatException

* * @param string 字符串 * @param delimiter 分隔符 * @return 分割后的long数组. */ public static long[] splitToLongArray(String string, String delimiter) { List stringList = splitToStringList(string, delimiter); long[] longArray = new long[stringList.size()]; int i = 0; for (String str : stringList) { longArray[i++] = Long.parseLong(str); } return longArray; } /** * 将字符串用分隔符分割为Long列表 *

只支持10进制的数值转换

*

如果格式错误,将抛出NumberFormatException

* * @param string 字符串 * @param delimiter 分隔符 * @return 分割后的Long列表. */ public static List splitToLongList(String string, String delimiter) { List stringList = splitToStringList(string, delimiter); List longList = new ArrayList(stringList.size()); for (String str : stringList) { longList.add(Long.parseLong(str)); } return longList; } /** * 将字符串用分隔符分割为字符串数组 * * @param string 字符串 * @param delimiter 分隔符 * @return 分割后的字符串数组. */ public static String[] splitToStringArray(String string, String delimiter) { List stringList = splitToStringList(string, delimiter); return stringList.toArray(new String[stringList.size()]); } /** * 将字符串用分隔符分割为字符串列表 * * @param string 字符串 * @param delimiter 分隔符 * @return 分割后的字符串数组. */ public static List splitToStringList(String string, String delimiter) { List stringList = new ArrayList(); if (!isEmpty(string)) { int length = string.length(); int pos = 0; do { int end = string.indexOf(delimiter, pos); if (end == -1) { end = length; } stringList.add(string.substring(pos, end)); pos = end + 1; // skip the delimiter } while (pos < length); } return stringList; } /** * InputSteam 转换到 String,会把输入流关闭 * * @param inputStream 输入流 * @return String 如果有异常则返回null */ public static String stringFromInputStream(InputStream inputStream) { try { byte[] readBuffer = new byte[CACHE_SIZE]; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); while (true) { int readLen = inputStream.read(readBuffer, 0, CACHE_SIZE); if (readLen <= 0) { break; } byteArrayOutputStream.write(readBuffer, 0, readLen); } return byteArrayOutputStream.toString("UTF-8"); } catch (Exception e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } return null; } /** * 测试是否为有效的注册电子邮件格式 * * @param string 内容 * @return true if yes */ public static boolean isEmailFormat(String string) { if (StringUtils.isEmpty(string)) { return false; } String emailFormat = "^([a-zA-Z0-9_\\.-]+)@([\\da-zA-Z\\.-]+)\\.([a-zA-Z\\.]{1,16})$"; return Pattern.matches(emailFormat, string); } /** * 测试是否为有效的登录电子邮件格式 * * @param string 内容 * @return true if yes */ public static boolean isLoginEmailFormat(String string) { if (StringUtils.isEmpty(string)) { return false; } String emailFormat = "^\\s*\\w+(?:\\.?[\\w-]+\\.?)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"; return Pattern.matches(emailFormat, string); } /** * 是否在长度范围之类 * * @param string 内容 * @param begin 最小长度(inclusive) * @param end 最大长度(inclusive) * @return 字符串长度在begin和end之内返回true,否则返回false。

输入字符串为null时,返回false

*/ public static boolean lengthInRange(String string, int begin, int end) { return string != null && string.length() >= begin && string.length() <= end; } /** * 去除文件名中的无效字符 * * @param srcStr srcStr * @return 去除文件名后的字符 */ public static String validateFilePath(String srcStr) { return StringUtils.isEmpty(srcStr) ? srcStr : srcStr.replaceAll("[\\\\/:\"*?<>|]+", "_"); } /** * 获取字串字符长度,规则如下: * 中文一个字长度为2,英文、字符长度为1 * 如:"我c"长度为3 * * @param str str * @return 字符串长度 */ public static int getCharsLength(String str) { int length = 0; try { if (str == null) { return 0; } str = str.replaceAll("[^\\x00-\\xff]", "**"); length += str.length(); } catch (Exception e) { e.printStackTrace(); } return length; } /** * 获取字串的文字个数,规则如下: * 汉字为1,英文、字符算0.5个字 * 如:"我"字数为1,"我k"字数为2,"我ko"字数也为2 * * @param str str * @return 字符串长度 */ public static int getWordCount(String str) { int length = getCharsLength(str); return length % 2 + length / 2; } /** * 得到毫秒数对应的时间串, 格式 "2013-07-04 12:44:53.098"
*
* 这个方法使用Android的Time类实现,用以替代java.util.Calender
* 使用同余计算毫秒数,在某些ROM上,JDK被替换的算法不能计算毫秒数 (e.g. 华为荣耀) * * @param time 毫秒数 * @return 时间字符串 */ public static String getTimeStr(long time) { long ms = time % 1000; Time timeObj = new Time(); timeObj.set(time); StringBuilder builder = new StringBuilder(); builder.append(timeObj.format("%Y-%m-%d %H:%M:%S")).append('.'); if (ms < 10) { builder.append("00"); } else if (ms < 100) { builder.append('0'); } builder.append(ms); return builder.toString(); } /** * 比较两个字符串,是否prefix字符串是source字符串的前缀,忽略大小写差别 * * @param source 查找的字符串.. * @param prefix 前缀. * @return {@code true} 如果指定字符串是这个字符串的前缀, 否则{@code false} */ public static boolean startsWithIgnoreCase(String source, String prefix) { if (source == prefix) { return true; } if (source == null || prefix == null) { return false; } return source.regionMatches(true, 0, prefix, 0, prefix.length()); } /** * 比较两个字符串,是否prefix字符串是source字符串的后缀,忽略大小写差别 * * @param source 查找的字符串.. * @param suffix 后缀. * @return {@code true} 如果指定字符串是这个字符串的后缀, 否则{@code false} */ public static boolean endsWithIgnoreCase(String source, String suffix) { if (source == suffix) { return true; } if (source == null || suffix == null) { return false; } int startIndex = source.length() - suffix.length(); if (startIndex < 0) { return false; } return source.regionMatches(true, startIndex, suffix, 0, suffix.length()); } /** * 使用数组中的键值对替换字符串. 算法将每个在字符串中找的的key替换成对应value. * 数组的构造类似 {key1, value1, key2, value2...}. * * @param source source字符串. * @param keyValueArray 包含键值对的数组. * @return 被替换了的字符串,如果没有找到任意key则返回source. */ public static String replaceWith(String source, Object... keyValueArray) { if (TextUtils.isEmpty(source)) { return source; } if (keyValueArray.length % 2 != 0) { throw new IllegalArgumentException("key value array not valid"); } StringBuilder sb = null; for (int i = 0; i < keyValueArray.length; i += 2) { String key = String.valueOf(keyValueArray[i]); String value = String.valueOf(keyValueArray[i + 1]); int index = sb != null ? sb.indexOf(key) : source.indexOf(key); while (index >= 0) { if (sb == null) { sb = new StringBuilder(source); } sb.replace(index, index + key.length(), value); index = sb.indexOf(key, index + value.length()); } } return sb != null ? sb.toString() : source; } /** * 使用数组中的键值对替换StringBuilder. 算法将每个在字符串中找的的key替换成对应value. * 数组的构造类似 {key1, value1, key2, value2...}. * * @param source source StringBuilder. * @param keyValueArray 包含键值对的数组. * @return 被处理过的StringBuilder. */ public static StringBuilder replaceWith(StringBuilder source, Object... keyValueArray) { if (TextUtils.isEmpty(source)) { return source; } if (keyValueArray.length % 2 != 0) { throw new IllegalArgumentException("key value array not valid"); } for (int i = 0; i < keyValueArray.length; i += 2) { String key = String.valueOf(keyValueArray[i]); String value = String.valueOf(keyValueArray[i + 1]); int index = source.indexOf(key); while (index >= 0) { source.replace(index, index + key.length(), value); index = source.indexOf(key, index + value.length()); } } return source; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/ThreadUtils.java ================================================ package com.wkw.common_lib.utils; import android.os.Handler; import android.os.Looper; import android.util.Printer; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicBoolean; /** * Created by wukewei on 16/7/24. */ public class ThreadUtils { /** * Map to remember looper' printer wrappers. Use WeakHashMap to avoid * hold looper instance permanently. */ private final static WeakHashMap sLooperPrinters = new WeakHashMap(); private static Thread sMainThread = Looper.getMainLooper().getThread(); private static Handler sMainHandler = new Handler(Looper.getMainLooper()); private ThreadUtils() { // static usage. } /** *

Causes the Runnable to be added to the MAIN message queue. * The runnable will be run on the user interface thread.

* * @param r The Runnable that will be executed. * @see #postDelayed * @see #removeCallbacks */ public static void post(Runnable r) { sMainHandler.post(r); } /** *

Causes the Runnable to be added to the MAIN message queue, to be run * after the specified amount of time elapses. * The runnable will be run on the user interface thread.

* * @param r The Runnable that will be executed. * @param delayMillis The delay (in milliseconds) until the Runnable * will be executed. * @see #post * @see #removeCallbacks */ public static void postDelayed(Runnable r, long delayMillis) { sMainHandler.postDelayed(r, delayMillis); } /** *

Removes the specified Runnable from the MAIN message queue.

* * @param r The Runnable to remove from the message handling queue * @see #post * @see #postDelayed */ public static void removeCallbacks(Runnable r) { sMainHandler.removeCallbacks(r); } /** * Run this runnable in MAIN ui thread. * * @param runnable Runnable to run. */ public static void runOnUiThread(Runnable runnable) { if (isMainThread()) { runnable.run(); } else { post(runnable); } } /** * Whether current thread is MAIN ui thread. */ public static boolean isMainThread() { return sMainThread == Thread.currentThread(); } /** * Get the MAIN handler. * * @return Main handler. */ public static Handler getMainHandler() { return sMainHandler; } /** * Add a printer to current thread's looper. * * @param printer Looper printer. */ public static void addLooperPrinter(Printer printer) { addLooperPrinter(Looper.myLooper(), printer); } /** * Add a printer to corresponding looper. * * @param looper Looper. * @param printer Looper printer. */ public static void addLooperPrinter(Looper looper, Printer printer) { if (looper == null) { throw new RuntimeException("null looper"); } PrinterWrapper wrapper; synchronized (sLooperPrinters) { wrapper = sLooperPrinters.get(looper); if (wrapper == null) { wrapper = new PrinterWrapper(); sLooperPrinters.put(looper, wrapper); // set looper' message logging. looper.setMessageLogging(wrapper); } } wrapper.add(printer); } /** * Printer wrapper which allows multiple printers. */ final static class PrinterWrapper implements Printer { // wrapped printers, can ONLY be accessed within #println (thus corresponding looper thread). private final List mWrappedPrinters = new ArrayList(); // pending printers, which is used to hold pending printers (waiting to be wrapped). private final List mPendingPrinters = new LinkedList(); private final AtomicBoolean mHasPendingPrinter = new AtomicBoolean(false); PrinterWrapper() { } @Override public void println(String x) { // deal with pending printer, try to avoid synchronize. if (mHasPendingPrinter.getAndSet(false)) { synchronized (mPendingPrinters) { mWrappedPrinters.addAll(mPendingPrinters); mPendingPrinters.clear(); } } // print. for (Printer printer : mWrappedPrinters) { printer.println(x); } } public void add(Printer printer) { synchronized (mPendingPrinters) { mPendingPrinters.add(printer); } mHasPendingPrinter.set(true); } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/ToashUtils.java ================================================ package com.wkw.common_lib.utils; import android.app.Activity; import android.content.Context; import android.support.annotation.Nullable; import android.view.Gravity; import android.view.View; import android.view.Window; import android.widget.Toast; /** * Created by wukewei on 16/7/24. */ public final class ToashUtils { private static final int LENGTH_SHORT = Toast.LENGTH_SHORT; private static final int LENGTH_LONG = Toast.LENGTH_LONG; private final static int DEFAULT_GRAVITY = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM; private final static Singleton sToast = new Singleton() { @Override protected Toast create(Context context) { if (context == null || context.getApplicationContext() == null) { return null; } try { return Toast.makeText(context.getApplicationContext(), null, LENGTH_SHORT); } catch (Throwable e) { return null; } } }; private ToashUtils() { } /** * Get the singleton instance of toast. * * @param context Application or activity context. * @return Singleton instance of toast. */ public static Toast get(Context context) { return sToast.get(context); } /** * Show application or activity level toast. * * @param context Application or activity context. * @param resId The resource text to show. Can be formatted text. */ public static void show(Context context, int resId) { show(context, resId, LENGTH_SHORT); } /** * Show application or activity level toast. * * @param context Application or activity context. * @param msg The text to show. Can be formatted text. */ public static void show(Context context, CharSequence msg) { show(context, msg, LENGTH_SHORT); } /** * Show application or activity level toast. * * @param context Application or activity context. * @param resId The resource text to show. Can be formatted text. * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or * {@link Toast#LENGTH_LONG} */ public static void show(Context context, int resId, int duration) { show(context, resId, duration, DEFAULT_GRAVITY); } /** * Show application or activity level toast. * * @param context Application or activity context. * @param msg The text to show. Can be formatted text. * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or * {@link Toast#LENGTH_LONG} */ public static void show(Context context, CharSequence msg, int duration) { show(context, msg, duration, DEFAULT_GRAVITY); } /** * Show application or activity level toast. * * @param context Application or activity context. * @param resId The resource text to show. Can be formatted text. * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or * {@link Toast#LENGTH_LONG} * @param gravity The gravity when display the message. See constant defined in {@link Gravity}. */ public static void show(Context context, int resId, int duration, int gravity) { show(context, resId == 0 ? null : getString(context, resId), duration, gravity); } /** * Show application or activity level toast. * * @param context Application or activity context. * @param msg The text to show. Can be formatted text. * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or * {@link Toast#LENGTH_LONG} * @param gravity The gravity when display the message. See constant defined in {@link Gravity}. */ public static void show(Context context, final CharSequence msg, final int duration, final int gravity) { if (msg == null || msg.length() == 0) { return; } if (!shouldShow(context)) { return; } final Context appContext = context.getApplicationContext(); if (ThreadUtils.isMainThread()) { showImmediately(appContext, msg, duration, gravity); } else { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { showImmediately(appContext, msg, duration, gravity); } }); } } /** * Show activity level toast. * * @param activity Activity. * @param resId The resource text to show. Can be formatted text. */ public static void show(Activity activity, int resId) { show(activity, resId, LENGTH_SHORT); } /** * Show activity level toast. * * @param activity Activity, can be null. * @param msg The text to show. Can be formatted text. */ public static void show(@Nullable Activity activity, CharSequence msg) { show(activity, msg, LENGTH_SHORT); } /** * Show activity level toast. * * @param activity Activity. * @param resId The resource text to show. Can be formatted text. * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or * {@link Toast#LENGTH_LONG} */ public static void show(@Nullable Activity activity, int resId, int duration) { show(activity, resId == 0 ? null : getString(activity, resId), duration, DEFAULT_GRAVITY); } /** * Show activity level toast. * * @param activity Activity. * @param msg The text to show. Can be formatted text. * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or * {@link Toast#LENGTH_LONG} */ public static void show(@Nullable Activity activity, CharSequence msg, int duration) { show(activity, msg, duration, DEFAULT_GRAVITY); } /** * Show activity level toast. * * @param activity Activity. * @param resId The resource text to show. Can be formatted text. * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or * {@link Toast#LENGTH_LONG} * @param gravity The gravity when display the message. See constant defined in {@link Gravity}. */ public static void show(@Nullable Activity activity, int resId, int duration, int gravity) { show(activity, resId == 0 ? null : getString(activity, resId), duration, gravity); } /** * Show activity level toast. * * @param activity Activity. * @param msg The text to show. Can be formatted text. * @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} or * {@link Toast#LENGTH_LONG} * @param gravity The gravity when display the message. See constant defined in {@link Gravity}. */ public static void show(@Nullable Activity activity, final CharSequence msg, final int duration, final int gravity) { if (msg == null || msg.length() == 0) { return; } if (!shouldShow(activity)) { return; } final Context appContext = activity.getApplicationContext(); if (ThreadUtils.isMainThread()) { showImmediately(appContext, msg, duration, gravity); } else { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { showImmediately(appContext, msg, duration, gravity); } }); } } private static void showImmediately(Context context, CharSequence msg, int duration, int gravity) { Toast toast = sToast.get(context); if (toast != null) { try { toast.setText(msg); toast.setDuration(duration); toast.setGravity(gravity, toast.getXOffset(), toast.getYOffset()); toast.show(); } catch (Throwable e) { // internal INotificationManager may be null, just catch it and do nothing. } } } private static boolean shouldShow(Context context) { if (context == null) { // special situation. return true; } if (context != context.getApplicationContext()) { // fast way: application context. return true; } if (context instanceof Activity) { return shouldShow((Activity) context); } // default. return true; } private static boolean shouldShow(Activity activity) { if (activity == null) { // null activity. return false; } if (activity.isFinishing()) { // activity finished. return false; } Window window = activity.getWindow(); if (window == null) { // contains no window. return false; } View decorView = window.getDecorView(); if (decorView == null || decorView.getVisibility() != View.VISIBLE) { // contains no decor view or decor view is not visible. return false; } return true; } private static String getString(Context context, int resId) { return context.getString(resId); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/utils/ViewUtils.java ================================================ package com.wkw.common_lib.utils; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.widget.FrameLayout; import com.wkw.common_lib.Ext; import java.security.InvalidParameterException; /** * Created by wukewei on 16/7/24. */ public final class ViewUtils { private final static boolean DEBUG = false; private final static Object TAG_DECORATE = new Object(); static private float density = -1; static private int screenWidth = -1; static private int screenHeight = -1; static { DisplayMetrics metris = Ext.getContext().getResources().getDisplayMetrics(); density = metris.density; if (metris.widthPixels < metris.heightPixels) { screenWidth = metris.widthPixels; screenHeight = metris.heightPixels; } else { // 部分机器使用application的context宽高反转 screenHeight = metris.widthPixels; screenWidth = metris.heightPixels; Log.d("ViewUtils", "screenHeight:" + screenHeight + ",screenWidth:" + screenWidth); } } private ViewUtils() { // static use. } public static T findById(View view, int id) { return (T) view.findViewById(id); } /** * 防止控件被连续误点击的实用方法,传入要保护的时间,在此时间内将不可被再次点击 */ public static void preventViewMultipleClick(final View v, int protectionMilliseconds) { v.setClickable(false); v.setEnabled(false); v.postDelayed(new Runnable() { @Override public void run() { v.setClickable(true); v.setEnabled(true); } }, protectionMilliseconds); } /** * Helper to set tag. Notice, do NOT use {@link android.view.View#setTag} * or {@link android.view.View#getTag} after this. Use {@link #getTag(android.view.View)} instead. */ public static void setTag(View view, final Object tag) { setTagInternal(view, 0, tag, true); } /** * Helper to get tag of view. */ public static Object getTag(View view) { return getTagInternal(view, 0); } /** * Helper to set tag with key-value pair. Notice, do NOT use {@link android.view.View#setTag} * or {@link android.view.View#getTag} after this. Use {@link #getTag(android.view.View, int)} instead. */ public static void setTag(View view, int key, final Object tag) { setTagInternal(view, key, tag, false); } /** * Helper to get tag of specific key.. */ public static Object getTag(View view, int key) { return getTagInternal(view, key); } @SuppressWarnings("unchecked") private static void setTagInternal(View view, int key, final Object tag, boolean ignoreKey) { if (view == null) { return; } if (!ignoreKey) { // If the package id is 0x00 or 0x01, it's either an undefined package // or a framework id if ((key >>> 24) < 2) { throw new IllegalArgumentException("The key must be an application-specific " + "resource id."); } } Object viewTag = view.getTag(); if (viewTag == null || !(viewTag instanceof SparseArray)) { viewTag = new SparseArray(); } SparseArray tagArray = (SparseArray) viewTag; tagArray.put(key, tag); view.setTag(tagArray); } @SuppressWarnings("unchecked") private static Object getTagInternal(View view, int key) { if (view == null) { return null; } Object viewTag = view.getTag(); if (viewTag == null || !(viewTag instanceof SparseArray)) { return null; } SparseArray tagArray = (SparseArray) viewTag; return tagArray.get(key); } /** * Decorate a decor view on corresponding host view. * * @param hostView host view to be decorated with. * @param decorView decor view. * @param gravity gravity of decor view. */ public static void decorate(View hostView, View decorView, int gravity) { decorate(hostView, decorView, gravity, 0, 0, 0, 0); } /** * Decorate a decor view on corresponding host view. * * @param hostView host view to be decorated with. * @param decorView decor view. * @param gravity gravity of decor view. * @param leftMargin left margin of decor view. * @param topMargin top margin of decor view. * @param rightMargin right margin of decor view. * @param bottomMargin bottom margin of decor view. */ public static void decorate(View hostView, View decorView, int gravity, int leftMargin, int topMargin, int rightMargin, int bottomMargin) { if (hostView == null || decorView == null) { return; } ViewParent parent = hostView.getParent(); if (parent == null) { if (DEBUG) { throw new IllegalStateException("host " + hostView + " not attached to parent"); } return; } if (!(parent instanceof ViewGroup)) { if (DEBUG) { throw new InvalidParameterException("host " + hostView + " has invalid parent " + parent); } return; } if (decorView.getParent() != null) { if (DEBUG) { throw new IllegalStateException("decorate " + decorView + " has already be added to a ViewParent " + decorView.getParent()); } return; } // generate layout params, before modify the host view's layout params. FrameLayout.LayoutParams hostLp = generateHostLayoutParams(hostView); FrameLayout.LayoutParams decorLp = generateDecorLayoutParams(gravity, leftMargin, topMargin, rightMargin, bottomMargin); ViewGroup hostGroup = (ViewGroup) parent; FrameLayout decorContainer; if ((hostGroup instanceof FrameLayout) && getTag(hostView) == TAG_DECORATE) { decorContainer = (FrameLayout) hostGroup; } else { decorContainer = new DecorateContainer(hostGroup.getContext(), hostView); // decorate container should re-use the layout params and index as host view. int index = computeChildIndex(hostGroup, hostView); ViewGroup.LayoutParams lp = hostView.getLayoutParams(); // decorate container should wrap it's content (host and decorate view). lp.width = ViewGroup.LayoutParams.WRAP_CONTENT; lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; // remove host view & add decorate container. hostGroup.removeView(hostView); hostGroup.addView(decorContainer, index, lp); // tag for recognise. setTag(decorContainer, TAG_DECORATE); } // remove all existing decorates. decorContainer.removeAllViews(); // add host & decorate view. if (hostLp != null) { decorContainer.addView(hostView, hostLp); } if (decorLp != null) { decorContainer.addView(decorView, decorLp); } } private static FrameLayout.LayoutParams generateHostLayoutParams(View hostView) { if (hostView == null) { return null; } FrameLayout.LayoutParams lp = newLayoutParams(hostView.getLayoutParams()); // host layout should contains no margin, it's container already preserves. lp.leftMargin = lp.rightMargin = lp.topMargin = lp.bottomMargin = 0; return lp; } private static FrameLayout.LayoutParams generateDecorLayoutParams(int gravity, int leftMargin, int topMargin, int rightMargin, int bottomMargin) { FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); lp.gravity = gravity; lp.leftMargin = leftMargin; lp.topMargin = topMargin; lp.rightMargin = rightMargin; lp.bottomMargin = bottomMargin; return lp; } private static FrameLayout.LayoutParams newLayoutParams(ViewGroup.LayoutParams source) { if (source == null) { return null; } if (source instanceof ViewGroup.MarginLayoutParams) { return new FrameLayout.LayoutParams((ViewGroup.MarginLayoutParams) source); } else { return new FrameLayout.LayoutParams(source); } } private static int computeChildIndex(ViewGroup parent, View child) { if (parent == null || child == null) { return -1; } int index = 0; int count = parent.getChildCount(); for (; index < count; index++) { if (parent.getChildAt(index) == child) { break; } } return (index >= 0 && index < count) ? index : -1; } /** * Capture corresponding view. * * @param view view to capture. */ public static Bitmap capture(View view) { view.buildDrawingCache(); Bitmap drawingCache = view.getDrawingCache(); if (drawingCache == null) { return null; } Context context = view.getContext(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); Bitmap bitmap = Bitmap.createBitmap(drawingCache, 0, 0, Math.min(outMetrics.widthPixels, drawingCache.getWidth()), Math.min(outMetrics.heightPixels, drawingCache.getHeight())); if (!view.isDrawingCacheEnabled()) { view.destroyDrawingCache(); } return bitmap; } // 支持系统设置的字体大中小变化 public static float getSpValue(float value) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value, Ext.getContext().getResources().getDisplayMetrics()); } public static boolean isChildOf(View c, View p) { if (c == p) { return true; } else if (p instanceof ViewGroup) { int count = ((ViewGroup) p).getChildCount(); for (int i = 0; i < count; i++) { View ci = ((ViewGroup) p).getChildAt(i); if (isChildOf(c, ci)) { return true; } } } return false; } public static void getChildPos(View child, View parent, int[] posContainer) { if (posContainer == null || posContainer.length < 2) { return; } int x = 0; int y = 0; View vc = child; while (vc.getParent() != null) { x += vc.getLeft(); y += vc.getTop(); if (vc.getParent() == parent) { posContainer[0] = x; posContainer[1] = y; if (posContainer.length >= 4) { posContainer[2] = vc.getMeasuredWidth(); posContainer[3] = vc.getMeasuredHeight(); } break; } try { vc = (View) vc.getParent(); if (posContainer.length >= 4) { posContainer[2] = vc.getMeasuredWidth(); posContainer[3] = vc.getMeasuredHeight(); } } catch (ClassCastException e) { break; } } if (parent == null) { posContainer[0] = x; posContainer[1] = y; } } public static String getActivityName(Context ctx) { Context c = ctx; if (!(ctx instanceof Activity) && (ctx instanceof ContextWrapper)) { c = ((ContextWrapper) ctx).getBaseContext(); } return c.getClass().getName(); } public static int getStatusBarHeight(Context context) { int result = 0; Resources resources = context.getResources(); int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = resources.getDimensionPixelSize(resourceId); } return result; } public static float getDensity() { return density; } public static int getScreenWidth() { return screenWidth; } public static int getScreenHeight() { return screenHeight; } /** * Converts a dp value to a px value * * @param dp the dp value */ public static int dpToPx(float dp) { return Math.round(dp * getDensity()); } public static int pxToDp(float px) { return Math.round(px / getDensity()); } public static int spToPx(float sp) { final float fontScale = Ext.getContext().getResources().getDisplayMetrics().scaledDensity; return (int) (sp * fontScale + 0.5f); } public static int pxTosp(float px) { final float fontScale = Ext.getContext().getResources().getDisplayMetrics().scaledDensity; return (int) (px / fontScale + 0.5f); } /** * 在xml里设置android:alpha对api11以前的系统不起作用,所以在代码里获取并设置透明度 */ public static void setAlpha(View view, float alphaValue) { if (view == null) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { view.setAlpha(alphaValue); } else { AlphaAnimation alpha = new AlphaAnimation(alphaValue, alphaValue); alpha.setDuration(0); alpha.setFillAfter(true); view.startAnimation(alpha); } } /** * 兼容4.1前后的设置view background drawable的方法 */ public static void setViewBackground(View v, Drawable drawable) { if (v == null) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { v.setBackgroundDrawable(drawable); } else { v.setBackground(drawable); } } private static class DecorateContainer extends FrameLayout { private final View mHostView; public DecorateContainer(Context context, View hostView) { super(context); mHostView = hostView; } @Override public int getVisibility() { // decorate container share the visibility with host view. return mHostView != null ? mHostView.getVisibility() : super.getVisibility(); } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/ClearEditText.java ================================================ package com.wkw.common_lib.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.v7.widget.AppCompatEditText; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.CycleInterpolator; import android.view.animation.TranslateAnimation; import com.wkw.common_lib.R; /** * Created by wukewei on 16/12/3. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class ClearEditText extends AppCompatEditText implements View.OnFocusChangeListener, TextWatcher { private Drawable mClearDrawable; public ClearEditText(Context context) { this(context, null); } public ClearEditText(Context context, AttributeSet attrs) { this(context, attrs, R.attr.editTextStyle); } public ClearEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ClearEditText); mClearDrawable = a.getDrawable(R.styleable.ClearEditText_clearDrawable); if (mClearDrawable == null) { mClearDrawable = getResources().getDrawable(R.drawable.ic_delete); } mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); setClearIconVisible(false); setOnFocusChangeListener(this); addTextChangedListener(this); } /** * 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件 * 当我们按下的位置 在 EditText的宽度 - 图标到控件右边的间距 - 图标的宽度 和 * EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向没有考虑 */ @Override public boolean onTouchEvent(MotionEvent event) { if (getCompoundDrawables()[2] != null) { if (event.getAction() == MotionEvent.ACTION_UP) { boolean touchable = event.getX() > (getWidth() - getPaddingRight() - mClearDrawable.getIntrinsicWidth()) && (event.getX() < ((getWidth() - getPaddingRight()))); if (touchable) { this.setText(""); } } } return super.onTouchEvent(event); } /** * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏 */ @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } } /** * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去 * * @param visible true if visible */ private void setClearIconVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } /** * 当输入框里面内容发生变化的时候回调的方法 */ @Override public void onTextChanged(CharSequence s, int start, int count, int after) { super.onTextChanged(s, start, count, after); setClearIconVisible(hasFocus() && s.length() > 0); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } /** * 设置晃动动画 */ public void setShakeAnimation() { setAnimation(shakeAnimation(5)); } /** * 晃动动画 * * @param counts 1秒钟晃动多少下 * @return animation generated */ public static Animation shakeAnimation(int counts) { Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0); translateAnimation.setInterpolator(new CycleInterpolator(counts)); translateAnimation.setDuration(1000); return translateAnimation; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/CustomTabHost.java ================================================ package com.wkw.test.tabhost; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TabHost; import android.widget.TabWidget; import java.util.ArrayList; /** * Created by wukewei on 17/2/21. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class CustomTabHost extends TabHost implements TabHost.OnTabChangeListener { private final ArrayList mTabs = new ArrayList(); private FrameLayout mRealTabContent; private Context mContext; private FragmentManager mFragmentManager; private int mContainerId; private OnTabChangeListener mOnTabChangeListener; private TabInfo mLastTab; private boolean mAttached; static final class TabInfo { private final String tag; private final Class clss; private final Bundle args; private Fragment fragment; TabInfo(String _tag, Class _class, Bundle _args) { tag = _tag; clss = _class; args = _args; } } static class DummyTabFactory implements TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } static class SavedState extends BaseSavedState { String curTab; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); curTab = in.readString(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(curTab); } @Override public String toString() { return "FragmentTabHost.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " curTab=" + curTab + "}"; } public static final Creator CREATOR = new Creator() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } public CustomTabHost(Context context) { // Note that we call through to the version that takes an AttributeSet, // because the simple Context construct can result in a broken object! super(context, null); initFragmentTabHost(context, null); } public CustomTabHost(Context context, AttributeSet attrs) { super(context, attrs); initFragmentTabHost(context, attrs); } private void initFragmentTabHost(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, new int[]{android.R.attr.inflatedId}, 0, 0); mContainerId = a.getResourceId(0, 0); a.recycle(); super.setOnTabChangedListener(this); } private void ensureHierarchy(Context context) { // If owner hasn't made its own view hierarchy, then as a convenience // we will construct a standard one here. if (findViewById(android.R.id.tabs) == null) { LinearLayout ll = new LinearLayout(context); ll.setOrientation(LinearLayout.VERTICAL); addView(ll, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); TabWidget tw = new TabWidget(context); tw.setId(android.R.id.tabs); tw.setOrientation(TabWidget.HORIZONTAL); ll.addView(tw, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0)); FrameLayout fl = new FrameLayout(context); fl.setId(android.R.id.tabcontent); ll.addView(fl, new LinearLayout.LayoutParams(0, 0, 0)); mRealTabContent = fl = new FrameLayout(context); mRealTabContent.setId(mContainerId); ll.addView(fl, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1)); } } /** * @deprecated Don't call the original TabHost setup, you must instead * call {@link #setup(Context, FragmentManager)} or * {@link #setup(Context, FragmentManager, int)}. */ @Override @Deprecated public void setup() { throw new IllegalStateException( "Must call setup() that takes a Context and FragmentManager"); } public void setup(Context context, FragmentManager manager) { ensureHierarchy(context); // Ensure views required by super.setup() super.setup(); mContext = context; mFragmentManager = manager; ensureContent(); } public void setup(Context context, FragmentManager manager, int containerId) { ensureHierarchy(context); // Ensure views required by super.setup() super.setup(); mContext = context; mFragmentManager = manager; mContainerId = containerId; ensureContent(); mRealTabContent.setId(containerId); // We must have an ID to be able to save/restore our state. If // the owner hasn't set one at this point, we will set it ourself. if (getId() == View.NO_ID) { setId(android.R.id.tabhost); } } private void ensureContent() { if (mRealTabContent == null) { mRealTabContent = (FrameLayout) findViewById(mContainerId); if (mRealTabContent == null) { throw new IllegalStateException( "No tab content FrameLayout found for id " + mContainerId); } } } @Override public void setOnTabChangedListener(OnTabChangeListener l) { mOnTabChangeListener = l; } public void addTab(TabSpec tabSpec, Class clss, Bundle args) { tabSpec.setContent(new DummyTabFactory(mContext)); String tag = tabSpec.getTag(); TabInfo info = new TabInfo(tag, clss, args); if (mAttached) { // If we are already attached to the window, then check to make // sure this tab's fragment is inactive if it exists. This shouldn't // normally happen. info.fragment = mFragmentManager.findFragmentByTag(tag); if (info.fragment != null && !info.fragment.isDetached()) { FragmentTransaction ft = mFragmentManager.beginTransaction(); // ft.detach(info.fragment); ft.hide(info.fragment); ft.commitAllowingStateLoss(); } } mTabs.add(info); addTab(tabSpec); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); String currentTab = getCurrentTabTag(); // Go through all tabs and make sure their fragments match // the correct state. FragmentTransaction ft = null; for (int i = 0; i < mTabs.size(); i++) { TabInfo tab = mTabs.get(i); tab.fragment = mFragmentManager.findFragmentByTag(tab.tag); // if (tab.fragment != null && !tab.fragment.isDetached()) { if (tab.fragment != null) { if (tab.tag.equals(currentTab)) { // The fragment for this tab is already there and // active, and it is what we really want to have // as the current tab. Nothing to do. mLastTab = tab; } else { // This fragment was restored in the active state, // but is not the current tab. Deactivate it. if (ft == null) { ft = mFragmentManager.beginTransaction(); } // ft.detach(tab.fragment); ft.hide(tab.fragment); } } } // We are now ready to go. Make sure we are switched to the // correct tab. mAttached = true; ft = doTabChanged(currentTab, ft); if (ft != null) { ft.commitAllowingStateLoss(); mFragmentManager.executePendingTransactions(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mAttached = false; } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.curTab = getCurrentTabTag(); return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setCurrentTabByTag(ss.curTab); } @Override public void onTabChanged(String tabId) { if (mAttached) { FragmentTransaction ft = doTabChanged(tabId, null); if (ft != null) { ft.commitAllowingStateLoss(); } } if (mOnTabChangeListener != null) { mOnTabChangeListener.onTabChanged(tabId); } } private FragmentTransaction doTabChanged(String tabId, FragmentTransaction ft) { TabInfo newTab = null; for (int i = 0; i < mTabs.size(); i++) { TabInfo tab = mTabs.get(i); if (tab.tag.equals(tabId)) { newTab = tab; } } if (newTab == null) { throw new IllegalStateException("No tab known for tag " + tabId); } if (mLastTab != newTab) { if (ft == null) { ft = mFragmentManager.beginTransaction(); } if (mLastTab != null) { if (mLastTab.fragment != null) { ft.hide(mLastTab.fragment); //detach改为hide } } if (newTab.fragment == null) { newTab.fragment = Fragment.instantiate(mContext, newTab.clss.getName(), newTab.args); ft.add(mContainerId, newTab.fragment, newTab.tag); } else { ft.show(newTab.fragment); //attach改为show } mLastTab = newTab; } return ft; } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/ProgressLayout.java ================================================ package com.wkw.common_lib.widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import com.wkw.common_lib.R; import java.util.ArrayList; import java.util.List; /** * Created by wukewei on 16/6/1. */ public class ProgressLayout extends RelativeLayout { private static final String LOADING_TAG = "loading_tag"; private static final String ERROR_TAG = "error_tag"; private static final String NOTDATA_TAG = "not_data_tag"; private LayoutParams layoutParams; private LayoutInflater layoutInflater; private RelativeLayout loadingView, errorView, notDataView; private Button btn_error, btn_notdata; private List contentViews = new ArrayList<>(); public ProgressLayout(Context context) { super(context); } private enum State { LOADING, CONTENT, ERROR, NOTDATA } private State currentState = State.LOADING; public ProgressLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public ProgressLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } private void init(AttributeSet attrs) { layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); if (child.getTag() == null || (!child.getTag().equals(LOADING_TAG) && !child.getTag().equals(ERROR_TAG) && !child.getTag().equals(NOTDATA_TAG))) { contentViews.add(child); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (btn_error != null) btn_error.setOnClickListener(null); if (btn_notdata != null) btn_error.setOnClickListener(null); } public void showLoading() { currentState = State.LOADING; this.showLoadingView(); this.hideErrorView(); this.hideNotDataView(); this.setContentVisibility(false); } public void showContent() { currentState = State.CONTENT; this.hideLoadingView(); this.hideErrorView(); this.hideNotDataView(); this.setContentVisibility(true); } public void showError(String msg,OnClickListener click) { if (this.isContent()) return; currentState = State.ERROR; this.hideNotDataView(); this.hideLoadingView(); this.showErrorView(msg); this.btn_error.setOnClickListener(click); this.setContentVisibility(false); } public void showNotData(OnClickListener click) { currentState = State.NOTDATA; this.hideLoadingView(); this.hideErrorView(); this.showNotDataView(); this.btn_notdata.setOnClickListener(click); this.setContentVisibility(false); } public boolean isContent() { return currentState == State.CONTENT; } private void showLoadingView() { if (loadingView == null) { loadingView = (RelativeLayout) layoutInflater.inflate(R.layout.layout_loading_view, null); loadingView.setTag(LOADING_TAG); layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); layoutParams.addRule(CENTER_IN_PARENT); this.addView(loadingView, layoutParams); } else { loadingView.setVisibility(VISIBLE); } } private void showErrorView(String msg) { if (errorView == null) { errorView = (RelativeLayout) layoutInflater.inflate(R.layout.layout_error_view, null); errorView.setTag(ERROR_TAG); btn_error = (Button) errorView.findViewById(R.id.btn_try); ((TextView)errorView.findViewById(R.id.tv_error)).setText(msg); layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); layoutParams.addRule(CENTER_IN_PARENT); this.addView(errorView, layoutParams); } else { errorView.setVisibility(VISIBLE); } } private void showNotDataView() { if (notDataView == null) { notDataView = (RelativeLayout) layoutInflater.inflate(R.layout.layout_no_data_view, null); notDataView.setTag(ERROR_TAG); btn_notdata = (Button) notDataView.findViewById(R.id.btn_try); layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); layoutParams.addRule(CENTER_IN_PARENT); this.addView(notDataView, layoutParams); } else { notDataView.setVisibility(VISIBLE); } } private void hideLoadingView() { if (loadingView != null && loadingView.getVisibility() != GONE) { loadingView.setVisibility(GONE); } } private void hideErrorView() { if (errorView != null && errorView.getVisibility() != GONE) { errorView.setVisibility(GONE); } } private void hideNotDataView() { if (notDataView != null && notDataView.getVisibility() != GONE) { notDataView.setVisibility(GONE); } } private void setContentVisibility(boolean visible) { for (View contentView : contentViews) { contentView.setVisibility(visible ? View.VISIBLE : View.GONE); } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/TimerButton.java ================================================ package com.wkw.common_lib.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import android.widget.Button; /** * Created by wukewei on 16/12/4. * Email zjwkw1992@163.com * GitHub https://github.com/zj-wukewei */ public class TimerButton extends Button { private static final long UNIT = 1000; private long mDuration; private String mNormalText; private String mTimerTextFormat; private Drawable mEnableBackground; private Drawable mDisableBackground; private final Handler mHandler = new Handler(Looper.getMainLooper()); private final Runnable mTimerRunnable = new Runnable() { @Override public void run() { if (mDuration <= 0) { setText(mNormalText); setEnabled(true); return; } setText(String.format(mTimerTextFormat, mDuration / UNIT)); mDuration -= UNIT; mHandler.postDelayed(mTimerRunnable, UNIT); } }; public TimerButton(Context context) { super(context); } public TimerButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public TimerButton(Context context, AttributeSet attrs) { super(context, attrs); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public TimerButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public void startTimer(String timerTextFormat,String normalText, long duration) { mTimerTextFormat = timerTextFormat; mNormalText = normalText; mDuration = duration; setEnabled(false); mHandler.post(mTimerRunnable); } public void setDisableBackground(Drawable disableBackground) { mEnableBackground = getBackground(); mDisableBackground = disableBackground; } private void setEnableStatus(boolean enable) { setEnabled(enable); if (enable) { setBackgroundDrawable(mEnableBackground); } else { setBackgroundDrawable(mDisableBackground); } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/loadmore/DefaultEmptyItem.java ================================================ /* * The GPL License (GPL) * * Copyright (c) 2016 Moduth (https://github.com/moduth) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.wkw.common_lib.widget.loadmore; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.wkw.common_lib.R; /** * 默认的空数据视图 * * @author cjj on 16/1/31. */ public class DefaultEmptyItem extends EmptyItem { private TextView mEmptyTextView; private ImageView mEmptyImageView; @Override public View onCreateView(ViewGroup parent) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_with_footer_empty_layout, parent, false); view.setLayoutParams(new ViewGroup.LayoutParams(parent.getMeasuredWidth(), parent.getMeasuredHeight())); mEmptyTextView = (TextView) view.findViewById(R.id.rv_with_footer_empty_title); mEmptyImageView = (ImageView) view.findViewById(R.id.rv_with_footer_empty_icon); return view; } @Override public void onBindData(View view) { if (TextUtils.isEmpty(mEmptyText)) { mEmptyTextView.setVisibility(View.GONE); } else { mEmptyTextView.setVisibility(View.VISIBLE); mEmptyTextView.setText(mEmptyText); } if (mEmptyIconRes != -1) { mEmptyImageView.setImageResource(mEmptyIconRes); } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/loadmore/DefaultFootItem.java ================================================ /* * The GPL License (GPL) * * Copyright (c) 2016 Moduth (https://github.com/moduth) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.wkw.common_lib.widget.loadmore; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.wkw.common_lib.R; /** * @author cjj */ public class DefaultFootItem extends FootItem { private static final String TAG = "DefaultFootItem"; private ProgressBar mProgressBar; private TextView mLoadingText; private TextView mPullToLoadText; private TextView mEndTextView; @Override public View onCreateView(ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.rv_with_footer_loading, parent, false); mProgressBar = (ProgressBar) view.findViewById(R.id.rv_with_footer_loading_progress); mEndTextView = (TextView) view.findViewById(R.id.rv_with_footer_loading_end); mLoadingText = (TextView) view.findViewById(R.id.rv_with_footer_loading_load); mPullToLoadText = (TextView) view.findViewById(R.id.rv_with_footer_loading_pull_to_load); return view; } @Override public void onBindData(View view, int state) { if (state == RecyclerViewWithFooter.STATE_LOADING) { if (TextUtils.isEmpty(loadingText)) { showProgressBar(view.getContext().getResources().getString(R.string.rv_with_footer_loading)); } else { showProgressBar(loadingText); } } else if (state == RecyclerViewWithFooter.STATE_END) { if (TextUtils.isEmpty(endText)) { showPullToLoad(view.getContext().getResources().getString(R.string.rv_with_footer_empty)); } else { showPullToLoad(endText); } } else if (state == RecyclerViewWithFooter.STATE_PULL_TO_LOAD) { if (TextUtils.isEmpty(pullToLoadText)) { showPullToLoad(view.getContext().getResources().getString(R.string.rv_with_footer_pull_load_more)); } else { showPullToLoad(pullToLoadText); } } } public void showPullToLoad(CharSequence message) { if (mPullToLoadText != null) { mPullToLoadText.setVisibility(View.VISIBLE); if (!TextUtils.isEmpty(message)) { mPullToLoadText.setText(message); } } if (mEndTextView != null) { mEndTextView.setVisibility(View.GONE); } if (mProgressBar != null) { mProgressBar.setVisibility(View.GONE); } if (mLoadingText != null) { mLoadingText.setVisibility(View.GONE); } } public void showProgressBar(CharSequence load) { if (mEndTextView != null) { mEndTextView.setVisibility(View.GONE); } if (mProgressBar != null) { mProgressBar.setVisibility(View.VISIBLE); } if (mPullToLoadText != null) { mPullToLoadText.setVisibility(View.GONE); } if (mLoadingText != null) { if (!TextUtils.isEmpty(load)) { mLoadingText.setVisibility(View.VISIBLE); mLoadingText.setText(load); } else { mLoadingText.setVisibility(View.GONE); } } } public void showEnd(CharSequence end) { if (mEndTextView != null) { mEndTextView.setVisibility(View.VISIBLE); if (!TextUtils.isEmpty(end)) { mEndTextView.setText(end); } } if (mPullToLoadText != null) { mPullToLoadText.setVisibility(View.GONE); } if (mProgressBar != null) { mProgressBar.setVisibility(View.GONE); } if (mLoadingText != null) { mLoadingText.setVisibility(View.GONE); } } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/loadmore/EmptyFootItem.java ================================================ /* * The GPL License (GPL) * * Copyright (c) 2016 Moduth (https://github.com/moduth) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.wkw.common_lib.widget.loadmore; import android.view.View; import android.view.ViewGroup; import android.widget.Space; /** * @author markzhai on 16/7/11 * @version 1.3.0 */ public class EmptyFootItem extends FootItem { @Override public View onCreateView(ViewGroup parent) { return new Space(parent.getContext()); } @Override public void onBindData(View view, int state) { } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/loadmore/EmptyItem.java ================================================ /* * The GPL License (GPL) * * Copyright (c) 2016 Moduth (https://github.com/moduth) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.wkw.common_lib.widget.loadmore; import android.view.View; import android.view.ViewGroup; /** * 没数据时候的默认View * * @author zzz40500 on 16/1/31. */ public abstract class EmptyItem { CharSequence mEmptyText; int mEmptyIconRes = -1; abstract View onCreateView(ViewGroup parent); abstract void onBindData(View view); } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/loadmore/FootItem.java ================================================ /* * The GPL License (GPL) * * Copyright (c) 2016 Moduth (https://github.com/moduth) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.wkw.common_lib.widget.loadmore; import android.view.View; import android.view.ViewGroup; /** * Footer item * * @author cjj on 2016/1/30. */ public abstract class FootItem { public CharSequence loadingText; public CharSequence endText; public CharSequence pullToLoadText; public abstract View onCreateView(ViewGroup parent); public abstract void onBindData(View view, int state); } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/loadmore/OnLoadMoreListener.java ================================================ /* * The GPL License (GPL) * * Copyright (c) 2016 Moduth (https://github.com/moduth) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.wkw.common_lib.widget.loadmore; /** * Load more interface * * @author cjj */ public interface OnLoadMoreListener { void onLoadMore(); } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/loadmore/RecyclerViewUtils.java ================================================ /* * The GPL License (GPL) * * Copyright (c) 2016 Moduth (https://github.com/moduth) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.wkw.common_lib.widget.loadmore; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; /** * 设置rv manager 类型 * * @author cjj */ class RecyclerViewUtils { private static final String TAG = "RecyclerViewUtils"; public static void setVerticalLinearLayout(RecyclerView rv) { LinearLayoutManager layoutManager = new LinearLayoutManager(rv.getContext(), LinearLayoutManager.VERTICAL, false) { @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { try { super.onLayoutChildren(recycler, state); } catch (IndexOutOfBoundsException e) { Log.e(TAG, "meet an IndexOutOfBoundsException in RecyclerView"); } } }; rv.setLayoutManager(layoutManager); } public static void setGridLayout(final RecyclerView rv, int spanCount) { final GridLayoutManager gridLayoutManager = new GridLayoutManager(rv.getContext(), spanCount, GridLayoutManager.VERTICAL, false) { @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { try { super.onLayoutChildren(recycler, state); } catch (IndexOutOfBoundsException e) { Log.e(TAG, "meet an IndexOutOfBoundsException in RecyclerView"); } } }; gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { int viewType = rv.getAdapter().getItemViewType(position); if (viewType < 0) { return gridLayoutManager.getSpanCount(); } return 1; } }); rv.setLayoutManager(gridLayoutManager); } public static void setStaggeredGridLayoutManager(RecyclerView rv, int spanCount) { StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL) { @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { try { super.onLayoutChildren(recycler, state); } catch (IndexOutOfBoundsException e) { Log.e(RecyclerViewUtils.TAG, "meet an IndexOutOfBoundsException in RecyclerView"); } } }; rv.setLayoutManager(staggeredGridLayoutManager); } } ================================================ FILE: common_lib/src/main/java/com/wkw/common_lib/widget/loadmore/RecyclerViewWithFooter.java ================================================ /* * The GPL License (GPL) * * Copyright (c) 2016 Moduth (https://github.com/moduth) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.wkw.common_lib.widget.loadmore; import android.content.Context; import android.support.annotation.DrawableRes; import android.support.annotation.IntDef; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * A {@link RecyclerView} with footer which enables load more. * https://github.com/android-cjj/Android-RecyclerViewWithFooter * @author cjj */ public class RecyclerViewWithFooter extends RecyclerView { private static final String TAG = "RecyclerViewWithFooter"; public static final int STATE_END = 0; public static final int STATE_LOADING = 1; public static final int STATE_EMPTY = 2; public static final int STATE_NONE = 3; public static final int STATE_PULL_TO_LOAD = 4; private boolean mIsGettingData = false; @State private int mState = STATE_NONE; /** * 默认的 FootItem; */ private FootItem mFootItem = new DefaultFootItem(); private EmptyItem mEmptyItem = new DefaultEmptyItem(); private AdapterDataObserver mAdapterDataObserver = new AdapterDataObserver() { @Override public void onChanged() { super.onChanged(); reset(); } private void reset() { mIsGettingData = false; } @Override public void onItemRangeChanged(int positionStart, int itemCount) { super.onItemRangeChanged(positionStart, itemCount); reset(); } @Override public void onItemRangeChanged(int positionStart, int itemCount, Object payload) { super.onItemRangeChanged(positionStart, itemCount, payload); reset(); } @Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); reset(); } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { super.onItemRangeRemoved(positionStart, itemCount); reset(); } @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { super.onItemRangeMoved(fromPosition, toPosition, itemCount); reset(); } }; public RecyclerViewWithFooter(Context context) { super(context); init(); } public RecyclerViewWithFooter(Context context, AttributeSet attrs) { super(context, attrs); init(); } public RecyclerViewWithFooter(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { setVerticalLinearLayout(); } @Override protected void onMeasure(int widthSpec, int heightSpec) { super.onMeasure(widthSpec, heightSpec); // int width = MeasureSpec.getSize(widthSpec); // if(width != 0){ // int spans = width / mItemWidth; // if(spans > 0){ // mLayoutManager.setSpanCount(spans); // } // } } public void setVerticalLinearLayout() { RecyclerViewUtils.setVerticalLinearLayout(this); } public void setGridLayout(int span) { RecyclerViewUtils.setGridLayout(this, span); } public void setStaggeredGridLayoutManager(int spanCount) { RecyclerViewUtils.setStaggeredGridLayoutManager(this, spanCount); } public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) { setPullToLoad(); final OnLoadMoreListenerWrapper wrapper = new OnLoadMoreListenerWrapper(onLoadMoreListener); addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof LinearLayoutManager) { int lastVisiblePosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition(); if (lastVisiblePosition >= recyclerView.getAdapter().getItemCount() - 1) { wrapper.onLoadMore(); if (mState == STATE_PULL_TO_LOAD) { setLoading(); } } } else if (layoutManager instanceof StaggeredGridLayoutManager) { StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager; int last[] = new int[staggeredGridLayoutManager.getSpanCount()]; staggeredGridLayoutManager.findLastVisibleItemPositions(last); for (int aLast : last) { Log.i(TAG, aLast + " " + recyclerView.getAdapter().getItemCount()); if (aLast >= recyclerView.getAdapter().getItemCount() - 1) { wrapper.onLoadMore(); if (mState == STATE_PULL_TO_LOAD) { setLoading(); } } } } } } }); } @Override public void setAdapter(Adapter adapter) { LoadMoreAdapter loadMoreAdapter; if (adapter instanceof LoadMoreAdapter) { loadMoreAdapter = (LoadMoreAdapter) adapter; loadMoreAdapter.registerAdapterDataObserver(mAdapterDataObserver); super.setAdapter(adapter); } else { loadMoreAdapter = new LoadMoreAdapter(adapter); loadMoreAdapter.registerAdapterDataObserver(mAdapterDataObserver); super.setAdapter(loadMoreAdapter); } } /** * 设置loading提示字符串 * * @param loadText 提示字符串 * @return {@link RecyclerViewWithFooter} */ public RecyclerViewWithFooter applyLoadingText(CharSequence loadText) { mFootItem.loadingText = loadText; return this; } public RecyclerViewWithFooter applyPullToLoadText(CharSequence pullToLoadText) { mFootItem.pullToLoadText = pullToLoadText; return this; } public RecyclerViewWithFooter applyEndText(CharSequence endText) { mFootItem.endText = endText; return this; } public RecyclerViewWithFooter applyEmptyText(CharSequence emptyText, @DrawableRes int drawableId) { mEmptyItem.mEmptyIconRes = drawableId; mEmptyItem.mEmptyText = emptyText; return this; } public void setFootItem(FootItem footItem) { if (mFootItem != null) { if (footItem.endText == null) { footItem.endText = mFootItem.endText; } if (footItem.loadingText == null) { footItem.loadingText = mFootItem.loadingText; } if (footItem.pullToLoadText == null) { footItem.pullToLoadText = mFootItem.pullToLoadText; } } mFootItem = footItem; } public void setEmptyItem(EmptyItem emptyItem) { if (mEmptyItem != null) { if (emptyItem.mEmptyIconRes == -1) { emptyItem.mEmptyIconRes = mEmptyItem.mEmptyIconRes; } if (emptyItem.mEmptyText == null) { emptyItem.mEmptyText = mEmptyItem.mEmptyText; } } mEmptyItem = emptyItem; } /** * 切换为上拉加载更多状态 */ public void setPullToLoad() { if (getAdapter() != null) { mState = STATE_PULL_TO_LOAD; mIsGettingData = false; getAdapter().notifyItemChanged(getAdapter().getItemCount() - 1); getAdapter().notifyDataSetChanged(); } } /** * 切换为loading状态 */ public void setLoading() { if (getAdapter() != null) { mState = STATE_LOADING; mIsGettingData = true; getAdapter().notifyItemChanged(getAdapter().getItemCount() - 1); getAdapter().notifyDataSetChanged(); } } /** * 切换为没有更多数据状态 * * @param end 提示字符串 */ public void setEnd(CharSequence end) { if (getAdapter() != null) { mIsGettingData = false; mState = STATE_END; mFootItem.endText = end; getAdapter().notifyItemChanged(getAdapter().getItemCount() - 1); getAdapter().notifyDataSetChanged(); } } /** * 切换为没有更多数据状态 */ public void setEnd() { if (getAdapter() != null) { mIsGettingData = false; mState = STATE_END; getAdapter().notifyItemChanged(getAdapter().getItemCount() - 1); getAdapter().notifyDataSetChanged(); } } /** * 切换成无数据状态 * * @param empty 无数据状态提示消息 * @param resId 无数据状态提示图标 */ public void setEmpty(CharSequence empty, @DrawableRes int resId) { if (getAdapter() != null) { mState = STATE_EMPTY; mEmptyItem.mEmptyText = empty; mEmptyItem.mEmptyIconRes = resId; if (isEmpty()) { getAdapter().notifyDataSetChanged(); } } } /** * 切换成无数据状态 */ public void setEmpty() { if (getAdapter() != null) { mState = STATE_EMPTY; if (isEmpty()) { getAdapter().notifyDataSetChanged(); } } } /** * 数据是否为空 */ private boolean isEmpty() { return (mState == STATE_NONE && getAdapter().getItemCount() == 0) || (mState != STATE_NONE && getAdapter().getItemCount() == 1); } public boolean isLoadMoreEnable() { return mState != STATE_LOADING; } @IntDef({STATE_END, STATE_LOADING, STATE_EMPTY, STATE_NONE, STATE_PULL_TO_LOAD}) @Retention(RetentionPolicy.SOURCE) public @interface State { } private class OnLoadMoreListenerWrapper implements OnLoadMoreListener { private OnLoadMoreListener mOnLoadMoreListener; public OnLoadMoreListenerWrapper(OnLoadMoreListener onLoadMoreListener) { mOnLoadMoreListener = onLoadMoreListener; } @Override public void onLoadMore() { if (!mIsGettingData && !isLoadMoreEnable() && mOnLoadMoreListener != null) { mIsGettingData = true; mOnLoadMoreListener.onLoadMore(); } } } public class LoadMoreAdapter extends RecyclerView.Adapter { public static final int LOAD_MORE_VIEW_TYPE = -404; public static final int EMPTY_VIEW_TYPE = -403; public RecyclerView.Adapter mAdapter; public LoadMoreAdapter(Adapter adapter) { mAdapter = adapter; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == LOAD_MORE_VIEW_TYPE) { return new LoadMoreVH(); } else if (viewType == EMPTY_VIEW_TYPE) { return new EmptyVH(); } return mAdapter.onCreateViewHolder(parent, viewType); } @Override public void registerAdapterDataObserver(AdapterDataObserver observer) { super.registerAdapterDataObserver(observer); mAdapter.registerAdapterDataObserver(observer); } @Override public void unregisterAdapterDataObserver(AdapterDataObserver observer) { super.unregisterAdapterDataObserver(observer); mAdapter.unregisterAdapterDataObserver(observer); } @Override public void onBindViewHolder(ViewHolder holder, int position) { if (!isFootView(position)) { mAdapter.onBindViewHolder(holder, position); } else { if (getLayoutManager() instanceof StaggeredGridLayoutManager) { ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams(); if (layoutParams instanceof StaggeredGridLayoutManager.LayoutParams) { ((StaggeredGridLayoutManager.LayoutParams) layoutParams).setFullSpan(true); } } if (holder instanceof VH) { ((VH) holder).onBindViewHolder(); } } } private boolean isFootView(int position) { return position == getItemCount() - 1 && mState != STATE_NONE; } @Override public int getItemViewType(int position) { if (!isFootView(position)) { return mAdapter.getItemViewType(position); } else { if (mState == STATE_EMPTY && getItemCount() == 1) { return EMPTY_VIEW_TYPE; } else { return LOAD_MORE_VIEW_TYPE; } } } @Override public int getItemCount() { if (mState == STATE_NONE) { return mAdapter.getItemCount(); } else { return mAdapter.getItemCount() + 1; } } /** * 加载更多的ViewHolder */ private class LoadMoreVH extends VH { private View mItemView; public LoadMoreVH() { super(mFootItem.onCreateView(RecyclerViewWithFooter.this)); mItemView = itemView; } @Override public void onBindViewHolder() { super.onBindViewHolder(); if (mState == STATE_LOADING || mState == STATE_END || mState == STATE_PULL_TO_LOAD) { mFootItem.onBindData(mItemView, mState); } } } /** * 数据为空时的ViewHolder */ private class EmptyVH extends VH { public EmptyVH() { super(mEmptyItem.onCreateView(RecyclerViewWithFooter.this)); } @Override public void onBindViewHolder() { super.onBindViewHolder(); mEmptyItem.onBindData(itemView); } } class VH extends RecyclerView.ViewHolder { public VH(View itemView) { super(itemView); } public void onBindViewHolder() { } } } } ================================================ FILE: common_lib/src/main/res/layout/layout_error_view.xml ================================================