package com.example.android.justjava; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.TextView; import java.text.NumberFormat; public class MainActivity extends ActionBarActivity { int quantity = 2; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void increment(View view){ quantity = quantity + 1; display(quantity); } public void decrement(View view){ quantity = quantity - 1; display(quantity); } public void submitOrder(View view){ displayPrice(quantity * 5); } private void display(int number){ TextView quantityTextView = (TextView) findViewById( R.id.quantity_text_view); quantityTextView.setText("" + number); } private void displayPrice(int number){ TextView priceTextView = (TextView) findViewById(R.id.price_text_view); priceTextView.setText(NumberFormat.getCurrencyInstance().format(number)); } }
<LinearLayout xmlns:android="http://schemas.android." xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical" android:paddingLeft="@dimen/activity_horizontal" android:paddingRight="@dimen/activity_horizontal" android:paddingTop="@dimen/activity_vertical" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:text="Quantity" android:textAllCaps="true" /> <Button android:layout_height="48dp" android:layout_width="48dp" android:text="+" android:onClick="increment" /> <TextView android:id="@+id/quantity_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0" android:textSize="16sp" adnroid:textColor="@android:color/black" /> <Button android:layout_height="48dp" android:layout_width="48dp" android:text="-" android:onClick="decrement" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Price" android:textAllCaps="true" /> <TextView android:id="@+id/price_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="$0" android:textSize="16sp" adnroid:textColor="@android:color/black" /> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginTop="16dp" android:text="Order" android:onClick="submitOrder" /> </LinearLayout>