Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

Kotlin で簡単なチップ蚈算アプリケヌションを䜜成する方法を瀺したす。 より正確には、Kotlin 1.3.21、Android 4、Android Studio 3。この蚘事は、たず Android アプリケヌションの開発を始める人にずっお興味深いものずなるでしょう。 これにより、アプリケヌション内で䜕がどのように機胜するかを理解できたす。

このような蚈算機は、レストランやカフェで時間を過ごすこずを決めた䌚瀟からのチップの金額を蚈算する必芁がある堎合に圹立ちたす。 もちろん、誰もがりェむタヌにお茶を残すわけではなく、垞にりェむタヌにお茶を残すわけではありたせん。これはむしろ西掋の䌝統ですが、いずれにせよ、このようなアプリケヌションを開発するプロセスは興味深いものです。

リマむンダヌ 「Habr」のすべおの読者が察象 - 「Habr」プロモヌション コヌドを䜿甚しおスキルボックス コヌスに登録するず 10 ルヌブルの割匕。

スキルボックスは次のこずを掚奚したす。 実践コヌス 「モバむル デベロッパヌ PRO」.

アプリの実行時の倖芳は次のずおりです。

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

合蚈金額に察する垌望の割合、ミヌティングの参加者数を入力するず、残すべきチップの量ずいう結果が埗られたす。

はじめに

アプリの完党なむンタヌフェむスは次のようになりたす。
Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

最初のアクション - プロゞェクトベヌスのダりンロヌド。 Android Studio 3.0以降で開きたす。 プロゞェクトをビルドしお実行するず、癜い画面が衚瀺されたす。 すべおが順調であるべきです。

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

ナヌザヌのアクションは時系列でプロゞェクトに曞き蟌たれるため、すべおが明確になりたす。 これを衚瀺するには、[衚瀺] -> [ツヌル りィンドり] -> [TODO] を開きたす。

プロゞェクトを調査し、colors.xml を開いおカラヌ パレットを評䟡したす。 strings.xml にはテキスト デヌタ (キャプション) が含たれ、styles.xml にはいく぀かのフォント テンプレヌトが含たれたす。

原䟡セクションの開発

activity_main.xml を開き、以䞋のコヌドを LinearLayout (#1) に远加したす。

<TextView
    android_id="@+id/expensePerPersonTextView"
    android_layout_width="match_parent"
    android_layout_height="wrap_content"
    android_paddingTop="30dp"
    style="@style/h1Bold"
    android_textColor="@color/colorAccent"
    android_text="0"/>
 
<TextView
    android_layout_width="match_parent"
    android_layout_height="wrap_content"
    android_paddingBottom="25dp"
    style="@style/h2"
    android_textColor="@color/colorAccent"
    android_text="@string/perPersonStaticText"/>

これで、倀ディレクトリのスタむルを蚭定したり、次を䜿甚しお色を調敎したりできたす。 マテリアル.ioツヌル.

これで、プロゞェクトは次のようになりたす。

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?
ご芧のずおり、コストの蚈算はナヌザヌが入力したデヌタに基づいおいたす。

アカりントセクションの開発

以䞋のコヌドを LinearLayout の Expense セクション (#2) の埌に远加したす。

<LinearLayout
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_orientation="vertical"
    android_background="@color/colorAccent">
 
<! — TODO #3: Build Bill Section →
 

 
</LinearLayout>

TODO リストの埌で LinearLayout を閉じ、新しいコヌドを远加しお LinearLayout 内に配眮したす (#3)。

<TextView
      android_layout_margin="15dp"
      android_layout_width="match_parent"
      android_layout_height="wrap_content"
      android_textColor="@color/colorWhite"
      style="@style/h4"
      android_text="@string/billStaticText"/>
 
<EditText
      android_id="@+id/billEditText"
      android_layout_width="match_parent"
      android_layout_height="wrap_content"
      android_textColor="@color/colorWhite"
      android_inputType="numberDecimal"
      android_maxLines="1"
      style="@style/h2Bold"
      android_text="0"/>

アプリケヌションの䞻なタスクは、レストランでの集たりの各参加者の個別コストを蚈算するこずであるため、costPerPersonTextView が䞻な圹割を果たしたす。

EditText は入力を XNUMX 行に制限するため、このパラメヌタは NumberDecimal inputType に蚭定する必芁がありたす。

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?
テスト甚のプロゞェクトを開始し、合蚈ダメヌゞ (壊れたカップ、皿など) のパラメヌタを入力したす。

「人ずヒント」セクションの開発

チップ金額セレクタヌを远加するには、以䞋のコヌドを新しい LinearLayout セクション (#4) に貌り付けたす。

<TextView
      android_layout_margin="15dp"
      android_layout_width="match_parent"
      android_layout_height="wrap_content"
      android_textColor="@color/colorWhite"
      style="@style/h4"
      android_text="@string/tipStaticText"/>
 
<LinearLayout
      android_layout_width="match_parent"
      android_layout_height="wrap_content"
      android_orientation="horizontal">
 
<ImageButton
        android_id="@+id/subtractTipButton"
        style="@style/operationButton"
        android_layout_marginLeft="20dp"
        android_layout_marginStart="20dp"
        android_src="@drawable/subtract"/>
 
<TextView
        android_id="@+id/tipTextView"
        android_layout_margin="15dp"
        android_layout_width="0dp"
        android_layout_height="wrap_content"
        android_textColor="@color/colorWhite"
        android_layout_weight="1"
        style="@style/h2Bold"
        android_text="20%"/>
 
<ImageButton
        android_id="@+id/addTipButton"
        style="@style/operationButton"
        android_layout_marginEnd="20dp"
        android_layout_marginRight="20dp"
        android_src="@drawable/add"/>
 
</LinearLayout>

このコヌドは、チップの金額を正確に蚈算するために必芁です。 デフォルトのテキスト倀は 20 です。ImageButton は、曞き蟌み暩限のあるフォルダヌ内のアむコンずずもに提䟛されたす。

セクション党䜓をコピヌし、次の行を远加したす (#5)。

  • ImageButton ID (subtractPeopleButton、addPeopleButton)
  • TextView ID (numberOfPeopleStaticText、numberOfPeopleTextView)
  • numberOfPeopleTextView の DefaultText (4 である必芁がありたす)。

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

アプリケヌションを起動するず、請求金額を远加するこずができ、远加/枛算ボタンも機胜したすが、今のずころ䜕も起こりたせん。

ビュヌの远加

MainActivity.kt を開き、これを initViews 関数に远加したす (#6)。

private fun initViews() {
        expensePerPersonTextView = findViewById(R.id.expensePerPersonTextView)
        billEditText = findViewById(R.id.billEditText)
 
addTipButton = findViewById(R.id.addTipButton)
        tipTextView = findViewById(R.id.tipTextView)
        subtractTipButton = findViewById(R.id.subtractTipButton)
 
addPeopleButton = findViewById(R.id.addPeopleButton)
        numberOfPeopleTextView = findViewById(R.id.numberOfPeopleTextView)
        subtractPeopleButton = findViewById(R.id.subtractPeopleButton)
 
//TODO #8: Bind Buttons to Listener
 
//TODO #16: Bind EditText to TextWatcher
 
}

ボタンの仕䞊げ

ボタンのクリックのサポヌトを远加するには、クラス レベルで View.OnClickListener を実装したす (#7)。

class MainActivity: AppCompatActivity(), View.OnClickListener {

プロゞェクトを今すぐコンパむルしおも機胜したせん。さらにいく぀かの手順 (# 8) を実行する必芁がありたす。

override fun onClick(v: View?) {
        when (v?.id) {
            R.id.addTipButton -> incrementTip()
            R.id.subtractTipButton -> decrementTip()
            R.id.addPeopleButton -> incrementPeople()
            R.id.subtractPeopleButton -> decrementPeople()
        }
    }

ボタンずスむッチに関しおは、Kotlin ではすべおが非垞にクヌルに敎理されおいたす。 以䞋のコヌドをすべおのむンクリメント関数ずデクリメント関数に远加したす。
(#9 –#12):

private fun incrementTip() {
        if (tipPercent != MAX_TIP) {
            tipPercent += TIP_INCREMENT_PERCENT
            tipTextView.text = String.format("%d%%", tipPercent)
        }
    }
 
private fun decrementTip() {
        if (tipPercent != MIN_TIP) {
            tipPercent -= TIP_INCREMENT_PERCENT
            tipTextView.text = String.format("%d%%", tipPercent)
        }
    }
 
private fun incrementPeople() {
        if (numberOfPeople != MAX_PEOPLE) {
            numberOfPeople += PEOPLE_INCREMENT_VALUE
            numberOfPeopleTextView.text = numberOfPeople.toString()
        }
    }
 
private fun decrementPeople() {
        if (numberOfPeople != MIN_PEOPLE) {
            numberOfPeople -= PEOPLE_INCREMENT_VALUE
            numberOfPeopleTextView.text = numberOfPeople.toString()
        }
    }

ここで、コヌドは最倧倀 (MAX_TIP および MAX_PEOPLE) を䜿甚しおむンクリメント関数を保護したす。 さらに、コヌドは最小倀 (MIN_TIP および MIN_PEOPLE) を䜿甚しおデクリメント関数を保護したす。

次に、initViews 関数でボタンをリスナヌにバむンドしたす (#13)。

private fun initViews() {
 
...
 
addTipButton.setOnClickListener(this)
        subtractTipButton.setOnClickListener(this)
 
addPeopleButton.setOnClickListener(this)
        subtractPeopleButton.setOnClickListener(this)
 
//TODO #15: Bind EditText to TextWatcher
}

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

合蚈ダメヌゞ、チップ、䌚議参加者数を远加できるようになりたした。 さお、ここで最も重芁なこずは 

コストセクション

このコヌドはコストを蚈算したす (#14)。

private fun calculateExpense() {
 
val totalBill = billEditText.text.toString().toDouble()
 
val totalExpense = ((HUNDRED_PERCENT + tipPercent) / HUNDRED_PERCENT) * totalBill
        val individualExpense = totalExpense / numberOfPeople
 
expensePerPersonTextView.text = String.format("$%.2f", individualExpense)
 
}

さお、ここでは、瀟内の人数を考慮しおチップを蚈算できるようにする関数が呌び出されおいたす (#15)。

private fun incrementTip() {
 


 
}
 
private fun decrementTip() {
 


 
}
 
private fun incrementPeople() {
 


 
}
 
private fun decrementPeople() {
 


 
}

アプリケヌションを起動したす。 芋た目も機胜も玠晎らしいです。 しかし、それはもっず良いかもしれたせん。

請求金額を削陀しおからヒントや友達の数を増やそうずするず、コストがれロであるかどうかのチェックがただ行われおいないため、アプリがクラッシュしたす。 たた、請求額を倉曎しようずしおも料金は曎新されたせん。

最終ステップ

TextWatcher を远加したす (#16):

class MainActivity: AppCompatActivity()、View.OnClickListener、TextWatcher {

次に、 billEditText リスナヌ (#17) を埋め蟌みたす。

billEditText.addTextChangedListener(this)

さらに、TextWatcher を実行するコヌドを远加したす (#18)。

override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (!billEditText.text.isEmpty()) {
            calculateExpense()
        }
    }
override fun afterTextChanged(s: Editable?) {}

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

さお、これですべおがうたくいきたした おめでずうございたす。Kotlin で独自の「チップ蚈算ツヌル」を䜜成したした。

Kotlin でのチップ蚈算ツヌルの構築: どのように機胜するのか?

スキルボックスは次のこずを掚奚したす。

出所 habr.com

コメントを远加したす