How to Build a Calculator with Jetpack Compose - Android Studio Tutorial

Поделиться
HTML-код
  • Опубликовано: 21 май 2022
  • In this video, we'll build a simple calculator using Jetpack Compose :)
    ⭐ Get certificates for your future job
    ⭐ Save countless hours of time
    ⭐ 100% money back guarantee for 30 days
    ⭐ Become a professional Android developer now:
    pl-coding.com/premium-courses...
    💻 Let me personally review your code and provide individual feedback, so it won't backfire and cost you a fortune in future:
    elopage.com/s/philipplackner/...
    Subscribe to my FREE newsletter for regular Android, Kotlin & Architecture advice!
    pl-coding.com/newsletter
    Join this channel to get access to perks:
    / @philipplackner
    Get the source code for this video here:
    github.com/philipplackner/Cal...
    Join my Discord server:
    / discord
    Regular programming advice on my Instagram page: / _philipplackner_
    Checkout my GitHub: github.com/philipplackner
    You like my free content? Here you can buy me a coffee:
    www.buymeacoffee.com/philippl...

Комментарии • 145

  • @nipunkumarit2168
    @nipunkumarit2168 2 года назад +49

    I'm gonna upgrade this to the scientific level.

  • @gauravthakkar802
    @gauravthakkar802 2 года назад +48

    Just a readability hack I found
    Instead of using a data class Operation inside a sealed class CalculatorOperation we could just another sealed class
    Example:
    sealed class CalculatorAction {
    data class Number(val number: Int) : CalculatorAction()
    object Clear : CalculatorAction()
    object Delete : CalculatorAction()
    object Decimal : CalculatorAction()
    object Calculate : CalculatorAction()
    //Instead of this
    //data class Operation(val operation: CalculatorOperation) : CalculatorAction()
    //Use this
    sealed class CalculatorOperation(val symbol: String) : CalculatorAction(){
    object Add : CalculatorOperation("+")
    object Subtract : CalculatorOperation("-")
    object Divide : CalculatorOperation("/")
    object Multiply : CalculatorOperation("*")
    }
    }
    Readability benfit:
    // This is better
    onClick = {
    onAction(CalculatorAction.CalculatorOperation.Divide)
    })
    //than this
    onClick = {
    onAction(CalculatorAction.Operation(CalculatorOperation.Divide))
    })

    • @romoram13
      @romoram13 Год назад +2

      Damn, this comment need more likes

  • @dontforgettovote531
    @dontforgettovote531 2 года назад +1

    i've been learning on the side and had to take a break because work stuff was keeping me busy, holy cow the new version launches the app super fast now when i recompile my code, gotta give the props for the android team

  • @b_mathemagical
    @b_mathemagical 2 года назад +27

    Thanks as always for the great content, Philipp. One modest suggestion that I feel could be helpful: I'd love to see @Preview annotations used and see the UI built iteratively. It's easier to see the effects of the code that's being written when the execution of the code happens piecemeal. It's a little harder to string together when it happens all at once🙂.
    To be fair, coding along is an option, but sometimes I like to just hang back and enjoy the show.

  • @albertbo2178
    @albertbo2178 Год назад +2

    You are a genious. I expect one day to be able to think all the things as fast as you do with Kotlin

  • @brunonoveli6839
    @brunonoveli6839 4 месяца назад

    You are a really good teacher. I've been learning Kotlin mainly by watching your videos and it's been a great experience.

  • @a-zlearning6259
    @a-zlearning6259 5 месяцев назад

    Created it successfully, and modified it a little bit 🥰 Thanks Philipp, you are the best teacher ever!

  • @ninelivesforge6432
    @ninelivesforge6432 Год назад +14

    Thank you for this! As you said I was really overwhelmed with all the complex architecture and libraries in other tutorials, this is what I needed at my level! Please make more!

  • @RaivoDoc
    @RaivoDoc 2 месяца назад

    Really helpful videos for someone who's re-qualifying from data analytics world to Android. Keep up the good work!!!

  • @trejkaz
    @trejkaz 2 года назад +8

    I think this would actually be _simplified_ by adding support for more operations, because now you just input a big string of characters and finally calculate it by hitting =. So all the operation buttons can just be the same action as the digits.
    Also you could cut the repetitive code down very simply by defining a local function with the 4 params which vary and packing the calls to that on a single line for each button.

  • @sanjaybhatikar
    @sanjaybhatikar 11 месяцев назад

    Wonderful! Was wondering why you used sealed class vs enum for operations and I see you have another video for that. :) Mind-blown! ❣️

  • @sarthakvatsa5607
    @sarthakvatsa5607 17 дней назад

    Great one buddy. Helped a lot. Thanks!

  • @ingyukoh
    @ingyukoh 2 года назад +2

    I experience joy of elegant coding in Jetpack Compose without messy xml. Kotlin with Compose is now at the same level as SwiftUI without messy .xib associated with storyboard in UIKit. Great lecture, Thanks.

    • @farazahmed7
      @farazahmed7 Год назад

      but xml performance is sitll better

  • @mirchm
    @mirchm 2 года назад +5

    I already made a similar one in java, having something similar in compose is a good way for me to learn stuff. Thank you philip, now i can understand how to work in jetpack compose the correct way

    • @akashkroy
      @akashkroy 2 года назад +2

      hey, the best I found is the last 2 chapters of Headfirst Android 3rd edition. Those are really really good to understand how compose work. I found them better than the official material on compose.

    • @mirchm
      @mirchm 2 года назад

      @@akashkroy thank you for the advice, i will check them out

  • @mracipayam
    @mracipayam Год назад

    Thanks dude, it was so clear to understand.

  • @hasanforaty1536
    @hasanforaty1536 2 года назад +8

    thanks for the great video.
    there is a bug in 36:42 where for "number2" decimal you use the "number1" variable

  • @bugslayer-sama
    @bugslayer-sama Год назад

    Thank you, this was very helpful as always

  • @JJHaz
    @JJHaz 10 месяцев назад

    reallly helpful, thanks a lot philipp

  • @oubihinoureddine9025
    @oubihinoureddine9025 Год назад

    Thank you so much, great content love your videos

  • @user-dk4dl6pe1x
    @user-dk4dl6pe1x 2 месяца назад

    i have learn so much about Kotlin. I love your Videos

  • @musfickjamil2831
    @musfickjamil2831 2 года назад

    Thank you so much for this tutorial

  • @ailekzavy
    @ailekzavy Месяц назад

    Another fan!!!!! You're spectacular, I've been following your videos and honestly , I like you, you're so wonderful...thanks for your time...

  • @marekwalica4418
    @marekwalica4418 2 года назад

    Thank you, great tutorial

  • @miracleukaka4085
    @miracleukaka4085 Год назад +1

    Hello Phillip, so yeah, I did the assignment. I can carry out multiple operations. Though, I changed the layer above to contain two textviews, one for displaying input and the other for displaying result. Thanks once again.

    • @tar1885
      @tar1885 7 месяцев назад

      Wow. Mind sharing how you did it?I've tried it's not working for me.

  • @nadjlaau9267
    @nadjlaau9267 Месяц назад +1

    Thank u this was very helpful.

  • @learningSimplified2801
    @learningSimplified2801 2 года назад

    I search this on RUclips, you made my day..

  • @masoumi-td7fg
    @masoumi-td7fg Год назад

    great as always philipp

  • @michaelchristensen8350
    @michaelchristensen8350 2 года назад +1

    This was a great tutorial. I really hope you will do more simple basic tutorials like this

  • @beatricebastianello7372
    @beatricebastianello7372 3 месяца назад

    Thank you, it was great!!!

  • @timepasi
    @timepasi 5 дней назад

    Great video so much helpful great work :)

  • @nakrakanykrakowiaczek1187
    @nakrakanykrakowiaczek1187 Год назад

    Great tutorial, helped me with ViewModel when I was loosing hope to find solution of my problem, much thanks! :D
    Also I have a question: how did you push the modifier higher over buttonSpacing? Seem like some smart key comination

  • @gsrgae186
    @gsrgae186 Год назад

    Hope you will make an update for this app using Constraint layout. Nice video and very helpful!!

  • @mustafaammar551
    @mustafaammar551 2 года назад

    very cool video
    thank you BRO
    you are the best
    wish you all the best 🔥👍👍👍👍

  • @HerrThomasE
    @HerrThomasE Год назад

    Great!!!. Thank you very much!

  • @user-eo9gb1qq7n
    @user-eo9gb1qq7n 2 года назад

    thank you Philipp

  • @mattwalkgaming2626
    @mattwalkgaming2626 Год назад

    You are genius man

  • @HuynhDucPhu2502
    @HuynhDucPhu2502 6 дней назад

    Very very cool tutorial

  • @nguyencodervn
    @nguyencodervn Год назад

    Thank you Sir

  • @amritsohi6642
    @amritsohi6642 5 месяцев назад +1

    In enter decimal function, instead of writing number2=state.number2+"." you write number1=state.number2+"." Last thing it a nice project

  • @aboubakergb5929
    @aboubakergb5929 4 месяца назад

    Thanks One of the best Channel

  • @mikeschoch
    @mikeschoch 3 месяца назад

    Very good Video, please more stuff like this simple app in Compose, maybe some with an API Call to load some contacts in a lazy list or something like that.

  • @OrlanDroyd
    @OrlanDroyd 2 года назад +1

    It's really a good looking app
    Thx for the tutorial 🙏

  • @arielapp9469
    @arielapp9469 2 года назад +3

    it should be in android framework by default by now, but there is an operation called exhaustive, which if you add it to your when block, it forces you to add all the possible sealed classes possibilities (and will give you the option to do so) or add an else block.
    very handy indeed.
    it looks like this
    val T.exhaustive: T
    get() = this
    you add it to your util file, and can use it wherever you want.

  • @UhuPost
    @UhuPost 2 месяца назад

    that's very cool👍🏽

  • @jcdiezdemedina
    @jcdiezdemedina 2 года назад

    Thx for the video... Which plugin are you using?

  • @raheemadamboev
    @raheemadamboev 2 года назад

    Amazing video 🌟🌟🌟

  • @irvansyahnuradis-0614
    @irvansyahnuradis-0614 2 года назад

    Nice vid bro I dropped a like and a sub

  • @denisk3852
    @denisk3852 2 года назад

    Great!

  • @shock1136
    @shock1136 Год назад

    Hello Phillip Knacker. In the beginning of this video. You said that this is for those who have an idea of the basics of JetPack Compose. Does this mean I have to know at least the small basics of JetPack Compose before embarking on this project?? Just asking

  • @orhanavan7222
    @orhanavan7222 Год назад

    10/10 architecture

  • @marsgrib
    @marsgrib 2 года назад

    Great video! Thank you!
    How update viewModel from Service?

  • @clamum9648
    @clamum9648 2 года назад +2

    Great idea for a video big 🐕. I like that it's a realistic, full project but not overly complicated.
    I'm rewriting my super old Java/XML Android app in Compose/Kotlin/Room, learning all as I go, and decided to use Clean Architecture too. But man for my simple app that is way too unnecessarily complicated. There's about 4 times the files and code of my old app and I'm about half done lmao.
    I can see CA being useful for more complex apps and apps that a team works on, but for a small app by a single developer? No way, way overkill imo.

  • @ageingdragon8132
    @ageingdragon8132 2 года назад

    You are the fucking best ever Time a have a default thing that needs explaining your the man to go to... I hope you know how much we appreciate you..

  • @user-cs4dl3kk8r
    @user-cs4dl3kk8r 2 года назад

    Hello tell me pls what theme you use in android studio?

  • @abacaabaca8131
    @abacaabaca8131 10 месяцев назад +3

    @22:02
    luckily for me, I can populate the buttons using an array of buttons.
    because the button is actually the same object, it only differs in width in two areas (or elements).
    if we use the formula to linearize the 2d space into 1d space we can define it like this:
    f(i)=y*w+x
    where:
    'i' is the index,
    'y' is the index of y with the range of 0 to 4
    'x' is the index of x with the range of 0 to 4 except when y=0 and y=4, its range is 0 to 2
    so, since the number of buttons object is 4*5-2 = 18
    we can do for loop.
    in that for loop we can populate a homogenous attributes to all button object first for the color, then we can explicitly change certain attributes of the button.
    for example, button[0] and button[15] to have wider attribute for the size to be drawn on the screen. For button[0] and button[1] they have light grey color attribute.
    For the operation button, we can use % modulo operator to give orange color.
    like:
    if i%4==0:
    button[i].color=Color.orange
    button[17]=Color.orange
    and we are done.

  • @kbakhal5
    @kbakhal5 Год назад

    @Philipp: Is there is any way to create project KMP using jetpack library rather than jetpack compose. There is no setting while creating project of KMP. It is by default creating project using jetpack compose library. There should be a option to do so while creating project of KMP .

  • @karllviii
    @karllviii 8 месяцев назад +1

    I have created a calculator like this. It was in one class 400 columns and it takes nearly 4 hours.

  • @aistepan
    @aistepan 10 месяцев назад

    Спасибо!

  • @cgcrack4672
    @cgcrack4672 Год назад

    Hello phillip this is a non related question but, do you know which technology I can use to automate apps,Like i want to create an app that automate WhatsApp message,I know aapium out there,but there is no reference how to implement as an app,Can you please tell me!.

  • @thousandcranes3045
    @thousandcranes3045 2 года назад

    Philip can I know what your android studio theme is?
    I've been getting into native android recently, previously I've always worked in VS Code and I can't find a theme that I like. This one seems pretty cool to try

  • @brunno_gonzalez_dev
    @brunno_gonzalez_dev 2 года назад

    🔥🔥🔥🔝

  • @omamaashraf1694
    @omamaashraf1694 9 месяцев назад

    Can I start my development journey with jetpack compose If I'm a beginner or first I should go for XML one then switch on jetpack compose ????

  • @mertozankahraman
    @mertozankahraman 11 месяцев назад +1

    Adamın hası, hası

  • @letscoding3421
    @letscoding3421 2 года назад

    That is a great tutorial, could you make another tutorial about authentication especially firebase authentication with google credential in correct way? Thanks!!

  • @mrdeveloper4438
    @mrdeveloper4438 2 года назад

    Nice content but there should be history like normal calculator app

  • @viveksingh9223
    @viveksingh9223 2 года назад

    I already saw this one coming.

  • @hossamqandel5303
    @hossamqandel5303 2 года назад

    Hi phil.. i am always enter ur channel everyday and it helps me a lot... I am just wanna ask u if u could make these tutorials or at least one of them
    - Simple validation clean arch
    - how to handle lifecycle with many real examples
    - paging 3
    Oh and all of them by xml not the compose please 😂

  • @ibrahimal-zaidi6436
    @ibrahimal-zaidi6436 2 года назад

    Hi Philipp why you don't sale your courses on Udemy?

  • @sandek1878
    @sandek1878 2 года назад

    Woow woow

  • @user-yl6iq8fn7z
    @user-yl6iq8fn7z 2 года назад

    Actually, I made the UI and the final row overlaps with the above row because there is not much space. This is solved if I use scrollState on the column or lower the fontSize of the Text, but what is the optimal way of designing it so that it is smoothly running on all devices?

    • @PhilippLackner
      @PhilippLackner  2 года назад +1

      Give the Calc section a weight of 1f and the button section no weight

    • @user-yl6iq8fn7z
      @user-yl6iq8fn7z 2 года назад

      @@PhilippLackner Wow, that worked. Checked the documentation about how weight works when some children are unweighted. Thanks Philipp!

    • @peter4vn
      @peter4vn 8 месяцев назад

      I fixed it by replacing the line
      fontSize = 80.sp,
      to
      style = TextStyle(fontSize = 80.sp),

  • @AbhishekTiwari-of8hp
    @AbhishekTiwari-of8hp 2 года назад

    how to make table from json data dynamically through kotlin code volley without using xml

  • @abacaabaca8131
    @abacaabaca8131 10 месяцев назад

    @19:33 Initially I was confused with how Compose work. Because, it is just a function annotated with `@Composable` keyword with multiple parameters.
    In the parameter we can set the default value for the function.
    Inside the body of the function, we can set the layout of that compose such as the Box compose which is also a function, here inside the Box's parameter is the place where we can set the attribute for that Box, but in it's body,
    It will specify the children element of that Box. For example, a Column compose as the children of Box.
    So, it is like xml file, where we can set the attribute of an element, or declare a children element.
    In a nutshell, in the Compose function's:
    1. parameter : specify the attribute of that particular Compose element.
    2. body: specify the children element of that particular Compose element.

    • @abacaabaca8131
      @abacaabaca8131 10 месяцев назад

      If we want multiple children element let say inside Column, we have 2 children elements:
      1. Text
      2. Row
      we do not need to put comma ","
      also for `Text` element it does not need a "body" or children.

  • @Tejaswibhagat
    @Tejaswibhagat Год назад

    hey im unable to use fontWeigth in calculator.kt please help

  • @punyani775
    @punyani775 7 месяцев назад

    Please someone answer my question. At 15:31, if you want to retain the state after the screen rotates shouldn't the ViewModel be:
    "var state by rememberSaveable {mutableStateOf(CalculatorState()) }"
    Instead of what's in the video:
    var state by mutableStateOf(CalculatorState())

    • @PhilippLackner
      @PhilippLackner  7 месяцев назад

      No, in the viewmodel there's no composition which the state would need to survive

    • @punyani775
      @punyani775 7 месяцев назад

      @@PhilippLackner isn’t the purpose of the view model to keep the state after the screen rotates and it’s destroyed?
      I thought rememberSavable was the only way to stop the state from getting destroyed after a configuration change like rotating your screen so why does mutableState work too or does it have a different purpose?

    • @PhilippLackner
      @PhilippLackner  7 месяцев назад

      @@punyani775 if you store the state in the composable itself, rememberSaveable is needed. But in a viewmodel it's save since that has a different livecycle

    • @punyani775
      @punyani775 7 месяцев назад

      @@PhilippLackner I see. Thank you 🙏🏽

  • @priyanshukumar2606
    @priyanshukumar2606 Год назад

    My buttons are not working, whenever I click on any button it does not show up on the text field, please help

  • @marekzet482
    @marekzet482 10 месяцев назад

    Good video but this calculator can operate only at two numbers. It is unable to perform operation for 3 and more numbers like: 25+32+5 =

  • @gamesforu6619
    @gamesforu6619 2 года назад

    Why you haven't use constraint layout ?

    • @favour2871
      @favour2871 Год назад +1

      u dont need to. nesting is fine

  • @omamaashraf1694
    @omamaashraf1694 9 месяцев назад

    I'm getting error in text sir like annotationstring textunit , that's because i'm unable to run my app

  • @draman8414
    @draman8414 10 месяцев назад

    Using a key and value with a loop would work

  • @2050Debanjan
    @2050Debanjan 7 месяцев назад +1

    while following this tutorial while 15:56 viewModel is showing unresolved reference, i am using emptyactivity in android studio giraffe?????? please help!!!! !!!!!!!!!!!!!!!!!! i have found similar problem in stack overflow but no solution given

    • @hkjk0
      @hkjk0 7 месяцев назад +1

      Do you have?
      ...
      import androidx.lifecycle.ViewModel
      import androidx.compose.runtime.*
      and in build.gradle > implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2"
      Tip: Hover and use Alt-Enter when it suggests imports

    • @2050Debanjan
      @2050Debanjan 7 месяцев назад +1

      @@hkjk0 I have it but same issue suggestions are create local variable, property ,object, parameter. have viewModels() though not viewModel()

    • @hkjk0
      @hkjk0 7 месяцев назад

      @@2050Debanjan and you synced it? (I had similar issues, but would have to start all over again to reproduce the solution)

    • @hkjk0
      @hkjk0 7 месяцев назад

      Also, is anything else blowing red?

    • @2050Debanjan
      @2050Debanjan 7 месяцев назад

      @@hkjk0 solved after syncing ..there was sybcing issue

  • @AlbertEinsteinOfficialYt
    @AlbertEinsteinOfficialYt 5 месяцев назад

    12:33 why you don't use sealed interface instead of class 😅😅😅

  • @KamranKhan-lg8in
    @KamranKhan-lg8in 2 года назад

    How to remove that decimal from result i.e 5+5 = 10.0 how to remove that .0 ?

  • @user-dk4dl6pe1x
    @user-dk4dl6pe1x 2 месяца назад

    now i see my calculator from a different perspective 😅

  • @RomanAisly
    @RomanAisly 10 месяцев назад +1

    I made this app as on the video, but I have the collision in result field

    • @Luffy_2804
      @Luffy_2804 10 месяцев назад

      did you understand every bit of thing ? for how much time have you been learning android dev ?

    • @RomanAisly
      @RomanAisly 10 месяцев назад

      I made it correct
      @@Luffy_2804

  • @Lucky_Mirror
    @Lucky_Mirror 6 дней назад

    Where is thousend separator?

  • @andrewdunbar828
    @andrewdunbar828 9 месяцев назад

    Cullem cullem cullem cullem

  • @mirniyazulhaque3583
    @mirniyazulhaque3583 Год назад +1

    Having an issue:
    When i click on the numbers it’s not displaying the numbers.. where could be the mistake

    • @priyanshukumar2606
      @priyanshukumar2606 Год назад +1

      same problem bro. Have you resolved this issue yet?
      please answer this

    • @Luffy_2804
      @Luffy_2804 10 месяцев назад +1

      same issue is there any solution

    • @Luffy_2804
      @Luffy_2804 10 месяцев назад

      did you fixed it ? dude@@priyanshukumar2606

    • @Auggie_C
      @Auggie_C 9 месяцев назад

      in your CalculatorButton.kt, make sure the .clickable in your modifier inside your box is .clickable{ onClick() }
      If you use only .clickable {onClick}, it won't work

    • @mrtigeryt9558
      @mrtigeryt9558 8 месяцев назад

      did you got any solution

  • @tacozzitv7640
    @tacozzitv7640 2 года назад

    Hi phillip, ive been making an nft app in android studio and im struggling with the xml layout designs. Can you please make a video on an nft marketplace ui design?

  • @nonetrix3066
    @nonetrix3066 2 года назад

    What is this keyboard shortcut? sorry 3:24

    • @MohammadArif-gn7gr
      @MohammadArif-gn7gr 2 года назад

      I think there is no default keyboard shortcut in AS, but you can set your own by going to Setting -> Keymap -> search kotlin class/file and then you can use any shortcut which is not already assigned to any other

  • @user-uy7rr8hi8e
    @user-uy7rr8hi8e 2 года назад

    Hai anna iam Nagendar Anna na age 42 LIKESEX.Uno qualification m.l.t medical lab technicianc ,Srpt lo jobs unte cheppagalaru anna.with govt Jobs

  • @codybrown689
    @codybrown689 7 месяцев назад

    20:26
    41:22

  • @dislike__button
    @dislike__button 2 года назад

    Divide by zero. 🙂

  • @akenglishstudy
    @akenglishstudy 5 месяцев назад

    Probably it's good for someone, but it would be way better if you showed the visual changes while writing the code rather than just describing how it works. Thanks anyway.

  • @claudioLuna02
    @claudioLuna02 8 месяцев назад

    "With the layout preview while programming, it's better for understanding."😢

  • @ashwithchandra2622
    @ashwithchandra2622 Год назад

    Why u havent used textfield there coz in official google there is actually the implementation with text field what will you do when u have to change the number between the input please apply those changes and reupload the video....Thanks

  • @rahul_bali
    @rahul_bali Год назад

    The amount of files required to make this project in the jetpack compose is absurd. Google is trying, but this will down the drain. XML is much simpler and faster to implement.

    • @Luffy_2804
      @Luffy_2804 10 месяцев назад

      i agree but in this case only : ) but this is f** future

  • @kodeshower
    @kodeshower 5 месяцев назад

    your voice not clear

  • @sincapism
    @sincapism 2 года назад

    give up android compose :)

  • @user-mh1km3mv7z
    @user-mh1km3mv7z 4 месяца назад

    pretty garbage tutorials :/
    Where's JavaScript Mastery for Kotlin/Android? ugh :/

  • @dogu0101
    @dogu0101 Год назад

    Hello Philipp. I'm trying to modify the app to make multiple operations at the same time but I have an issue. I store the numbers in one list and operations in a different list so I will control if operation list contains a divison or multiplication first as they need to be done firstly. But things didn't go well with lists because I can't make change with state.copy on the middle of the lists. What can I do ? I'll appreciate any help.