Getting Started with Anko3:33 with Ben Deitch
In this video we'll see how we can use Anko to create a layout right inside our Activity!
We've just finished creating a simple counter app using Kotllin's Android 0:00 extensions, and now it's officially time we get back to Anko. 0:04 But before we do anything with Anko, 0:08 let's get rid of all the parts of our project that we won't be needing. 0:10 And MainActivity, let's delete everything in onCreate except the call to super and 0:14 our counter variable. 0:19 And let's also delete this now unneeded import statement. 0:24 Next, and the project pane inside the res directory, let's delete the layout folder. 0:30 Then let's open our values folder and delete the dimens directory, 0:40 which was only being used by our XML layout. 0:45 Finally, let's open our app's build.gradle file and 0:52 remove the kotlin-android-extensions plugin. 0:55 Next, just like most libraries, 1:02 the first thing we need to do with Anko is add it as a dependency. 1:04 So let's add a line below our Kotlin dependency and 1:08 then you can copy and paste in the Anko dependency from the teacher's notes. 1:11 Then let's sync the project And 1:17 close our build.gradle files. 1:22 And now we should be ready to roll with Anko. 1:27 To start learning Anko, let's try and 1:30 rebuild our simple counter app from the previous video. 1:32 Inside the OnCreate function, 1:36 let's make sure there's some space after we set our counter variable. 1:38 And then let's type relativeLayout and pick the one with the brackets. 1:41 Next, inside our relativeLayout let's create a new val to 1:48 store our text view named counterTextView. 1:52 And let's set it equal to textView And pick the option with the brackets. 1:58 And then inside our textView, let's set text = "0" as a string. 2:07 And textSize, = 24f. 2:16 With Anko, text size is given as a float, and by default the units are SP. 2:22 So this is the exact same text size as before. 2:28 Now that we've got our textView, let's move on to our button. 2:32 Let's add a line below our textView, and 2:36 then since we don't need our button as a variable, let’s just declare it. 2:38 Let's type button and choose the option with the brackets. 2:43 Then, inside our button, let's type onClick to add the onClick listener. 2:48 And then we just need to increment our counter by one and update our textView. 2:56 So let's type counter++ and you'll 3:00 occasionally see bugs like this when you're developing with Kotlin and Anko. 3:05 They don't really affect anything, so we can just click them off. 3:09 Back in our button's onClick method, 3:13 let's set counterTextView.text 3:19 =_counter.toString. 3:24 All that's left is putting our button below our textView, 3:28 which we'll get to in the next video. 3:31
You need to sign up for Treehouse in order to download course files.Sign up