├── .gitignore
├── README.md
├── build.gradle
├── chapter3
├── .gitignore
├── build.gradle
├── fabric.properties
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── backstopmedia
│ │ └── kotlin
│ │ └── chapter3
│ │ ├── api
│ │ ├── ApiDemoJava.java
│ │ └── ApiDemoKotlin.kt
│ │ ├── hello
│ │ ├── HelloActivityJava.java
│ │ └── HelloActivityKotlin.kt
│ │ └── twitter
│ │ ├── Kallback.kt
│ │ └── TwitterExtensions.kt
│ └── res
│ ├── layout
│ └── activity_hello.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── chapter6
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ └── res
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── backstopmedia
│ └── kotlin
│ └── chapter6
│ ├── collections
│ ├── Arrays.kt
│ ├── Lists.kt
│ └── Maps.kt
│ └── generics
│ ├── Bounds.kt
│ └── Generics.kt
├── chapter7
├── build.gradle
└── src
│ └── test
│ └── kotlin
│ └── com
│ └── backstopmedia
│ └── kotlin
│ └── chapter7
│ ├── decompose.kt
│ ├── option.kt
│ ├── patterns.kt
│ ├── sequences.kt
│ └── various.kt
├── chapter8
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── backstopmedia
│ │ │ └── kotlin
│ │ │ └── chapter6
│ │ │ └── FindOperators.kt
│ └── res
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── backstopmedia
│ └── kotlin
│ └── chapter6
│ └── ExampleUnitTest.java
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── proguard-com.twitter.sdk.android.twitter.txt
├── settings.gradle
└── twitter-app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
└── main
├── AndroidManifest.xml
├── java
└── com
│ └── backstopmedia
│ └── kotlin
│ └── ktwitter
│ ├── KotlinApplication.kt
│ ├── api
│ └── KTwitterApiClient.kt
│ ├── entities
│ └── Entities.kt
│ ├── interactors
│ ├── FollowersInteractor.kt
│ ├── TopImagesInteractor.kt
│ ├── TopUsersInteractor.kt
│ └── UserInteractor.kt
│ ├── presenters
│ ├── FollowersPresenter.kt
│ ├── NavigationDrawerPresenter.kt
│ ├── Presenter.kt
│ ├── TopImagesPresenter.kt
│ └── TopUsersPresenter.kt
│ ├── ui
│ ├── NavigationHelper.kt
│ ├── activities
│ │ ├── FollowersActivity.kt
│ │ ├── LoginActivity.kt
│ │ ├── MainActivity.kt
│ │ ├── TimelineActivity.kt
│ │ ├── TopImagesActivity.kt
│ │ └── TopUsersActivity.kt
│ ├── adapter
│ │ ├── FollowersAdapter.kt
│ │ ├── FollowersWithHeadersAdapter.kt
│ │ ├── TopImagesAdapter.kt
│ │ └── TopUsersAdapter.kt
│ └── view
│ │ ├── FollowersView.kt
│ │ ├── NavigationDrawerView.kt
│ │ ├── TopImagesView.kt
│ │ └── TopUsersView.kt
│ └── utils
│ ├── BaseSubscriber.kt
│ ├── Kallback.kt
│ ├── MyTwitter.kt
│ ├── dsl
│ └── TweetDsl.kt
│ ├── functional
│ └── _Collections.kt
│ ├── glide
│ └── CircleTransformation.java
│ ├── os
│ └── _Intents.kt
│ └── twitter
│ ├── _Tweets.kt
│ └── _Users.kt
└── res
├── drawable-hdpi
├── background.jpg
├── ic_collections_black_24dp.png
├── ic_collections_bookmark_black_24dp.png
├── ic_people_black_24dp.png
├── ic_plus.png
├── kotlin_logo.png
└── retweet_light.png
├── drawable-mdpi
└── ic_people_black_24dp.png
├── drawable-xhdpi
└── ic_people_black_24dp.png
├── drawable-xxhdpi
└── ic_people_black_24dp.png
├── drawable-xxxhdpi
└── ic_people_black_24dp.png
├── layout
├── activity_coordinator_recycler.xml
├── activity_followers.xml
├── activity_login.xml
├── activity_timeline.xml
├── activity_top_images.xml
├── drawer_header.xml
├── grid_item_top_image.xml
├── list_item_follower.xml
├── list_item_header.xml
├── list_item_user.xml
└── navigation_drawer_base.xml
├── menu
└── navigation_view_items.xml
├── mipmap-hdpi
└── ic_launcher.png
├── mipmap-mdpi
└── ic_launcher.png
├── mipmap-xhdpi
└── ic_launcher.png
├── mipmap-xxhdpi
└── ic_launcher.png
├── mipmap-xxxhdpi
└── ic_launcher.png
└── values
├── colors.xml
├── dimens.xml
├── strings.xml
├── strings_accessibility.xml
└── styles.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | # built application files
2 | *.apk
3 | *.ap_
4 |
5 | # files for the dex VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # generated files
12 | gen/
13 |
14 | # Local configuration file (sdk path, etc)
15 | local.properties
16 |
17 | # Eclipse project files
18 | .classpath
19 | .project
20 |
21 | # Android Studio
22 | .idea
23 | .gradle
24 | /*/local.properties
25 | /*/out
26 | /*/build
27 | /*/*/build
28 | /*/*/production
29 | *.iml
30 | *.iws
31 | *.ipr
32 | *~
33 | *.swp
34 | .DS_Store
35 | .keys
36 |
37 | build
38 | out.map
39 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # kotlin
2 | Kotlin Bleeding Edge Book Example
3 |
4 | Need to add a detailed description
5 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.0.0-beta-1103'
5 | ext.anko_version = '0.7.2'
6 | repositories {
7 | jcenter()
8 | maven { url 'https://maven.fabric.io/public' }
9 | }
10 | dependencies {
11 | classpath 'com.android.tools.build:gradle:1.3.1'
12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
13 | classpath 'io.fabric.tools:gradle:1.+'
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | jcenter()
20 | maven { url 'https://maven.fabric.io/public' }
21 | }
22 | }
23 |
24 | task clean(type: Delete) {
25 | delete rootProject.buildDir
26 | }
27 |
--------------------------------------------------------------------------------
/chapter3/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/chapter3/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 |
4 | buildscript {
5 | repositories {
6 | jcenter()
7 | }
8 | dependencies {
9 | classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
10 | }
11 | }
12 |
13 | android {
14 | compileSdkVersion 23
15 | buildToolsVersion "23.0.1"
16 |
17 | defaultConfig {
18 | applicationId "com.backstopmedia.kotlin.chapter1"
19 | minSdkVersion 16
20 | targetSdkVersion 23
21 | versionCode 1
22 | versionName "1.0"
23 | }
24 | buildTypes {
25 | release {
26 | minifyEnabled false
27 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
28 | }
29 | }
30 | }
31 |
32 | dependencies {
33 | compile fileTree(dir: 'libs', include: ['*.jar'])
34 | compile 'com.android.support:appcompat-v7:23.0.1'
35 | compile 'com.android.support:recyclerview-v7:23.0.1'
36 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
37 | compile('com.twitter.sdk.android:twitter:1.8.0@aar') {
38 | transitive = true;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/chapter3/fabric.properties:
--------------------------------------------------------------------------------
1 | #Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public.
2 | #Mon Oct 12 11:22:53 PDT 2015
3 | apiSecret=b811d7a69452a60ba82cfcef6ab416a5f10172a4f04c3958e57781966faf67b9
4 |
--------------------------------------------------------------------------------
/chapter3/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/asarazan/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/chapter3/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
12 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/chapter3/src/main/java/com/backstopmedia/kotlin/chapter3/api/ApiDemoJava.java:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter3.api;
2 |
3 | import android.util.Log;
4 |
5 | import com.twitter.sdk.android.Twitter;
6 | import com.twitter.sdk.android.core.AppSession;
7 | import com.twitter.sdk.android.core.Callback;
8 | import com.twitter.sdk.android.core.Result;
9 | import com.twitter.sdk.android.core.TwitterException;
10 | import com.twitter.sdk.android.core.models.Search;
11 |
12 | public class ApiDemoJava {
13 |
14 | public static void basicSearch() {
15 | Twitter.getInstance().core.logInGuest(new Callback() {
16 | @Override
17 | public void success(Result result) {
18 | Twitter.getApiClient().getSearchService().tweets("Kotlin", null, null, null, null, null, null, null, null, null, new Callback() {
19 | @Override
20 | public void success(Result result) {
21 | int tweetCount = result.data.tweets.size();
22 | Log.i("ApiDemoKotlin", "Found " + tweetCount + " tweets.");
23 | }
24 |
25 | @Override
26 | public void failure(TwitterException e) {
27 | }
28 | });
29 | }
30 |
31 | @Override
32 | public void failure(TwitterException e) {
33 | }
34 | });
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/chapter3/src/main/java/com/backstopmedia/kotlin/chapter3/api/ApiDemoKotlin.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter3.api
2 |
3 | import android.util.Log
4 | import com.backstopmedia.kotlin.chapter3.twitter.kallback
5 | import com.backstopmedia.kotlin.chapter3.twitter.tweets
6 | import com.twitter.sdk.android.Twitter
7 |
8 | object ApiDemoKotlin {
9 |
10 | fun basicSearch() {
11 | Twitter.getInstance().core.logInGuest(kallback {
12 | Twitter.getApiClient().searchService.tweets("Kotlin", callback = kallback {
13 | Log.i("ApiDemoKotlin", "Found ${it.data.tweets.size} tweets.")
14 | })
15 | })
16 | }
17 | }
--------------------------------------------------------------------------------
/chapter3/src/main/java/com/backstopmedia/kotlin/chapter3/hello/HelloActivityJava.java:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter3.hello;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.view.View;
6 | import android.widget.Button;
7 | import android.widget.EditText;
8 |
9 | import com.backstopmedia.kotlin.chapter3.R;
10 |
11 | import static android.view.View.OnClickListener;
12 |
13 | public class HelloActivityJava extends AppCompatActivity {
14 |
15 | @Override
16 | protected void onCreate(Bundle savedInstanceState) {
17 | super.onCreate(savedInstanceState);
18 | setContentView(R.layout.activity_hello);
19 |
20 | final EditText editText = (EditText) findViewById(R.id.editText);
21 | final Button button = (Button) findViewById(R.id.button);
22 |
23 | button.setOnClickListener(new OnClickListener() {
24 | @Override
25 | public void onClick(View v) {
26 | String name = editText.getText().toString();
27 | button.setText("Hello " + name + "!");
28 | }
29 | });
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/chapter3/src/main/java/com/backstopmedia/kotlin/chapter3/hello/HelloActivityKotlin.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter3.hello
2 |
3 | import android.os.Bundle
4 | import android.support.v7.app.AppCompatActivity
5 | import com.backstopmedia.kotlin.chapter3.R
6 | import kotlinx.android.synthetic.activity_hello.button
7 | import kotlinx.android.synthetic.activity_hello.editText
8 |
9 | class HelloActivityKotlin : AppCompatActivity() {
10 |
11 | override fun onCreate(savedInstanceState: Bundle?) {
12 | super.onCreate(savedInstanceState)
13 | setContentView(R.layout.activity_hello)
14 | button.setOnClickListener {
15 | val name = editText.text.toString()
16 | button.text = "Hello $name!"
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/chapter3/src/main/java/com/backstopmedia/kotlin/chapter3/twitter/Kallback.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter3.twitter
2 |
3 | import android.util.Log
4 | import com.twitter.sdk.android.core.Callback
5 | import com.twitter.sdk.android.core.Result
6 | import com.twitter.sdk.android.core.TwitterException
7 |
8 | /**
9 | * A convenience method for generating callbacks.
10 | *
11 | * @param onSuccess block to call on successful return
12 | * @return A [Callback] object with basic error logging.
13 | */
14 | fun kallback(onSuccess: (Result) -> Unit = {}): Kallback {
15 | return Kallback(onSuccess).onFail {
16 | Log.w("kallback", "Something went wrong: $it")
17 | }
18 | }
19 |
20 | /**
21 | * A streamlined subclass of [Callback] with optional failure behavior.
22 | *
23 | * @param T the response type, passed up to [Callback]
24 | * @param onSuccess block to call on successful return
25 | * @see onFail for optional fail block.
26 | */
27 | open class Kallback(private val onSuccess: (Result) -> Unit) : Callback() {
28 |
29 | private var onFail: ((TwitterException) -> Unit)? = null
30 |
31 | /**
32 | * Sets failure behavior. Can be chained from [kallback] or constructor.
33 | *
34 | * @param onFail block to run on failed request.
35 | */
36 | fun onFail(onFail: (TwitterException) -> Unit): Kallback {
37 | this.onFail = onFail
38 | return this
39 | }
40 |
41 | override fun success(result: Result) {
42 | onSuccess.invoke(result)
43 | }
44 |
45 | override fun failure(exception: TwitterException) {
46 | onFail?.invoke(exception)
47 | }
48 | }
--------------------------------------------------------------------------------
/chapter3/src/main/java/com/backstopmedia/kotlin/chapter3/twitter/TwitterExtensions.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter3.twitter
2 |
3 | import com.twitter.sdk.android.core.Callback
4 | import com.twitter.sdk.android.core.models.Search
5 | import com.twitter.sdk.android.core.services.SearchService
6 | import com.twitter.sdk.android.core.services.params.Geocode
7 |
8 | /**
9 | * Extension function for tweets method on [SearchService]
10 | *
11 | * Provides default values for all params except [callback]
12 | */
13 | fun SearchService.tweets(query: String? = null,
14 | geocode: Geocode? = null,
15 | lang: String? = null,
16 | locale: String? = null,
17 | resultType: String? = null,
18 | count: Int? = null,
19 | until: String? = null,
20 | sinceId: Long? = null,
21 | maxId: Long? = null,
22 | includeEntities: Boolean? = null,
23 | callback: Callback)
24 | {
25 | return tweets(query, geocode, lang, locale, resultType, count, until, sinceId, maxId, includeEntities, callback)
26 | }
27 |
--------------------------------------------------------------------------------
/chapter3/src/main/res/layout/activity_hello.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
15 |
16 |
23 |
24 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/chapter3/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter3/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter3/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter3/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter3/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter3/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter3/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter3/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter3/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter3/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter3/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/chapter3/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 |
5 |
--------------------------------------------------------------------------------
/chapter3/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Chapter 3
3 | Enter your name and press the button:
4 | Enter your name
5 | Press Me!
6 |
7 |
--------------------------------------------------------------------------------
/chapter3/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/chapter6/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/chapter6/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 |
4 | android {
5 | compileSdkVersion 23
6 | buildToolsVersion "23.0.1"
7 |
8 | defaultConfig {
9 | applicationId "com.backstopmedia.kotlin.chapter6"
10 | minSdkVersion 16
11 | targetSdkVersion 23
12 | versionCode 1
13 | versionName "1.0"
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | compile fileTree(dir: 'libs', include: ['*.jar'])
25 | testCompile 'junit:junit:4.12'
26 | compile 'com.android.support:appcompat-v7:23.1.0'
27 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
28 | }
29 |
--------------------------------------------------------------------------------
/chapter6/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/asarazan/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/chapter6/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/chapter6/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter6/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter6/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter6/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter6/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter6/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter6/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter6/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter6/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter6/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter6/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/chapter6/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | chapter6
3 |
4 |
--------------------------------------------------------------------------------
/chapter6/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/chapter6/src/test/java/com/backstopmedia/kotlin/chapter6/collections/Arrays.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter6.collections
2 |
3 | import org.junit.Test
4 |
5 | class Arrays {
6 |
7 | /**
8 | * You're tearing me apart with your amazing syntax, [Array]!
9 | * We are using [Array.asList] because Array doesn't have a good [toString] method.
10 | */
11 | @Test fun arrayInit() {
12 | val someStrings = arrayOf("Oh", "hai", "Mark!")
13 | println("someStrings is ${someStrings.asList()}")
14 | }
15 |
16 | @Test fun initNulls() {
17 | val initLater: Array = arrayOfNulls(5)
18 | println("initLater is ${initLater.asList()}")
19 | }
20 |
21 | /**
22 | * This will be of boxed type Array on the JVM
23 | * Read on to see how primitive arrays are handled.
24 | */
25 | @Test fun initBlock() {
26 | val blockArray: Array = Array(3) { it }
27 | println("Block array is ${blockArray.asList()}")
28 | }
29 |
30 | /**
31 | * The primitive array types, such as [LongArray], are technically
32 | * not subtypes of [Array], but they have the same methods.
33 | * This array will be represented as long[] on the JVM.
34 | */
35 | @Test fun primitives() {
36 | val longs = longArrayOf(1L, 2L, 3L)
37 | println("Long array is $longs")
38 | }
39 | }
--------------------------------------------------------------------------------
/chapter6/src/test/java/com/backstopmedia/kotlin/chapter6/collections/Lists.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter6.collections
2 |
3 | import org.junit.Test
4 |
5 | class Lists {
6 |
7 | /**
8 | * [String] is magically converted to [java.lang.String] when needed.
9 | */
10 | @Test fun kotlinStrings() {
11 | val logMessage: kotlin.String = "Something has occurred."
12 | System.out.println(logMessage) // This method expects java.lang.String
13 | }
14 |
15 | /**
16 | * [List] is immutable and has no add or put methods.
17 | * list[1] resolves to [List.get]
18 | */
19 | @Test fun lists() {
20 | val list = listOf("do", "re", "mi") // List
21 | // list.add("fa") // Compilation Failure. No such method.
22 | val re = list[1]
23 | println("list[1] is $re")
24 | }
25 |
26 | /**
27 | * If you want a mutable list, [ArrayList] is your best bet.
28 | * list[1] resolves to [MutableList.set]
29 | */
30 | @Test fun arrayLists() {
31 | val foobar = arrayListOf("foo", "bar")
32 | foobar[1] = "baz"
33 | println("foobar is actually $foobar") // foo baz
34 | }
35 |
36 | /**
37 | * You can also use operators for removal and addition.
38 | * This will create new immutable lists, rather than mutating the original.
39 | */
40 | @Test fun operators() {
41 | val foobar = listOf("foo", "bar")
42 | val football = (foobar - "bar" + "tball").joinToString("")
43 | println("We can also turn foobar into $football")
44 | println("But the original will always be $foobar!")
45 | }
46 |
47 | /**
48 | * You can easily convert one list into another using [List.map]
49 | * Sorting is also easily accomplished.
50 | */
51 | @Test fun fmap() {
52 | val animals = listOf("walrus", "eel", "giraffe")
53 | val lengths = animals.map { it.length }
54 | println("lengths are $lengths")
55 | }
56 |
57 | }
--------------------------------------------------------------------------------
/chapter6/src/test/java/com/backstopmedia/kotlin/chapter6/collections/Maps.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter6.collections
2 |
3 | import org.junit.Test
4 |
5 | public class Maps {
6 |
7 | /**
8 | * Map has a pretty nice initializer syntax.
9 | * Technically it leverages extension methods to create [Pair] objects.
10 | */
11 | @Test fun mapInit() {
12 | val map = mapOf(
13 | 1L to "one",
14 | 2L to "two")
15 | println("Here's some numbers: $map")
16 | }
17 |
18 | }
--------------------------------------------------------------------------------
/chapter6/src/test/java/com/backstopmedia/kotlin/chapter6/generics/Bounds.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter6.generics
2 |
3 | class Bounds {
4 |
5 | fun test() {
6 | val ints = rocketListOf(1, 2, 3)
7 | val objects: RocketList = ints
8 | }
9 |
10 | }
11 |
12 |
13 | interface RocketList {
14 | fun get(i: Int): T
15 | }
16 |
17 | fun rocketListOf(vararg items: T): RocketList {
18 | return object: RocketList {
19 | override fun get(i: Int): T = items[i]
20 | }
21 | }
--------------------------------------------------------------------------------
/chapter6/src/test/java/com/backstopmedia/kotlin/chapter6/generics/Generics.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter6.generics
2 |
3 | import org.junit.Test
4 |
5 |
6 | class Generics {
7 |
8 | /**
9 | * Our [description] extension method declares an upper bound of [Number].
10 | * This means that you can't use the method on anything that doesn't
11 | * inherit from or implement that class/interface.
12 | */
13 | @Test fun upperBounds() {
14 | val something = 100
15 | println(something.description())
16 |
17 | val nothing: Int? = null
18 | println(nothing.description())
19 |
20 | val notNumber = "You're tearing me apart"
21 | // println(notNumber.description()) // Not valid for this receiver.
22 | }
23 |
24 | }
25 |
26 | /**
27 | * A null-safe toString wrapper for numbers. Works on any kind of number, null or not.
28 | */
29 | fun T?.description(): String? {
30 | return if (this == null) "null" else "${this.javaClass.simpleName}: $this"
31 | }
32 |
--------------------------------------------------------------------------------
/chapter7/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'kotlin'
2 |
3 | buildscript {
4 | repositories {
5 | mavenCentral()
6 | }
7 | dependencies {
8 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
9 | }
10 | }
11 |
12 |
13 | dependencies {
14 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
15 |
16 | testCompile 'junit:junit:4.12'
17 | }
18 |
--------------------------------------------------------------------------------
/chapter7/src/test/kotlin/com/backstopmedia/kotlin/chapter7/decompose.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter7
2 |
3 | import org.junit.Test
4 |
5 | @Suppress("UNUSED_VARIABLE")
6 | class DecomposeTest {
7 | @Test fun decomposeClass() {
8 | class Person(val name: String, val age: Int) {
9 | operator fun component1(): String = name
10 | operator fun component2(): Int = age
11 | }
12 | val (name, age) = Person("Christina Rudloff", 29)
13 | }
14 |
15 | @Test fun decomposeDataClass() {
16 | data class Person(val name: String, val age: Int)
17 | val (name, age) = Person("Troy Mott", 31)
18 | }
19 |
20 | @Test fun decomposeArray() {
21 | val (a, b, c) = arrayOf(1, 2, 3)
22 | }
23 |
24 | @Test fun decomposeList() {
25 | val (a, b, c) = listOf(1, 2, 3)
26 | }
27 |
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/chapter7/src/test/kotlin/com/backstopmedia/kotlin/chapter7/option.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter7
2 |
3 | import org.junit.Test
4 |
5 |
6 | @Suppress("UNUSED_VARIABLE")
7 | class OptionTest {
8 |
9 |
10 | @Test fun optionWhen() {
11 | val values = mapOf(1 to "one", 2 to "two", 3 to "three")
12 | val option = values.optional(4)
13 | val msg = when (option) {
14 | is Option.Some -> "Some[${option.value}]"
15 | is Option.None -> "Nothing"
16 | }
17 | println(msg)
18 | }
19 |
20 | @Test fun optionMap() {
21 | val values = mapOf(1 to 3, 2 to 6)
22 | val opt1 = values.optional(1)
23 | val opt2 = opt1.map { it * 2 }
24 | val opt3 = opt2.map { it + 4 }
25 |
26 | when (opt3) {
27 | is Option.Some -> println(opt3.value)
28 | }
29 | }
30 |
31 | @Test fun optionApply() {
32 | val optionVal = Option.of(3)
33 | val optionFn = Option.of({ n: Int -> n * 2 })
34 | val option = optionVal.apply(optionFn)
35 |
36 | when (option) {
37 | is Option.Some -> println(option.value)
38 | }
39 | }
40 |
41 | @Test fun optionBind() {
42 | val optionVal = Option.of(4)
43 | val fn = fun(n: Int) = if (n and 1 == 0) Option.Some(n) else Option.None.of()
44 | val option = optionVal.bind(fn)
45 |
46 | when (option) {
47 | is Option.Some -> println(option.value)
48 | }
49 | }
50 |
51 | }
52 |
53 |
54 | sealed class Option {
55 | companion object {
56 | fun of(value: T?): Option =
57 | if (value != null) Option.Some(value) else Option.None.of()
58 | }
59 |
60 | abstract fun map(functor: (T) -> R): Option
61 | abstract fun apply(applicative: Option<(T) -> R>): Option
62 | abstract fun bind(fn: (T) -> Option): Option
63 |
64 | class Some(val value: T) : Option() {
65 |
66 | override fun apply(applicative: Option<(T) -> R>): Option = when (applicative) {
67 | is Some -> Some(applicative.value(value))
68 | is None -> None.of()
69 | }
70 |
71 | override fun map(functor: (T) -> R): Some = Some(functor(value))
72 | override fun bind(fn: (T) -> Option): Option = fn(value)
73 | }
74 |
75 |
76 | class None private constructor() : Option() {
77 |
78 |
79 | companion object {
80 | private val instance = None()
81 |
82 | @Suppress("CAST_NEVER_SUCCEEDS")
83 | fun of(): None = instance as None
84 | }
85 |
86 | override fun apply(applicative: Option<(T) -> R>): None = None.of()
87 | override fun map(functor: (T) -> R): None = None.of()
88 | override fun bind(fn: (T) -> Option): None = None.of()
89 | }
90 | }
91 |
92 | fun Map.optional(key: K): Option = Option.of(this[key])
--------------------------------------------------------------------------------
/chapter7/src/test/kotlin/com/backstopmedia/kotlin/chapter7/patterns.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter7
2 |
3 | import org.junit.Test
4 |
5 | @Suppress("UNUSED_VARIABLE")
6 | class PatternMatchingTest {
7 |
8 |
9 | @Test fun valueMatch() {
10 | val x: Any = "hello"
11 | when (x) {
12 | 1 -> println("just 1")
13 | "hello" -> println("hello indeed")
14 | else -> println("no match]")
15 | }
16 | }
17 |
18 | @Test fun rangeMatch() {
19 | val x = 5
20 | when (x) {
21 | in 0..4 -> println("0..4")
22 | in 5..9 -> println("5..9")
23 | else -> println("negative")
24 | }
25 | }
26 |
27 |
28 | @Test fun typeMatch() {
29 | val x: Any = "hello"
30 | when (x) {
31 | is Int -> println("Int[$x]")
32 | is List<*> -> println("List[${x.size}]")
33 | is String -> println("String[${x.length}]")
34 | }
35 | }
36 |
37 | @Test fun typeMatchExpression() {
38 | val x: Any = "hello"
39 | val s = when (x) {
40 | is Int -> "Int[$x]"
41 | is List<*> -> "List[${x.size}]"
42 | is String -> "String[${x.length}]"
43 | else -> "Any[$x]"
44 | }
45 | }
46 |
47 | @Test fun elseMatch() {
48 | val x: Any = "hello"
49 | when (x) {
50 | is Int -> println("Int[$x]")
51 | is List<*> -> println("List[${x.size}]")
52 | is String -> println("String[${x.length}]")
53 | else -> println("Any[$x]")
54 | }
55 | }
56 |
57 | @Test fun sealedMatch() {
58 | fun number(foo: Foo): Int = when (foo) {
59 | is Foo.Bar -> 3
60 | is Foo.Baz -> 6
61 | }
62 |
63 | println(number(Foo.Bar("hi")))
64 | }
65 |
66 | }
67 |
68 | @Suppress("UNUSED_PARAMETER")
69 | sealed class Foo {
70 | class Bar(value: String) : Foo()
71 | class Baz(value: Int) : Foo()
72 | }
73 |
74 |
75 |
76 |
77 |
78 |
--------------------------------------------------------------------------------
/chapter7/src/test/kotlin/com/backstopmedia/kotlin/chapter7/sequences.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter7
2 |
3 | import org.junit.Test
4 |
5 | @Suppress("UNUSED_VARIABLE")
6 | class SequenceTest {
7 |
8 | @Test fun createSequenceOfArray() {
9 | val seq = arrayOf(1, 2, 3).asSequence()
10 | }
11 |
12 | @Test fun createSequenceOfList() {
13 | val seq = listOf(1, 2, 3).asSequence()
14 | }
15 |
16 | @Test fun createSequenceOfValues() {
17 | val seq = sequenceOf(1, 2, 3)
18 | }
19 |
20 | @Test fun createSequenceOfProgression() {
21 | val seq = sequenceOf(1..10)
22 | seq.printElements()
23 | }
24 |
25 | @Test fun createSequenceByFunction() {
26 | var i = 0
27 | val seq = sequence { ++i }
28 | }
29 |
30 | @Test fun createSequenceBy() {
31 | var i = 0
32 | val seq = sequence(i) { ++i + it }
33 | }
34 |
35 | @Test fun map() {
36 | val seq = sequenceOf(1, 2, 3).map { it * 2 }
37 | seq.printElements()
38 | }
39 |
40 | @Test fun filter() {
41 | val seq = sequenceOf(1, 2, 3, 4, 5, 6).filter { it and 1 == 0 }
42 | seq.printElements()
43 | }
44 |
45 | @Test fun distinct() {
46 | val seq = sequenceOf(1, 2, 1).distinct()
47 | seq.printElements()
48 | }
49 | }
50 |
51 |
52 | fun Sequence.printElements() {
53 | val sb = StringBuilder()
54 | sb.append("[")
55 | forEach {
56 | if (sb.length > 1) sb.append(", ")
57 | sb.append(it)
58 | }
59 | sb.append("]")
60 | println(sb)
61 | }
--------------------------------------------------------------------------------
/chapter7/src/test/kotlin/com/backstopmedia/kotlin/chapter7/various.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter7
2 |
3 | import org.junit.Test
4 |
5 | @Suppress("UNUSED_VARIABLE")
6 | class VariousTest {
7 |
8 | @Test fun letFn() {
9 |
10 | val x = Point(1, 2).let {
11 | val p = Point(3,4)
12 | it.x + p.x
13 | }
14 | }
15 |
16 | @Test fun nullableLetFn() {
17 |
18 | val point : Point? = Point(1, 2)
19 |
20 | val x : Int? = point?.let {
21 | val p = Point(3,4)
22 | it.x + p.x
23 | }
24 | }
25 |
26 | @Test fun withFn() {
27 | val point3D : Point3D = with(Point(1, 2)) {
28 | Point3D(x, y, 3)
29 | }
30 |
31 | }
32 |
33 | @Test fun applyFn() {
34 | val point : Point = Point(1, 2).apply {
35 | val msg = "Point ($x, $y)"
36 | println(msg)
37 | }
38 | }
39 |
40 |
41 | }
42 |
43 | data class Point(val x: Int, val y: Int)
44 |
45 | data class Point3D(val x: Int, val y: Int, val z: Int)
46 |
47 |
--------------------------------------------------------------------------------
/chapter8/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/chapter8/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.1"
6 |
7 | defaultConfig {
8 | applicationId "com.backstopmedia.kotlin.chapter6"
9 | minSdkVersion 16
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.0.1'
26 | compile 'io.reactivex:rxjava:1.0.14'
27 | }
28 |
--------------------------------------------------------------------------------
/chapter8/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/asarazan/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/chapter8/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/chapter8/src/main/java/com/backstopmedia/kotlin/chapter6/FindOperators.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter6
2 |
3 | import android.app.Activity
4 | import android.support.annotation.IdRes
5 | import android.support.v4.app.Fragment
6 | import android.support.v4.app.FragmentManager
7 | import android.view.View
8 | import android.view.ViewGroup
9 |
10 |
11 | @Suppress("UNCHECKED_CAST")
12 | operator fun Activity.get(resId: Int): T {
13 | return findViewById(resId) as T
14 | }
15 |
16 | @Suppress("UNCHECKED_CAST")
17 | operator fun FragmentManager.get(key: String): T? {
18 | return findFragmentByTag(key) as T
19 | }
20 |
21 | operator fun rx.subscriptions.CompositeSubscription.plus(other: rx.Subscription): Unit {
22 | add(other)
23 | }
24 |
25 | @Suppress("UNCHECKED_CAST")
26 | operator fun ViewGroup.get(@IdRes resId: Int): T {
27 | return findViewById(resId) as T
28 | }
--------------------------------------------------------------------------------
/chapter8/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter8/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter8/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter8/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter8/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter8/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter8/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter8/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter8/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/chapter8/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/chapter8/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/chapter8/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | chapter6
3 |
4 |
--------------------------------------------------------------------------------
/chapter8/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/chapter8/src/test/java/com/backstopmedia/kotlin/chapter6/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.chapter6;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Oct 06 20:17:52 PDT 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/proguard-com.twitter.sdk.android.twitter.txt:
--------------------------------------------------------------------------------
1 | # Twitter Core proguard configuration
2 | # '-include' this file in your proguard config
3 | # Autogenerated file -- Do not modify
4 |
5 | #Proguard Config for when AppCompat is not a dependency
6 | -dontwarn com.digits.sdk.android.*ActionBarActivity
7 |
8 | # retrofit specific
9 | -dontwarn com.squareup.okhttp.**
10 | -dontwarn com.google.appengine.api.urlfetch.**
11 | -dontwarn rx.**
12 | -dontwarn retrofit.**
13 | -keepattributes Signature
14 | -keepattributes *Annotation*
15 | -keep class com.squareup.okhttp.** { *; }
16 | -keep interface com.squareup.okhttp.** { *; }
17 | -keep class retrofit.** { *; }
18 | -keepclasseswithmembers class * {
19 | @retrofit.http.* ;
20 | }
21 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':chapter3'
2 | include ':twitter-app'
3 | include ':chapter6'
4 | include ':chapter7' // Functional Programming
5 | include ':chapter8'
6 |
--------------------------------------------------------------------------------
/twitter-app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/twitter-app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 |
4 | buildscript {
5 | repositories {
6 | jcenter()
7 | }
8 | dependencies {
9 | classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
10 | }
11 | }
12 |
13 | android {
14 | compileSdkVersion 23
15 | buildToolsVersion "23.0.1"
16 |
17 | defaultConfig {
18 | applicationId "com.backstopmedia.kotlin.chapter4"
19 | minSdkVersion 16
20 | targetSdkVersion 23
21 | versionCode 1
22 | versionName "1.0"
23 | }
24 | buildTypes {
25 | release {
26 | minifyEnabled false
27 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
28 | }
29 | }
30 | android {
31 | lintOptions {
32 | abortOnError false
33 | }
34 | }
35 | }
36 |
37 | dependencies {
38 | compile fileTree(dir: 'libs', include: ['*.jar'])
39 | compile 'com.android.support:appcompat-v7:23.0.1'
40 | compile 'com.android.support:design:23.0.1'
41 | compile 'com.android.support:recyclerview-v7:23.0.1'
42 | compile 'com.android.support:cardview-v7:23.0.1'
43 | compile 'com.github.bumptech.glide:glide:3.6.1'
44 | compile 'com.android.support:support-v4:23.0.1'
45 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
46 | compile "org.jetbrains.anko:anko-sdk15:$anko_version"
47 | compile "org.jetbrains.anko:anko-support-v4:$anko_version"
48 | compile 'io.reactivex:rxjava:1.0.15'
49 | compile 'io.reactivex:rxandroid:1.0.1'
50 | // compile 'io.reactivex:rxkotlin:0.22.14'
51 | compile('com.twitter.sdk.android:twitter:1.8.0@aar') {
52 | transitive = true;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/twitter-app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/aaronsarazan/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/twitter-app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
14 |
15 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
29 |
30 |
33 |
34 |
37 |
38 |
41 |
42 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/KotlinApplication.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter
2 |
3 | import android.app.Application
4 | import com.backstopmedia.kotlin.ktwitter.utils.MyTwitter
5 | import com.twitter.sdk.android.Twitter
6 | import com.twitter.sdk.android.core.TwitterAuthConfig
7 | import io.fabric.sdk.android.Fabric
8 |
9 | class KotlinApplication : Application() {
10 |
11 | override fun onCreate() {
12 | super.onCreate()
13 | Fabric.with(this, Twitter(TwitterAuthConfig(MyTwitter.KEY, MyTwitter.SECRET)))
14 | }
15 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/api/KTwitterApiClient.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.api
2 |
3 | import com.backstopmedia.kotlin.ktwitter.entities.UserIdList
4 | import com.twitter.sdk.android.core.Callback
5 | import com.backstopmedia.kotlin.ktwitter.entities.UsersList
6 | import com.twitter.sdk.android.core.TwitterApiClient
7 | import com.twitter.sdk.android.core.TwitterSession
8 | import com.twitter.sdk.android.core.models.Tweet
9 | import com.twitter.sdk.android.core.models.User
10 | import retrofit.http.GET
11 | import retrofit.http.POST
12 | import retrofit.http.Path
13 | import retrofit.http.Query
14 | import rx.Observable
15 |
16 | class KTwitterApiClient(val session: TwitterSession) : TwitterApiClient(session) {
17 |
18 | val kTwitterApi: KTwitterApi by lazy { getService(KTwitterApi::class.java) }
19 | }
20 |
21 | interface KTwitterApi {
22 |
23 | @GET("/1.1/statuses/home_timeline.json")
24 | fun homeTimeline(@Query("count") count: Int = 20,
25 | @Query("trim_user") trimUser: Boolean = true,
26 | @Query("exclude_replies") excludeReplies: Boolean = true,
27 | @Query("contributor_details") contributorDetails: Boolean = true,
28 | @Query("include_entities") includeEntities: Boolean = true): Observable>
29 |
30 | @GET("/1.1/statuses/user_timeline.json")
31 | fun userTimeline(@Query("user_id") user: Long,
32 | @Query("count") count: Int? = null): Observable>
33 |
34 | @GET("/1.1/users/show.json")
35 | fun getUser(@Query("screen_name") screenName: String, @Query("include_entities") includeEntities: Boolean = true): Observable
36 |
37 | @GET("/1.1/favorites/list.json")
38 | fun getFaves(@Query("user_id") user: Long,
39 | @Query("count") count: Int? = null): Observable>
40 |
41 | @GET("/1.1/friends/ids.json")
42 | fun getFollowing(@Query("user_id") user: Long): Observable
43 |
44 | @GET("/1.1/followers/list.json")
45 | fun getFollowers(@Query("user_id") user: Long, @Query("count") count: Int? = null): Observable
46 |
47 | @POST("/1.1/friendships/create.json")
48 | fun follow(@Query("user_id") user: Long, @Query("follow") follow: Boolean): Observable
49 | }
50 |
51 | fun KTwitterApi.getRetweets(user: Long, count: Int? = null): Observable> {
52 | return userTimeline(user, count).map { it.map { it.retweetedStatus }.filterNotNull() }
53 | }
54 |
55 | fun KTwitterApi.getFollowingIds(user: Long): Observable> {
56 | return getFollowing(user).map { it.ids.toSet() }
57 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/entities/Entities.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.entities
2 |
3 | import com.google.gson.annotations.SerializedName
4 | import com.twitter.sdk.android.core.models.Tweet
5 | import com.twitter.sdk.android.core.models.User
6 |
7 | data class Image(val title: String, val retweetCount: Int, val mediaUrl: String) {
8 |
9 | companion object {
10 | fun fromTweet(tweet: Tweet): Image {
11 | val title = tweet.text?.split("http")?.firstOrNull() ?: ""
12 | val url = tweet.entities?.media?.firstOrNull()?.mediaUrl?.concat(":large") ?: ""
13 | return Image(title, tweet.retweetCount, url)
14 | }
15 | }
16 | }
17 |
18 | data class Profile(val handle: String, val avatarUrl: String) {
19 |
20 | companion object {
21 | fun fromUser(user: User): Profile = with(user) {
22 | Profile(handle = "@$screenName", avatarUrl = profileImageUrl.replace("_normal", ""))
23 | }
24 | }
25 | }
26 |
27 | /**
28 | * A User object, with FaveRank™ technology
29 | *
30 | * We've also added a [following] boolean, which is mutable so that we don't have to
31 | * hit the server again just to reflect that a follow operation succeeded.
32 | */
33 | data class RankedUser(val user: User, val rank: Int, var following: Boolean) {
34 |
35 | companion object {
36 |
37 | /**
38 | * Retweets are worth twice as much as faves.
39 | */
40 | fun fromRetweets(user: User, tweets: List, following: Set): RankedUser {
41 | return RankedUser(user, tweets.size * 2, user.id in following)
42 | }
43 |
44 | /**
45 | * Faves are still pretty good.
46 | */
47 | fun fromFaves(user: User, tweets: List, following: Set): RankedUser {
48 | return RankedUser(user, tweets.size, user.id in following)
49 | }
50 | }
51 |
52 | operator fun plus(other: RankedUser?): RankedUser {
53 | if (other == null) return this
54 | if (user.id != other.user.id) throw IllegalArgumentException("Illegal attempt to combine user ${user.id} with ${other.user.id}")
55 | return RankedUser(user, rank + other.rank, following || other.following)
56 | }
57 |
58 | override fun equals(other: Any?): Boolean {
59 | return other is RankedUser && other.user.id == user.id
60 | }
61 |
62 | override fun hashCode(): Int {
63 | return user.id.hashCode()
64 | }
65 | }
66 |
67 | /**
68 | * Gson object for a list of user ids.
69 | */
70 | open class UserIdList {
71 |
72 | @JvmField
73 | @SerializedName("ids")
74 | var ids: List = listOf()
75 |
76 | }
77 |
78 | data class FollowingUser(val user: User, val followed: Boolean)
79 |
80 | class UsersList {
81 |
82 | @JvmField
83 | @SerializedName("users")
84 | var users: List = listOf()
85 |
86 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/interactors/FollowersInteractor.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.interactors
2 |
3 | import com.backstopmedia.kotlin.ktwitter.api.KTwitterApi
4 | import com.backstopmedia.kotlin.ktwitter.api.KTwitterApiClient
5 | import com.backstopmedia.kotlin.ktwitter.entities.FollowingUser
6 | import com.twitter.sdk.android.core.TwitterSession
7 | import com.twitter.sdk.android.core.models.User
8 | import rx.Observable
9 |
10 | interface FollowersInteractor {
11 | fun getFollowers(userId: Long): Observable>
12 | }
13 |
14 | class FollowersInteractorImpl(val session: TwitterSession) : FollowersInteractor {
15 |
16 | private val kTwitterApi: KTwitterApi = KTwitterApiClient(session).kTwitterApi
17 |
18 | override fun getFollowers(userId: Long): Observable> {
19 | return kTwitterApi.getFollowers(userId, count = 200).map {
20 | it.users.sortedBy { it.name.toLowerCase() }
21 | }.zipWith(kTwitterApi.getFollowing(userId)) { followers, following ->
22 | followers.map {
23 | FollowingUser(it, it.id in following.ids)
24 | }
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/interactors/TopImagesInteractor.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.interactors
2 |
3 | import com.backstopmedia.kotlin.ktwitter.api.KTwitterApi
4 | import com.backstopmedia.kotlin.ktwitter.api.KTwitterApiClient
5 | import com.backstopmedia.kotlin.ktwitter.entities.Image
6 | import com.twitter.sdk.android.core.TwitterSession
7 | import com.twitter.sdk.android.core.models.Tweet
8 | import rx.Observable
9 |
10 | interface TopImagesInteractor {
11 |
12 | fun getMostRecentImages(): Observable>
13 | }
14 |
15 | class TopImagesInteractorImpl(val session: TwitterSession) : TopImagesInteractor {
16 |
17 | private val kTwitterApi: KTwitterApi
18 |
19 | init {
20 | kTwitterApi = KTwitterApiClient(session).kTwitterApi
21 | }
22 |
23 | override fun getMostRecentImages(): Observable> =
24 | kTwitterApi.homeTimeline(count = 200)
25 | .map {
26 | it.filter { it.hasImage() }.map { Image.fromTweet(it) }.sortedByDescending { it.retweetCount }
27 | }
28 | }
29 |
30 | fun Tweet.hasImage(): Boolean =
31 | if (entities == null || entities.media == null || entities.media.isEmpty()) false
32 | else with(entities.media) {
33 | val firstEntry = first()
34 | if (firstEntry == null || !firstEntry.type.equals("photo")) false
35 | else true
36 | }
37 |
38 |
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/interactors/TopUsersInteractor.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.interactors
2 |
3 | import com.backstopmedia.kotlin.ktwitter.api.KTwitterApi
4 | import com.backstopmedia.kotlin.ktwitter.api.KTwitterApiClient
5 | import com.backstopmedia.kotlin.ktwitter.api.getFollowingIds
6 | import com.backstopmedia.kotlin.ktwitter.api.getRetweets
7 | import com.backstopmedia.kotlin.ktwitter.entities.RankedUser
8 | import com.backstopmedia.kotlin.ktwitter.utils.functional.toMultimapBy
9 | import com.backstopmedia.kotlin.ktwitter.utils.twitter.tweetsByUser
10 | import com.twitter.sdk.android.core.TwitterSession
11 | import rx.Observable
12 |
13 | interface TopUsersInteractor {
14 | fun getTopUsers(userId: Long): Observable>
15 | }
16 |
17 | class TopUsersInteractorImpl(val session: TwitterSession) : TopUsersInteractor {
18 |
19 | private val kTwitterApi: KTwitterApi = KTwitterApiClient(session).kTwitterApi
20 |
21 | /**
22 | * Get a list of the most faved users in your last [count] tweets
23 | * Also resolves following status via a separate [kTwitterApi.getFollowing] call
24 | */
25 | fun getFavoriteUsers(userId: Long): Observable> = with(kTwitterApi) {
26 | getFaves(userId).zipWith(getFollowingIds(session.userId)) {
27 | tweets, following ->
28 | val userMap = tweets.map { it.user }.toMapBy { it.id }
29 | tweets.tweetsByUser().map {
30 | RankedUser.fromFaves(userMap[it.key]!!, it.value, following)
31 | }.sortedByDescending { it.rank }
32 | }
33 | }
34 |
35 | /**
36 | * Get a list of the most RT'd users in your last [count] tweets
37 | * Also resolves following status via a separate [kTwitterApi.getFollowing] call
38 | */
39 | fun getRetweetedUsers(userId: Long): Observable> = with(kTwitterApi) {
40 | getRetweets(userId).zipWith(getFollowingIds(session.userId)) {
41 | tweets, following ->
42 | val userMap = tweets.map { it.user }.toMapBy { it.id }
43 | tweets.tweetsByUser().map {
44 | RankedUser.fromRetweets(userMap[it.key]!!, it.value, following)
45 | }.sortedByDescending { it.rank }
46 | }
47 | }
48 |
49 | /**
50 | * Takes [getFavoriteUsers] and [getRetweetedUsers]
51 | * and applies Rx's [zipWith] function to merge the results.
52 | *
53 | * Ranking algorithm:
54 | * 2 pts/retweet
55 | * 1 pts/fave
56 | */
57 | override fun getTopUsers(userId: Long): Observable> {
58 | return getFavoriteUsers(userId).zipWith(getRetweetedUsers(userId)) {
59 | faves, retweets ->
60 | (faves + retweets).let {
61 | it.toMultimapBy { it.user }.map {
62 | it.value.first() + it.value.lastOrNull()
63 | }.sortedByDescending { it.rank }
64 | }
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/interactors/UserInteractor.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.interactors
2 |
3 | import android.util.Log
4 | import com.backstopmedia.kotlin.ktwitter.api.KTwitterApi
5 | import com.backstopmedia.kotlin.ktwitter.api.KTwitterApiClient
6 | import com.backstopmedia.kotlin.ktwitter.entities.Profile
7 | import com.backstopmedia.kotlin.ktwitter.entities.RankedUser
8 | import com.backstopmedia.kotlin.ktwitter.utils.functional.sortKeysByValue
9 | import com.backstopmedia.kotlin.ktwitter.utils.functional.toMultimapBy
10 | import com.twitter.sdk.android.core.TwitterSession
11 | import com.twitter.sdk.android.core.models.User
12 | import rx.Observable
13 |
14 | interface UserInteractor {
15 | fun getCurrentUser(): Observable
16 | }
17 |
18 | class UserInteractorImpl(val session: TwitterSession) : UserInteractor {
19 |
20 | private val kTwitterApi: KTwitterApi = KTwitterApiClient(session).kTwitterApi
21 |
22 | override fun getCurrentUser(): Observable =
23 | kTwitterApi.getUser(screenName = session.userName)
24 | .map { Profile.fromUser(it) }
25 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/presenters/FollowersPresenter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.presenters
2 |
3 | import com.backstopmedia.kotlin.ktwitter.entities.FollowingUser
4 | import com.backstopmedia.kotlin.ktwitter.interactors.FollowersInteractor
5 | import com.backstopmedia.kotlin.ktwitter.ui.view.FollowersView
6 | import com.backstopmedia.kotlin.ktwitter.utils.BaseSubscriber
7 | import com.twitter.sdk.android.Twitter
8 | import com.twitter.sdk.android.core.models.User
9 | import rx.android.schedulers.AndroidSchedulers
10 | import rx.schedulers.Schedulers
11 | import rx.subscriptions.CompositeSubscription
12 |
13 | interface FollowersPresenter : Presenter
14 |
15 | class FollowersPresenterImpl(val interactor: FollowersInteractor) : FollowersPresenter {
16 |
17 | private val compositeSubscription = CompositeSubscription()
18 |
19 | override fun takeView(view: FollowersView) {
20 | val userId = Twitter.getSessionManager().activeSession.userId
21 | val subscription = interactor.getFollowers(userId)
22 | .subscribeOn(Schedulers.io())
23 | .observeOn(AndroidSchedulers.mainThread())
24 | .subscribe(object : BaseSubscriber>() {
25 | override fun onError(e: Throwable) {
26 | view.showError(e)
27 | }
28 |
29 | override fun onNext(t: List) {
30 | view.bind(t)
31 | }
32 | })
33 | compositeSubscription.add(subscription)
34 | }
35 |
36 | override fun dropView(view: FollowersView) {
37 | compositeSubscription.unsubscribe()
38 | }
39 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/presenters/NavigationDrawerPresenter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.presenters
2 |
3 | import com.backstopmedia.kotlin.ktwitter.interactors.UserInteractor
4 | import com.backstopmedia.kotlin.ktwitter.ui.view.NavigationDrawerView
5 | import rx.android.schedulers.AndroidSchedulers
6 | import rx.schedulers.Schedulers
7 | import rx.subscriptions.CompositeSubscription
8 |
9 | interface NavigationDrawerPresenter : Presenter
10 |
11 | class NavigationDrawerPresenterImpl(val interactor: UserInteractor) : NavigationDrawerPresenter {
12 |
13 | val compositeSubscription = CompositeSubscription()
14 |
15 | override fun takeView(view: NavigationDrawerView) {
16 | val subscription = interactor.getCurrentUser()
17 | .subscribeOn(Schedulers.io())
18 | .observeOn(AndroidSchedulers.mainThread())
19 | .subscribe({
20 | view.bind(it)
21 | })
22 | compositeSubscription.add(subscription)
23 | }
24 |
25 | override fun dropView(view: NavigationDrawerView) {
26 | compositeSubscription.unsubscribe()
27 | }
28 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/presenters/Presenter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.presenters
2 |
3 | interface Presenter {
4 |
5 | fun takeView(view: V)
6 |
7 | fun dropView(view: V)
8 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/presenters/TopImagesPresenter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.presenters
2 |
3 | import com.backstopmedia.kotlin.ktwitter.entities.Image
4 | import com.backstopmedia.kotlin.ktwitter.interactors.TopImagesInteractor
5 | import com.backstopmedia.kotlin.ktwitter.ui.view.TopImagesView
6 | import com.backstopmedia.kotlin.ktwitter.utils.BaseSubscriber
7 | import rx.android.schedulers.AndroidSchedulers
8 | import rx.schedulers.Schedulers
9 | import rx.subscriptions.CompositeSubscription
10 |
11 | interface TopImagesPresenter : Presenter
12 |
13 | class TopImagesPresenterImpl(val interactor: TopImagesInteractor) : TopImagesPresenter {
14 |
15 | val compositeSubscription = CompositeSubscription()
16 |
17 | override fun takeView(view: TopImagesView) {
18 | val subscription = interactor.getMostRecentImages()
19 | .subscribeOn(Schedulers.io())
20 | .observeOn(AndroidSchedulers.mainThread())
21 | .subscribe(object : BaseSubscriber>() {
22 | override fun onError(e: Throwable) {
23 | view.showError(error = e)
24 | }
25 |
26 | override fun onNext(t: List) {
27 | view.bind(images = t)
28 | }
29 | })
30 | compositeSubscription.add(subscription)
31 | }
32 |
33 | override fun dropView(view: TopImagesView) {
34 | compositeSubscription.unsubscribe()
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/presenters/TopUsersPresenter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.presenters
2 |
3 | import com.backstopmedia.kotlin.ktwitter.entities.Image
4 | import com.backstopmedia.kotlin.ktwitter.entities.RankedUser
5 | import com.backstopmedia.kotlin.ktwitter.interactors.TopUsersInteractor
6 | import com.backstopmedia.kotlin.ktwitter.ui.view.TopUsersView
7 | import com.backstopmedia.kotlin.ktwitter.utils.BaseSubscriber
8 | import com.twitter.sdk.android.Twitter
9 | import com.twitter.sdk.android.core.models.User
10 | import rx.android.schedulers.AndroidSchedulers
11 | import rx.schedulers.Schedulers
12 | import rx.subscriptions.CompositeSubscription
13 |
14 | interface TopUsersPresenter : Presenter
15 |
16 | class TopUsersPresenterImpl(val interactor: TopUsersInteractor, val userId: Long? = null) : TopUsersPresenter {
17 |
18 | private val compositeSubscription = CompositeSubscription()
19 |
20 | override fun takeView(view: TopUsersView) {
21 | val nonNullUid = userId ?: Twitter.getSessionManager().activeSession.userId
22 | val sub = interactor.getTopUsers(nonNullUid)
23 | .subscribeOn(Schedulers.io())
24 | .observeOn(AndroidSchedulers.mainThread())
25 | .subscribe(object : BaseSubscriber>() {
26 | override fun onNext(t: List) {
27 | view.bind(t)
28 | }
29 | override fun onError(e: Throwable) {
30 | view.showError(error = e)
31 | }
32 | })
33 | compositeSubscription.add(sub)
34 | }
35 |
36 | override fun dropView(view: TopUsersView) {
37 | compositeSubscription.unsubscribe()
38 | }
39 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/NavigationHelper.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.support.annotation.IdRes
6 | import android.support.annotation.LayoutRes
7 | import android.support.design.widget.NavigationView
8 | import android.support.v4.app.Fragment
9 | import android.support.v4.widget.DrawerLayout
10 | import android.support.v7.app.ActionBarDrawerToggle
11 | import android.support.v7.app.AppCompatActivity
12 | import android.support.v7.widget.Toolbar
13 | import android.util.Log
14 | import android.view.LayoutInflater
15 | import android.view.MenuItem
16 | import android.view.ViewGroup
17 | import android.widget.ImageView
18 | import android.widget.TextView
19 | import com.backstopmedia.kotlin.ktwitter.R
20 | import com.backstopmedia.kotlin.ktwitter.entities.Profile
21 | import com.backstopmedia.kotlin.ktwitter.entities.RankedUser
22 | import com.backstopmedia.kotlin.ktwitter.interactors.TopUsersInteractorImpl
23 | import com.backstopmedia.kotlin.ktwitter.interactors.UserInteractor
24 | import com.backstopmedia.kotlin.ktwitter.interactors.UserInteractorImpl
25 | import com.backstopmedia.kotlin.ktwitter.presenters.NavigationDrawerPresenter
26 | import com.backstopmedia.kotlin.ktwitter.presenters.NavigationDrawerPresenterImpl
27 | import com.backstopmedia.kotlin.ktwitter.ui.activities.FollowersActivity
28 | import com.backstopmedia.kotlin.ktwitter.ui.activities.TimelineActivity
29 | import com.backstopmedia.kotlin.ktwitter.ui.activities.TopImagesActivity
30 | import com.backstopmedia.kotlin.ktwitter.ui.activities.TopUsersActivity
31 | import com.backstopmedia.kotlin.ktwitter.ui.view.NavigationDrawerView
32 | import com.backstopmedia.kotlin.ktwitter.utils.functional.toMultimapBy
33 | import com.backstopmedia.kotlin.ktwitter.utils.glide.CircleTransformation
34 | import com.bumptech.glide.Glide
35 | import com.twitter.sdk.android.Twitter
36 | import com.twitter.sdk.android.core.TwitterCore
37 | import org.jetbrains.anko.find
38 | import rx.android.schedulers.AndroidSchedulers
39 | import rx.schedulers.Schedulers
40 | import kotlin.properties.Delegates
41 |
42 | class NavigationHelper : Fragment(), NavigationDrawerView {
43 |
44 | companion object {
45 | fun setup(activity: AppCompatActivity, @LayoutRes resId: Int): NavigationHelper {
46 | val navigationHelper = activity.attachNavigationHelper()
47 | navigationHelper.setContentViewForActivity(activity, resId)
48 | return navigationHelper
49 | }
50 | }
51 |
52 | private val interactor: UserInteractor by lazy { UserInteractorImpl(TwitterCore.getInstance().sessionManager.activeSession) }
53 | private val presenter: NavigationDrawerPresenter by lazy { NavigationDrawerPresenterImpl(interactor) }
54 |
55 | private var isSubdecorInstalled = false
56 | private var drawerLayout: DrawerLayout by Delegates.notNull()
57 | private var drawerToggle: ActionBarDrawerToggle by Delegates.notNull()
58 | private var navigationView: NavigationView by Delegates.notNull()
59 | private var content: ViewGroup by Delegates.notNull()
60 | private var username: TextView by Delegates.notNull()
61 | private var avatar: ImageView by Delegates.notNull()
62 |
63 |
64 | override fun onCreate(savedInstanceState: Bundle?) {
65 | super.onCreate(savedInstanceState)
66 | setupNavigationView()
67 | setHasOptionsMenu(true)
68 | presenter.takeView(this)
69 | }
70 |
71 | override fun onActivityCreated(savedInstanceState: Bundle?) {
72 | super.onActivityCreated(savedInstanceState)
73 | (activity as? AppCompatActivity)?.setupSimpleToolbar(toolbarId = R.id.toolbar)
74 | }
75 |
76 | override fun onStart() {
77 | super.onStart()
78 | drawerToggle.syncState()
79 | }
80 |
81 | override fun onDestroyView() {
82 | super.onDestroyView()
83 | presenter.dropView(this)
84 | }
85 |
86 | override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (drawerToggle.onOptionsItemSelected(item)) {
87 | true -> true
88 | else -> super.onOptionsItemSelected(item)
89 | }
90 |
91 | override fun bind(userProfile: Profile) {
92 | username.text = userProfile.handle
93 | Glide.with(activity)
94 | .load(userProfile.avatarUrl)
95 | .transform(CircleTransformation(activity))
96 | .into(avatar)
97 | }
98 |
99 | private fun setupNavigationView() {
100 | navigationView.setNavigationItemSelectedListener {
101 | val intent = when (it.itemId) {
102 | R.id.drawer_timeline ->
103 | if (activity is TimelineActivity) null
104 | else Intent(activity, TimelineActivity::class.java)
105 | R.id.drawer_top_images ->
106 | if (activity is TopImagesActivity) null
107 | else Intent(activity, TopImagesActivity::class.java)
108 | R.id.drawer_recommend ->
109 | if (activity is TopUsersActivity) null
110 | else Intent(activity, TopUsersActivity::class.java)
111 | R.id.drawer_followers ->
112 | if (activity is FollowersActivity) null
113 | else Intent(activity, FollowersActivity::class.java)
114 | else -> null
115 | }
116 |
117 | drawerLayout.closeDrawers()
118 |
119 | intent?.let {
120 | activity.startActivity(it)
121 | activity.finish()
122 | }
123 |
124 | true
125 | }
126 | }
127 |
128 | private fun setContentViewForActivity(activity: AppCompatActivity, @LayoutRes resId: Int) {
129 | ensureSubDecor(activity)
130 | content.removeAllViews()
131 | LayoutInflater.from(activity).inflate(resId, content, true)
132 | activity.window.callback.onContentChanged()
133 | }
134 |
135 | private fun ensureSubDecor(activity: AppCompatActivity) {
136 | if (isSubdecorInstalled) {
137 | return
138 | }
139 |
140 | activity.setContentView(R.layout.navigation_drawer_base)
141 | findViewsIn(activity)
142 |
143 | drawerToggle = ActionBarDrawerToggle(activity, drawerLayout, R.string.drawer_open, R.string.drawer_close)
144 | drawerLayout.setDrawerListener(drawerToggle)
145 |
146 | isSubdecorInstalled = true
147 | }
148 |
149 | private fun findViewsIn(activity: AppCompatActivity) {
150 | content = activity.find(R.id.content)
151 | drawerLayout = activity.find(R.id.drawer_layout)
152 | navigationView = activity.find(R.id.navigation_view)
153 | username = activity.find(R.id.username)
154 | avatar = activity.find(R.id.avatar)
155 | }
156 | }
157 |
158 | fun AppCompatActivity.attachNavigationHelper(): NavigationHelper {
159 | val fm = this.supportFragmentManager
160 |
161 | var frag = fm.findFragmentByTag(FRAG_TAG) as NavigationHelper?
162 | if (frag == null) {
163 | frag = NavigationHelper()
164 | fm.beginTransaction().add(frag, FRAG_TAG).commit()
165 | }
166 |
167 | return frag
168 | }
169 |
170 | fun AppCompatActivity.setupSimpleToolbar(@IdRes toolbarId: Int): Toolbar {
171 | val toolbar = find(toolbarId)
172 | setSupportActionBar(toolbar)
173 |
174 | val actionBar = supportActionBar
175 | actionBar?.let {
176 | it.setHomeButtonEnabled(true)
177 | it.setDisplayHomeAsUpEnabled(true)
178 | it.setDisplayShowTitleEnabled(true)
179 | }
180 |
181 | return toolbar
182 | }
183 |
184 | private const val FRAG_TAG: String = "NavigationHelper"
185 |
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/activities/FollowersActivity.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.activities
2 |
3 | import android.os.Bundle
4 | import android.support.v7.app.AppCompatActivity
5 | import android.support.v7.widget.LinearLayoutManager
6 | import com.backstopmedia.kotlin.ktwitter.R
7 | import com.backstopmedia.kotlin.ktwitter.entities.FollowingUser
8 | import com.backstopmedia.kotlin.ktwitter.interactors.FollowersInteractor
9 | import com.backstopmedia.kotlin.ktwitter.interactors.FollowersInteractorImpl
10 | import com.backstopmedia.kotlin.ktwitter.presenters.FollowersPresenter
11 | import com.backstopmedia.kotlin.ktwitter.presenters.FollowersPresenterImpl
12 | import com.backstopmedia.kotlin.ktwitter.ui.NavigationHelper
13 | import com.backstopmedia.kotlin.ktwitter.ui.adapter.FollowersAdapter
14 | import com.backstopmedia.kotlin.ktwitter.ui.adapter.FollowersWithHeadersAdapter
15 | import com.backstopmedia.kotlin.ktwitter.ui.view.FollowersView
16 | import com.twitter.sdk.android.core.TwitterCore
17 | import com.twitter.sdk.android.core.models.User
18 | import org.jetbrains.anko.toast
19 | import kotlinx.android.synthetic.activity_followers.*
20 |
21 | class FollowersActivity : AppCompatActivity(), FollowersView {
22 |
23 | private val interactor: FollowersInteractor by lazy { FollowersInteractorImpl(TwitterCore.getInstance().sessionManager.activeSession) }
24 | private val presenter: FollowersPresenter by lazy { FollowersPresenterImpl(interactor) }
25 |
26 | override fun onCreate(savedInstanceState: Bundle?) {
27 | super.onCreate(savedInstanceState)
28 | NavigationHelper.setup(this, R.layout.activity_followers)
29 | recyclerView.layoutManager = LinearLayoutManager(this)
30 | presenter.takeView(this)
31 | }
32 |
33 | override fun onDestroy() {
34 | super.onDestroy()
35 | presenter.dropView(this)
36 | }
37 |
38 | override fun bind(users: List) {
39 | // recyclerView.adapter = FollowersAdapter(users)
40 | recyclerView.adapter = FollowersWithHeadersAdapter(users)
41 | }
42 |
43 | override fun showError(error: Throwable) {
44 | toast("Couldn't load list. You probably crossed the rate limit.")
45 | }
46 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/activities/LoginActivity.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.activities
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.support.v7.app.AppCompatActivity
6 | import com.backstopmedia.kotlin.ktwitter.R
7 | import com.backstopmedia.kotlin.ktwitter.utils.kallback
8 | import kotlinx.android.synthetic.activity_login.login
9 | import org.jetbrains.anko.toast
10 |
11 | class LoginActivity : AppCompatActivity() {
12 |
13 | override fun onCreate(savedInstanceState: Bundle?) {
14 | super.onCreate(savedInstanceState)
15 | setContentView(R.layout.activity_login)
16 | login.callback = kallback {
17 | finish()
18 | startActivity(Intent(this, TimelineActivity::class.java))
19 | toast("Logged in as ${it.data.userName}")
20 | }
21 | }
22 |
23 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
24 | super.onActivityResult(requestCode, resultCode, data)
25 | login.onActivityResult(requestCode, resultCode, data)
26 | }
27 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/activities/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.activities
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.support.v7.app.AppCompatActivity
6 | import com.twitter.sdk.android.core.TwitterCore
7 |
8 | class MainActivity : AppCompatActivity() {
9 |
10 | override fun onCreate(savedInstanceState: Bundle?) {
11 | super.onCreate(savedInstanceState)
12 | finish()
13 | startActivity(redirectIntent())
14 | }
15 |
16 | private fun redirectIntent(): Intent {
17 | return when (TwitterCore.getInstance()?.sessionManager?.activeSession) {
18 | null -> Intent(this, LoginActivity::class.java)
19 | else -> Intent(this, TimelineActivity::class.java)
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/activities/TimelineActivity.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.activities
2 |
3 | import android.net.Uri
4 | import android.os.Bundle
5 | import android.support.v7.app.AppCompatActivity
6 | import android.text.Editable
7 | import android.text.InputType
8 | import android.util.Log
9 | import android.view.Gravity
10 | import com.backstopmedia.kotlin.ktwitter.R
11 | import com.backstopmedia.kotlin.ktwitter.ui.NavigationHelper
12 | import com.twitter.sdk.android.tweetcomposer.TweetComposer
13 | import com.twitter.sdk.android.tweetui.TweetTimelineListAdapter
14 | import com.twitter.sdk.android.tweetui.UserTimeline
15 | import kotlinx.android.synthetic.activity_timeline.*
16 | import org.jetbrains.anko.*
17 |
18 | class TimelineActivity : AppCompatActivity(), AnkoLogger {
19 |
20 | override fun onCreate(savedInstanceState: Bundle?) {
21 | super.onCreate(savedInstanceState)
22 | NavigationHelper.setup(this, R.layout.activity_timeline)
23 |
24 | val userTimeline = UserTimeline.Builder()
25 | .screenName("fabric")
26 | .build()
27 |
28 | val adapter = TweetTimelineListAdapter.Builder(this)
29 | .setTimeline(userTimeline)
30 | .build()
31 |
32 | timeline_list.adapter = adapter
33 | timeline_list.emptyView = empty
34 |
35 | fab.onClick { showAlert() }
36 | }
37 |
38 | private fun showAlert() {
39 | alert("So how many pages of our book have you read so far?") {
40 | customView {
41 | val pages = editText {
42 | hint = "Enter pages count"
43 | inputType = InputType.TYPE_CLASS_NUMBER
44 | gravity = Gravity.CENTER
45 | }
46 | positiveButton {
47 | composeTweet(pages.text)
48 | }
49 | }
50 | }.show()
51 | }
52 |
53 | private fun composeTweet(pages: Editable) {
54 | val text = "I've read ${pages.count} pages of \"Kotlin Book\"! #AndroidDev #Kotlin"
55 | val imageUri = Uri.parse("android.resource://$packageName/drawable/kotlin_logo")
56 | TweetComposer.Builder(this)
57 | .text(text)
58 | .image(imageUri)
59 | .show()
60 | }
61 |
62 | private val Editable.count: Int
63 | get() = if (toString().isEmpty()) 0 else try {
64 | toString().toInt()
65 | } catch(e: NumberFormatException) {
66 | warn { "inputType should be set to TYPE_CLASS_NUMBER" }
67 | 0
68 | }
69 |
70 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/activities/TopImagesActivity.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.activities
2 |
3 | import android.os.Bundle
4 | import android.support.v7.app.AppCompatActivity
5 | import android.support.v7.widget.DefaultItemAnimator
6 | import android.support.v7.widget.GridLayoutManager
7 | import com.backstopmedia.kotlin.ktwitter.R
8 | import com.backstopmedia.kotlin.ktwitter.entities.Image
9 | import com.backstopmedia.kotlin.ktwitter.interactors.TopImagesInteractor
10 | import com.backstopmedia.kotlin.ktwitter.interactors.TopImagesInteractorImpl
11 | import com.backstopmedia.kotlin.ktwitter.presenters.TopImagesPresenter
12 | import com.backstopmedia.kotlin.ktwitter.presenters.TopImagesPresenterImpl
13 | import com.backstopmedia.kotlin.ktwitter.ui.NavigationHelper
14 | import com.backstopmedia.kotlin.ktwitter.ui.adapter.TopImagesAdapter
15 | import com.backstopmedia.kotlin.ktwitter.ui.view.TopImagesView
16 | import com.twitter.sdk.android.core.TwitterCore
17 | import kotlinx.android.synthetic.activity_top_images.recycler_view
18 | import org.jetbrains.anko.toast
19 |
20 | class TopImagesActivity : AppCompatActivity(), TopImagesView {
21 |
22 | private val interactor: TopImagesInteractor by lazy { TopImagesInteractorImpl(TwitterCore.getInstance().sessionManager.activeSession) }
23 | private val presenter: TopImagesPresenter by lazy { TopImagesPresenterImpl(interactor) }
24 |
25 | val onImageClick: (Image) -> Unit = {
26 | toast(it.title)
27 | }
28 |
29 | override fun onCreate(savedInstanceState: Bundle?) {
30 | super.onCreate(savedInstanceState)
31 | NavigationHelper.setup(this, R.layout.activity_top_images)
32 |
33 | recycler_view.layoutManager = GridLayoutManager(this, 2)
34 | recycler_view.itemAnimator = DefaultItemAnimator()
35 |
36 | presenter.takeView(this)
37 | }
38 |
39 | override fun onDestroy() {
40 | super.onDestroy()
41 | presenter.dropView(this)
42 | }
43 |
44 | override fun bind(images: List) {
45 | recycler_view.adapter = TopImagesAdapter(images, onImageClick)
46 | }
47 |
48 | override fun showError(error: Throwable) {
49 | toast("Something went wrong")
50 | }
51 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/activities/TopUsersActivity.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.activities
2 |
3 | import android.app.Activity
4 | import android.content.Intent
5 | import android.os.Bundle
6 | import android.support.v7.app.AppCompatActivity
7 | import android.support.v7.widget.DefaultItemAnimator
8 | import android.support.v7.widget.GridLayoutManager
9 | import android.support.v7.widget.LinearLayoutManager
10 | import com.backstopmedia.kotlin.ktwitter.R
11 | import com.backstopmedia.kotlin.ktwitter.entities.Image
12 | import com.backstopmedia.kotlin.ktwitter.entities.RankedUser
13 | import com.backstopmedia.kotlin.ktwitter.interactors.TopUsersInteractor
14 | import com.backstopmedia.kotlin.ktwitter.interactors.TopUsersInteractorImpl
15 | import com.backstopmedia.kotlin.ktwitter.presenters.TopUsersPresenter
16 | import com.backstopmedia.kotlin.ktwitter.presenters.TopUsersPresenterImpl
17 | import com.backstopmedia.kotlin.ktwitter.ui.NavigationHelper
18 | import com.backstopmedia.kotlin.ktwitter.ui.adapter.TopImagesAdapter
19 | import com.backstopmedia.kotlin.ktwitter.ui.adapter.TopUsersAdapter
20 | import com.backstopmedia.kotlin.ktwitter.ui.view.TopUsersView
21 | import com.backstopmedia.kotlin.ktwitter.utils.os.getExtra
22 | import com.backstopmedia.kotlin.ktwitter.utils.os.intentExtra
23 | import com.twitter.sdk.android.core.TwitterCore
24 | import com.twitter.sdk.android.core.models.User
25 | import kotlinx.android.synthetic.activity_top_images.*
26 | import org.jetbrains.anko.toast
27 |
28 | class TopUsersActivity : AppCompatActivity(), TopUsersView {
29 |
30 | val userId: Long? by intentExtra("userId")
31 |
32 | private val interactor: TopUsersInteractor by lazy { TopUsersInteractorImpl(TwitterCore.getInstance().sessionManager.activeSession) }
33 | private val presenter: TopUsersPresenter by lazy { TopUsersPresenterImpl(interactor, userId) }
34 |
35 | override fun onCreate(savedInstanceState: Bundle?) {
36 | super.onCreate(savedInstanceState)
37 | NavigationHelper.setup(this, R.layout.activity_coordinator_recycler)
38 | recycler_view.layoutManager = LinearLayoutManager(this)
39 | presenter.takeView(this)
40 | if (userId == null) {
41 | toast("Tap somebody to see their favorite users.")
42 | }
43 | }
44 |
45 | override fun onDestroy() {
46 | super.onDestroy()
47 | presenter.dropView(this)
48 | }
49 |
50 | override fun bind(users: List) {
51 | recycler_view.adapter = TopUsersAdapter(users) {
52 | startActivity(Intent(this, TopUsersActivity::class.java).putExtra("userId", it.user.id))
53 | }
54 | }
55 |
56 | override fun showError(error: Throwable) {
57 | toast("Something went wrong")
58 | }
59 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/adapter/FollowersAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.adapter
2 |
3 | import android.support.v7.widget.RecyclerView
4 | import android.view.View
5 | import android.view.ViewGroup
6 | import com.backstopmedia.kotlin.ktwitter.R
7 | import com.backstopmedia.kotlin.ktwitter.entities.FollowingUser
8 | import com.bumptech.glide.Glide
9 | import kotlinx.android.synthetic.list_item_follower.view.*
10 | import org.jetbrains.anko.layoutInflater
11 |
12 | class FollowersAdapter(val users: List) : RecyclerView.Adapter() {
13 |
14 | override fun getItemCount() = users.size
15 |
16 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FollowersViewHolder? {
17 | return FollowersViewHolder(parent.context.layoutInflater.inflate(R.layout.list_item_follower, parent, false))
18 | }
19 |
20 | override fun onBindViewHolder(holder: FollowersViewHolder, position: Int) {
21 | val item = users[position]
22 | holder.bind(item)
23 | }
24 |
25 | class FollowersViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
26 |
27 | fun bind(item: FollowingUser) {
28 | val (user, followed) = item
29 | with(user) {
30 | itemView.nameView.text = name
31 | itemView.screenNameView.text = "@$screenName"
32 | itemView.followedView.text = if (followed) "followed" else ""
33 | itemView.followersCountView.text = "$followersCount followers"
34 | Glide.with(itemView.context).load(profileImageUrlHttps).into(itemView.imageView)
35 | }
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/adapter/FollowersWithHeadersAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.adapter
2 |
3 | import android.support.v7.widget.RecyclerView
4 | import android.view.View
5 | import android.view.ViewGroup
6 | import com.backstopmedia.kotlin.ktwitter.R
7 | import com.backstopmedia.kotlin.ktwitter.entities.FollowingUser
8 | import com.backstopmedia.kotlin.ktwitter.ui.adapter.FollowersWithHeadersAdapter.ListItem.FollowerItem
9 | import com.backstopmedia.kotlin.ktwitter.ui.adapter.FollowersWithHeadersAdapter.ListItem.HeaderItem
10 | import com.bumptech.glide.Glide
11 | import kotlinx.android.synthetic.list_item_follower.view.*
12 | import kotlinx.android.synthetic.list_item_header.view.*
13 | import org.jetbrains.anko.layoutInflater
14 | import java.util.*
15 |
16 | class FollowersWithHeadersAdapter(val users: List) : RecyclerView.Adapter() {
17 |
18 | companion object {
19 | private val VIEW_TYPE_HEADER = 0
20 | private val VIEW_TYPE_FOLLOWER = 1
21 | }
22 |
23 | private val items = ArrayList()
24 |
25 | init {
26 | var lastHeader = ' '
27 | for (i in users.indices) {
28 | val header = users[i].user.name.first().toUpperCase()
29 | if (header != lastHeader) {
30 | lastHeader = header
31 | items.add(HeaderItem(header))
32 | }
33 | items.add(FollowerItem(users[i]))
34 | }
35 | }
36 |
37 | override fun getItemCount() = items.size
38 |
39 | override fun getItemViewType(position: Int) = when (items[position]) {
40 | is HeaderItem -> VIEW_TYPE_HEADER
41 | is FollowerItem -> VIEW_TYPE_FOLLOWER
42 | }
43 |
44 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FollowersWithHeadersViewHolder? {
45 | val view = when (viewType) {
46 | VIEW_TYPE_HEADER -> parent.context.layoutInflater.inflate(R.layout.list_item_header, parent, false)
47 | else -> parent.context.layoutInflater.inflate(R.layout.list_item_follower, parent, false)
48 | }
49 | return FollowersWithHeadersViewHolder(view)
50 | }
51 |
52 | override fun onBindViewHolder(holder: FollowersWithHeadersViewHolder, position: Int) {
53 | val item = items[position]
54 | holder.bind(item)
55 | }
56 |
57 | class FollowersWithHeadersViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
58 |
59 | fun bind(item: ListItem) {
60 | when (item) {
61 | is HeaderItem -> {
62 | with(item) {
63 | itemView.headerView.text = header.toString()
64 | }
65 | }
66 | is FollowerItem -> {
67 | val (user, followed) = item.user
68 | with(user) {
69 | itemView.nameView.text = name
70 | itemView.screenNameView.text = "@$screenName"
71 | itemView.followedView.text = if (followed) "followed" else ""
72 | itemView.followersCountView.text = "$followersCount followers"
73 | com.bumptech.glide.Glide.with(itemView.context).load(profileImageUrlHttps).into(itemView.imageView)
74 | }
75 |
76 | }
77 | }
78 | }
79 | }
80 |
81 | sealed class ListItem() {
82 | class HeaderItem(val header: Char) : ListItem()
83 | class FollowerItem(val user: FollowingUser) : ListItem()
84 | }
85 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/adapter/TopImagesAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.adapter
2 |
3 | import android.support.v7.widget.RecyclerView
4 | import android.view.View
5 | import android.view.ViewGroup
6 | import com.backstopmedia.kotlin.ktwitter.R
7 | import com.backstopmedia.kotlin.ktwitter.entities.Image
8 | import com.bumptech.glide.Glide
9 | import kotlinx.android.synthetic.grid_item_top_image.view.media
10 | import kotlinx.android.synthetic.grid_item_top_image.view.retweet
11 | import org.jetbrains.anko.layoutInflater
12 | import org.jetbrains.anko.onClick
13 |
14 | class TopImagesAdapter(val images: List, val onImageClick: (Image) -> Unit) : RecyclerView.Adapter() {
15 |
16 |
17 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
18 | val itemView = parent.context.layoutInflater.inflate(R.layout.grid_item_top_image, parent, false)
19 | return ViewHolder(itemView, onImageClick)
20 | }
21 |
22 | override fun onBindViewHolder(holder: ViewHolder, position: Int) {
23 | holder.bind(image = getItem(position))
24 | }
25 |
26 | override fun getItemCount(): Int = images.size
27 |
28 | fun getItem(position: Int) = images[position]
29 |
30 |
31 | }
32 |
33 | class ViewHolder(view: View, val onImageClick: (Image) -> Unit) : RecyclerView.ViewHolder(view) {
34 |
35 | fun bind(image: Image) = with(image) {
36 | itemView.onClick { onImageClick(image) }
37 | itemView.retweet.text = retweetCount.toString()
38 | when (mediaUrl.isEmpty()) {
39 | true -> itemView.media.visibility = View.GONE
40 | else -> {
41 | itemView.media.visibility = View.VISIBLE
42 | Glide.with(itemView.context).load(mediaUrl).into(itemView.media)
43 | }
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/adapter/TopUsersAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.adapter
2 |
3 | import android.support.v7.widget.RecyclerView
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import android.widget.TextView
8 | import com.backstopmedia.kotlin.ktwitter.R
9 | import com.backstopmedia.kotlin.ktwitter.api.KTwitterApiClient
10 | import com.backstopmedia.kotlin.ktwitter.entities.RankedUser
11 | import com.bumptech.glide.Glide
12 | import com.twitter.sdk.android.Twitter
13 | import com.twitter.sdk.android.core.models.User
14 |
15 | import kotlinx.android.synthetic.list_item_user.view.*
16 | import org.jetbrains.anko.toast
17 | import rx.android.schedulers.AndroidSchedulers
18 | import rx.schedulers.Schedulers
19 |
20 | class TopUsersAdapter(users: List, val onClick: (RankedUser) -> Unit) : RecyclerView.Adapter() {
21 |
22 | private val users = users.toArrayList()
23 |
24 | override fun getItemCount(): Int {
25 | return users.size
26 | }
27 |
28 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UsersViewHolder? {
29 | return UsersViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.list_item_user, parent, false))
30 | }
31 |
32 | override fun onBindViewHolder(holder: UsersViewHolder, position: Int) {
33 | holder.bind(users[position])
34 | }
35 |
36 | public inner class UsersViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
37 | fun bind(user: RankedUser) {
38 | with(user.user) {
39 | itemView.name.text = name
40 | itemView.screen_name.text = screenName
41 | Glide.with(itemView.context).load(profileImageUrlHttps).into(itemView.image)
42 | itemView.setOnClickListener {
43 | onClick(user)
44 | }
45 |
46 | val applyFollowing = {
47 | with(user.following) {
48 | itemView.follow.isEnabled = !this
49 | itemView.follow.text = if (this) "Following" else "Follow"
50 | itemView.follow.alpha = if (this) 0.5f else 1f
51 | }
52 | }
53 | applyFollowing()
54 |
55 | itemView.follow.setOnClickListener {
56 | itemView.follow.isEnabled = false
57 | KTwitterApiClient(Twitter.getSessionManager().activeSession).kTwitterApi.follow(id, true)
58 | .observeOn(AndroidSchedulers.mainThread())
59 | .subscribeOn(Schedulers.io())
60 | .subscribe {
61 | itemView.context.toast("Followed $screenName!")
62 | user.following = true
63 | applyFollowing()
64 | }
65 | }
66 | }
67 | }
68 |
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/view/FollowersView.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.view
2 |
3 | import com.backstopmedia.kotlin.ktwitter.entities.FollowingUser
4 |
5 | interface FollowersView {
6 |
7 | fun bind(users: List)
8 |
9 | fun showError(error: Throwable)
10 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/view/NavigationDrawerView.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.view
2 |
3 | import com.backstopmedia.kotlin.ktwitter.entities.Profile
4 |
5 | interface NavigationDrawerView {
6 |
7 | fun bind(userProfile: Profile)
8 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/view/TopImagesView.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.view
2 |
3 | import com.backstopmedia.kotlin.ktwitter.entities.Image
4 |
5 | interface TopImagesView {
6 |
7 | fun bind(images: List)
8 |
9 | fun showError(error: Throwable)
10 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/ui/view/TopUsersView.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.ui.view
2 |
3 | import com.backstopmedia.kotlin.ktwitter.entities.RankedUser
4 | import com.twitter.sdk.android.core.models.User
5 |
6 | interface TopUsersView {
7 |
8 | fun bind(users: List)
9 |
10 | fun showError(error: Throwable)
11 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/utils/BaseSubscriber.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.utils
2 |
3 | import rx.Subscriber
4 |
5 | open class BaseSubscriber() : Subscriber() {
6 |
7 | override fun onCompleted() {
8 | }
9 |
10 | override fun onError(e: Throwable) {
11 | }
12 |
13 | override fun onNext(t: T) {
14 | }
15 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/utils/Kallback.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.utils
2 |
3 | import android.app.Activity
4 | import android.util.Log
5 | import android.widget.Toast
6 | import com.twitter.sdk.android.core.Callback
7 | import com.twitter.sdk.android.core.Result
8 | import com.twitter.sdk.android.core.TwitterException
9 |
10 | private val TAG = "Kallback"
11 |
12 | /**
13 | * A convenience method for generating callbacks.
14 | *
15 | * @param onSuccess block to call on successful return
16 | * @return A [Callback] object with basic error logging.
17 | */
18 | fun kallback(onSuccess: (Result) -> Unit = {}): Kallback {
19 | return Kallback(onSuccess).onFail {
20 | Log.w(TAG, "Something went wrong: $it")
21 | }
22 | }
23 |
24 | /**
25 | * Specialization of [kallback]
26 | *
27 | * This version, since it has access to the calling Context,
28 | * is able to pop up a toast on error states.
29 | *
30 | * @param onSuccess block to call on successful return
31 | * @return A [Callback] object with basic error logging.
32 | */
33 | fun Activity.kallback(onSuccess: (Result) -> Unit = {}): Kallback {
34 | return Kallback(onSuccess).onFail {
35 | Log.w(TAG, "Something went wrong: $it")
36 | Toast.makeText(this, "Something went wrong: ${it.message}", Toast.LENGTH_LONG).show()
37 | }
38 | }
39 |
40 | /**
41 | * A streamlined subclass of [Callback] with optional failure behavior.
42 | *
43 | * @param T the response type, passed up to [Callback]
44 | * @param onSuccess block to call on successful return
45 | * @see onFail for optional fail block.
46 | */
47 | open class Kallback(private val onSuccess: (Result) -> Unit) : Callback() {
48 |
49 | private var onFail: ((TwitterException) -> Unit)? = null
50 |
51 | /**
52 | * You may want to take an existing callback
53 | * and fork it with new [onSuccess] or [onFail]
54 | * @constructor copy constructor
55 | */
56 | constructor(other: Kallback) : this(other.onSuccess) {
57 | onFail = other.onFail
58 | }
59 |
60 | /**
61 | * Sets failure behavior. Can be chained from [kallback] or constructor.
62 | *
63 | * @param onFail block to run on failed request.
64 | */
65 | infix fun onFail(onFail: (TwitterException) -> Unit): Kallback {
66 | this.onFail = onFail
67 | return this
68 | }
69 |
70 | override fun success(result: Result) {
71 | onSuccess(result)
72 | }
73 |
74 | override fun failure(exception: TwitterException) {
75 | onFail?.invoke(exception)
76 | }
77 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/utils/MyTwitter.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.utils
2 |
3 | object MyTwitter {
4 | // Note: Your consumer key and secret should be obfuscated in your source code before shipping.
5 | const val KEY = "9zKVaamMBSsSkihrQeRLYS8us"
6 | const val SECRET = "U60A07OCvPd13bXZP9zNjjw1lluvyhZq4yakvvEWU1eLOKOWz4"
7 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/utils/dsl/TweetDsl.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.utils.dsl
2 |
3 | import android.util.Log
4 | import android.widget.Toast
5 | import com.backstopmedia.kotlin.ktwitter.utils.kallback
6 | import com.twitter.sdk.android.Twitter
7 | import com.twitter.sdk.android.core.Callback
8 | import com.twitter.sdk.android.core.Result
9 | import com.twitter.sdk.android.core.models.*
10 |
11 | /**
12 | * Allows us to build a tweet via DSL, then post it asynchronously using the API service.
13 | */
14 | fun Tweet.post(callback: Callback) {
15 | Twitter.getApiClient().statusesService.update(
16 | text,
17 | inReplyToStatusId,
18 | possiblySensitive,
19 | coordinates?.latitude,
20 | coordinates?.longitude,
21 | place?.id,
22 | true,
23 | false,
24 | null,
25 | callback)
26 | }
27 |
28 | /**
29 | * This will allow you to use a block-based DSL syntax for constructing a tweet.
30 | * It's a really nice alternative to the builder pattern
31 | * (and is generally even compatible with it, via extensions).
32 | *
33 | * @sample
34 | * tweet {
35 | * text = "HAY YOU GUYS"
36 | * }
37 | */
38 |
39 | fun tweetAboutHowGreatKotlinBuildersAre() {
40 | tweet {
41 | text = "Hey I'm tweeting with Kotlin builders!"
42 | possiblySensitive = false
43 | }.post(kallback {
44 | Log.d("Tweets", "Successfully tweeted ${it.data.id}")
45 | } onFail {
46 | Log.e("Tweets", "That didn't work")
47 | })
48 | }
49 |
50 | inline fun tweet(init: TweetBuilder.() -> Unit): Tweet {
51 | return TweetBuilder().apply(init).build()
52 | }
53 |
54 | /**
55 | * These vars were auto-generated based on the methods in [TweetBuilder]
56 | * We copy/pasted the methods over from that (decompiled) source file,
57 | * then we came up with a pretty gnarly regex to convert them into extension vars.
58 | * You can do this pretty easily by using Android Studio's Find/Replace feature.
59 | *
60 | * Unfortunately, because the members themselves have private visibility, we're unable to create
61 | * getters for the vars, so if you try to get() them, you'll crash.
62 | *
63 | * @sample:
64 | * fun setId(id:Long):TweetBuilder {
65 | * this.id = id
66 | * return this
67 | * }
68 | *
69 | * @find
70 | * fun (\w*)\((\w*)\: ([\w\?\<\>]*)\)\: (\w*) \{\n\s*this.(\w*) = (\w*)\n\s*return this\n\} *
71 | *
72 | * @replace
73 | * var $4.$2: $3\n\tget() = throw UnsupportedOperationException()\n\tset(value) { $1(value) }
74 | */
75 |
76 | var TweetBuilder.coordinates: Coordinates
77 | get() = throw UnsupportedOperationException()
78 | set(value) { setCoordinates(value) }
79 |
80 | var TweetBuilder.createdAt: String
81 | get() = throw UnsupportedOperationException()
82 | set(value) { setCreatedAt(value) }
83 |
84 | var TweetBuilder.currentUserRetweet: Any
85 | get() = throw UnsupportedOperationException()
86 | set(value) { setCurrentUserRetweet(value) }
87 |
88 | var TweetBuilder.entities: TweetEntities
89 | get() = throw UnsupportedOperationException()
90 | set(value) { setEntities(value) }
91 |
92 | var TweetBuilder.favoriteCount: Int?
93 | get() = throw UnsupportedOperationException()
94 | set(value) { setFavoriteCount(value) }
95 |
96 | var TweetBuilder.favorited: Boolean
97 | get() = throw UnsupportedOperationException()
98 | set(value) { setFavorited(value) }
99 |
100 | var TweetBuilder.filterLevel: String
101 | get() = throw UnsupportedOperationException()
102 | set(value) { setFilterLevel(value) }
103 |
104 | var TweetBuilder.id: Long
105 | get() = throw UnsupportedOperationException()
106 | set(value) { setId(value) }
107 |
108 | var TweetBuilder.idStr: String
109 | get() = throw UnsupportedOperationException()
110 | set(value) { setIdStr(value) }
111 |
112 | var TweetBuilder.inReplyToScreenName: String
113 | get() = throw UnsupportedOperationException()
114 | set(value) { setInReplyToScreenName(value) }
115 |
116 | var TweetBuilder.inReplyToStatusId: Long
117 | get() = throw UnsupportedOperationException()
118 | set(value) { setInReplyToStatusId(value) }
119 |
120 | var TweetBuilder.inReplyToStatusIdStr: String
121 | get() = throw UnsupportedOperationException()
122 | set(value) { setInReplyToStatusIdStr(value) }
123 |
124 | var TweetBuilder.inReplyToUserId: Long
125 | get() = throw UnsupportedOperationException()
126 | set(value) { setInReplyToUserId(value) }
127 |
128 | var TweetBuilder.inReplyToUserIdStr: String
129 | get() = throw UnsupportedOperationException()
130 | set(value) { setInReplyToUserIdStr(value) }
131 |
132 | var TweetBuilder.lang: String
133 | get() = throw UnsupportedOperationException()
134 | set(value) { setLang(value) }
135 |
136 | var TweetBuilder.place: Place
137 | get() = throw UnsupportedOperationException()
138 | set(value) { setPlace(value) }
139 |
140 | var TweetBuilder.possiblySensitive: Boolean
141 | get() = throw UnsupportedOperationException()
142 | set(value) { setPossiblySensitive(value) }
143 |
144 | var TweetBuilder.scopes: Any
145 | get() = throw UnsupportedOperationException()
146 | set(value) { setScopes(value) }
147 |
148 | var TweetBuilder.retweetCount: Int
149 | get() = throw UnsupportedOperationException()
150 | set(value) { setRetweetCount(value) }
151 |
152 | var TweetBuilder.retweeted: Boolean
153 | get() = throw UnsupportedOperationException()
154 | set(value) { setRetweeted(value) }
155 |
156 | var TweetBuilder.retweetedStatus: Tweet
157 | get() = throw UnsupportedOperationException()
158 | set(value) { setRetweetedStatus(value) }
159 |
160 | var TweetBuilder.source: String
161 | get() = throw UnsupportedOperationException()
162 | set(value) { setSource(value) }
163 |
164 | var TweetBuilder.text: String
165 | get() = throw UnsupportedOperationException()
166 | set(value) { setText(value) }
167 |
168 | var TweetBuilder.truncated: Boolean
169 | get() = throw UnsupportedOperationException()
170 | set(value) { setTruncated(value) }
171 |
172 | var TweetBuilder.user: User
173 | get() = throw UnsupportedOperationException()
174 | set(value) { setUser(value) }
175 |
176 | var TweetBuilder.withheldCopyright: Boolean
177 | get() = throw UnsupportedOperationException()
178 | set(value) { setWithheldCopyright(value) }
179 |
180 | var TweetBuilder.withheldInCountries: List
181 | get() = throw UnsupportedOperationException()
182 | set(value) { setWithheldInCountries(value) }
183 |
184 | var TweetBuilder.withheldScope: String
185 | get() = throw UnsupportedOperationException()
186 | set(value) { setWithheldScope(value) }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/utils/functional/_Collections.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.utils.functional
2 |
3 | import android.util.Log
4 | import java.util.*
5 |
6 | fun List.toMultimapBy(fn: (V) -> K): Map> {
7 | val retval = hashMapOf>()
8 | forEach {
9 | val k = fn(it)
10 | var list = retval[k] as ArrayList?
11 | if (list == null) {
12 | list = arrayListOf()
13 | retval[k] = list
14 | }
15 | list.add(it)
16 | }
17 | return retval
18 | }
19 |
20 | fun > Map.sortKeysByValue(fn: (V) -> R): List {
21 | return toSortedMap(object : Comparator {
22 | override fun compare(lhs: K, rhs: K): Int {
23 | return fn(get(lhs)!!).compareTo(fn(get(rhs)!!))
24 | }
25 | }).keys.toList()
26 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/utils/glide/CircleTransformation.java:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.utils.glide;
2 |
3 | import android.content.Context;
4 | import android.graphics.Bitmap;
5 | import android.graphics.BitmapShader;
6 | import android.graphics.Canvas;
7 | import android.graphics.Color;
8 | import android.graphics.Matrix;
9 | import android.graphics.Paint;
10 | import android.graphics.RectF;
11 | import android.graphics.Shader;
12 |
13 | import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
14 | import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
15 |
16 | /**
17 | * Created by Tudor Luca on 15/10/15.
18 | */
19 | public class CircleTransformation extends BitmapTransformation {
20 |
21 | public static final int PAINT_FLAGS = Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG;
22 | private final float mBorderWidth;
23 | private final int mBorderColor;
24 |
25 | public CircleTransformation(Context context) {
26 | super(context);
27 | mBorderWidth = 0;
28 | mBorderColor = Color.TRANSPARENT;
29 | }
30 |
31 | public CircleTransformation(Context context, float borderWidth, int borderColor) {
32 | super(context);
33 | mBorderWidth = borderWidth;
34 | mBorderColor = borderColor;
35 | }
36 |
37 | @Override
38 | protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
39 | final Bitmap toReuse = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
40 | Bitmap transformed = circleCrop(toReuse, toTransform, outWidth, outHeight, mBorderWidth, mBorderColor);
41 | if (toReuse != null && toReuse != transformed && !pool.put(toReuse)) {
42 | toReuse.recycle();
43 | }
44 | return transformed;
45 | }
46 |
47 | public Bitmap circleCrop(Bitmap recycled, Bitmap toTransform, int width, int height,
48 | float borderWidth, int borderColor) {
49 | if (toTransform == null) {
50 | return null;
51 | }
52 |
53 | final Bitmap result;
54 | if (recycled != null) {
55 | result = recycled;
56 | } else {
57 | result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
58 | }
59 |
60 | final float size = Math.min(width, height);
61 | final float x = width / 2f;
62 | final float y = height / 2f;
63 | final float imageSize = size - 2 * borderWidth;
64 |
65 | Shader shader = new BitmapShader(toTransform, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
66 | Matrix m = computeCenterFitMatrix(toTransform, width, height);
67 | m.postTranslate(borderWidth, borderWidth);
68 | shader.setLocalMatrix(m);
69 |
70 | Canvas canvas = new Canvas(result);
71 | Paint paint = new Paint(PAINT_FLAGS);
72 | paint.setShader(shader);
73 |
74 | float r = imageSize / 2;
75 | canvas.drawCircle(x, y, r, paint);
76 |
77 | Paint borderPaint = new Paint(PAINT_FLAGS);
78 | borderPaint.setStyle(Paint.Style.STROKE);
79 | borderPaint.setStrokeWidth(borderWidth);
80 | borderPaint.setColor(borderColor);
81 |
82 | r = (size - borderWidth) / 2;
83 | canvas.drawCircle(x, y, r, borderPaint);
84 |
85 | return result;
86 | }
87 |
88 | private Matrix computeCenterFitMatrix(Bitmap toFit, float width, float height) {
89 | RectF bitmap = new RectF(0, 0, toFit.getWidth(), toFit.getHeight());
90 | RectF dest = new RectF(0, 0, width, height);
91 | Matrix m = new Matrix();
92 | m.setRectToRect(bitmap, dest, Matrix.ScaleToFit.CENTER);
93 | return m;
94 | }
95 |
96 | @Override
97 | public String getId() {
98 | return "CircleTransformation";
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/utils/os/_Intents.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.utils.os
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.os.Parcelable
7 | import org.jetbrains.anko.intentFor
8 | import java.io.Serializable
9 | import kotlin.properties.ReadOnlyProperty
10 | import kotlin.reflect.KProperty
11 |
12 | /**
13 | * Delegated Property that will grab its value from the activity's intent.
14 | *
15 | * @sample
16 | * val uid: Long? by intentExtra("uid")
17 | */
18 | inline fun intentExtra(key: String): ReadOnlyProperty {
19 | return IntentProperty(key, T::class.java)
20 | }
21 |
22 | class IntentProperty(val key: String, val cls: Class) : ReadOnlyProperty {
23 | override fun getValue(thisRef: Activity, property: KProperty<*>): T? {
24 | return thisRef.getExtra(key, cls)
25 | }
26 | }
27 |
28 | inline fun Activity.getExtra(key: String): T? {
29 | return intent.getExtra(key, T::class.java)
30 | }
31 |
32 | fun Activity.getExtra(key: String, cls: Class): T? {
33 | return intent.getExtra(key, cls)
34 | }
35 |
36 | inline fun Intent?.getExtra(key: String): T? {
37 | return getExtra(key, T::class.java)
38 | }
39 |
40 | @Suppress("UNCHECKED_CAST", "IMPLICIT_CAST_TO_UNIT_OR_ANY")
41 | fun Intent?.getExtra(key: String, cls: Class): T? {
42 | if (this == null || !hasExtra(key)) return null
43 | return when {
44 | cls == String::class -> getStringExtra(key)
45 | cls == Int::class -> getIntExtra(key, 0)
46 | cls == Long::class -> getLongExtra(key, 0L)
47 | Serializable::class.java.isAssignableFrom(cls) -> getSerializableExtra(key)
48 | Parcelable::class.java.isAssignableFrom(cls) -> getParcelableExtra(key)
49 | // You get the picture. Add more if you need them!
50 | else -> throw IllegalArgumentException("Cannot get $cls from Intent")
51 | } as T?
52 | }
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/utils/twitter/_Tweets.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.utils.twitter
2 |
3 | import com.backstopmedia.kotlin.ktwitter.utils.functional.toMultimapBy
4 | import com.twitter.sdk.android.core.models.Tweet
5 | import com.twitter.sdk.android.core.models.User
6 | import rx.Observable
7 |
8 | fun List.tweetsByUser(): Map> {
9 | return toMultimapBy { it.user.id }
10 | }
11 |
--------------------------------------------------------------------------------
/twitter-app/src/main/java/com/backstopmedia/kotlin/ktwitter/utils/twitter/_Users.kt:
--------------------------------------------------------------------------------
1 | package com.backstopmedia.kotlin.ktwitter.utils.twitter
2 |
3 | import com.backstopmedia.kotlin.ktwitter.entities.RankedUser
4 | import com.twitter.sdk.android.core.models.User
5 |
6 | fun List.userMap(): Map = toMapBy { it.user.id }
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-hdpi/background.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-hdpi/background.jpg
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-hdpi/ic_collections_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-hdpi/ic_collections_black_24dp.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-hdpi/ic_collections_bookmark_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-hdpi/ic_collections_bookmark_black_24dp.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-hdpi/ic_people_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-hdpi/ic_people_black_24dp.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-hdpi/ic_plus.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-hdpi/ic_plus.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-hdpi/kotlin_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-hdpi/kotlin_logo.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-hdpi/retweet_light.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-hdpi/retweet_light.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-mdpi/ic_people_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-mdpi/ic_people_black_24dp.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-xhdpi/ic_people_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-xhdpi/ic_people_black_24dp.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-xxhdpi/ic_people_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-xxhdpi/ic_people_black_24dp.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/drawable-xxxhdpi/ic_people_black_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/drawable-xxxhdpi/ic_people_black_24dp.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/activity_coordinator_recycler.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
23 |
24 |
25 |
26 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/activity_followers.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
12 |
13 |
22 |
23 |
24 |
25 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/activity_login.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/activity_timeline.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
22 |
23 |
24 |
25 |
29 |
30 |
36 |
37 |
44 |
45 |
46 |
47 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/activity_top_images.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
23 |
24 |
25 |
26 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/drawer_header.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
19 |
20 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/grid_item_top_image.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
12 |
13 |
19 |
20 |
30 |
31 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/list_item_follower.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
18 |
19 |
23 |
24 |
30 |
31 |
37 |
38 |
43 |
44 |
52 |
53 |
61 |
62 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/list_item_header.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/list_item_user.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
18 |
19 |
27 |
28 |
37 |
38 |
47 |
48 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/layout/navigation_drawer_base.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/menu/navigation_view_items.xml:
--------------------------------------------------------------------------------
1 |
2 |
23 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/backstopmedia/kotlin/0236fc25a9de619ad22bcc49e6403272130d06e4/twitter-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/twitter-app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 | #F000
8 | #8000
9 | #4000
10 | #2000
11 |
12 | #F44336
13 | #4CAF50
14 | #2196F3
15 |
16 |
17 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 16dp
5 | 8dp
6 |
7 | 25dp
8 |
9 | 64dp
10 |
11 | 8dp
12 | 16dp
13 | 72dp
14 |
15 | 16sp
16 | 14sp
17 | 12sp
18 |
19 |
20 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | KTwitter
3 |
4 | Timeline
5 | Top Images
6 | Followers
7 | KTwitter
8 | No Tweets
9 | Who To Follow
10 | Follow
11 | Following
12 |
13 |
14 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/values/strings_accessibility.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | User avatar
4 | Open navigation drawer
5 | Close navigation drawer
6 | Tweeted image
7 |
--------------------------------------------------------------------------------
/twitter-app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
13 |
--------------------------------------------------------------------------------