Содержание

В моей предыдущей статье я написал подробные инструкции о том, как создать простое приложение для Android . В этом конкретном приложении я также объяснил понятия кнопки Android и основные понятия Android.
Все остальные мои статьи вы можете найти в разделе Android .
В этой статье мы создадим calculator android app , Это простой калькулятор с ограниченными функциональными возможностями.
Прежде чем мы продолжим, было бы неплохо пройти полный курс HelloWorld Tutorial. Вот снова ссылка: Мое первое приложение для Android HelloWorld
- Как создать простое приложение-калькулятор — полное руководство
- Создание простого калькулятора с помощью Android Studio
- Разработка Android: создание базового калькулятора
- Создать простое приложение для Android
- Как создать приложение калькулятор для Android
Давайте начнем с нашего приложения для калькулятора Android:
Шаг 1
- Откройте вашу Android Studio
- Нажмите «Начать новый проект Android Studio».
- Дайте название вашей заявки
CrunchifyCalculatorи оставьте другие поля пустыми, как есть, затем нажмите NEXT.

Шаг 2
- Выберите минимальный SDK
API 15: Android 4.0.3(IceCreamSandwich), Я выбрал API 15 (IceCreamSandwich), потому что он охватывает почти 94% устройств и обладает практически всеми функциями. Если вы хотите покрыть 100% устройства, вы можете выбрать API 8: Android 2.2 (Froyo).

Шаг 3
- Выберите
Empty Activityи нажмите ДАЛЕЕ. - Оставьте название деятельности
MainActivityкак есть и оставь все как есть. Нажмите Готово.

Шаг 4
- После нажатия кнопки «Готово» на создание действия и файлов уходит около 2 минут.
- Вот окончательная структура проекта для вашего приложения.

Шаг 5
- Теперь мы должны добавить наш Java-код в наш файл MainActivity.java.
- Так открою тебя
MainActivity.javaфайл с левой стороны IDE (приложение -> java -> com.crunchify.tutorials.crunchifycalculator -> MainActivity.java)
Вы можете найти объяснение выделенной строки под кодом.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
|
пакет ком . crunchify. учебники . хрустящий калькулятор ;
импорт андроид . ос . Расслоение ;
импорт андроид . поддержка. v7 . приложение AppCompatActivity ;
импорт андроид . вид. Вид ;
импорт андроид . виджет. Кнопка ;
импорт андроид . виджет. EditText ;
общественности учебный класс Основная деятельность продолжается AppCompatActivity {
Кнопка button0 , button1 , button2 , button3 , button4 , button5 , button6 ,
button7 , кнопка8 , button9 , кнопка Добавить , buttonSub , buttonDivision ,
buttonMul , кнопка10 , кнопка C , buttonEqual ;
EditText crunchifyEditText ;
поплавок mValueOne , mValueTwo ;
логический crunchifyAddition , mSubtract , crunchifyMultiplication , crunchifyDivision ;
@ Override
защищенный недействительным OnCreate (Пачка savedInstanceState) {
супер. onCreate ( saveInstanceState ) ;
setContentView (.. Р компоновка activity_main);
button0 знак равно ( Кнопка ) findViewById (.. R ID button0);
button1 знак равно ( Кнопка ) findViewById (.. R ID Button1);
button2 знак равно ( Кнопка ) findViewById (.. R ID button2);
Button3 знак равно ( Кнопка ) findViewById (.. R ID Button3);
Button4 знак равно ( Кнопка ) findViewById (.. R ID Button4);
button5 знак равно ( Кнопка ) findViewById (.. R ID button5);
Button6 знак равно ( Кнопка ) findViewById (.. R ID Button6);
Button7 знак равно ( Кнопка ) findViewById (.. R ID Button7);
Button8 знак равно ( Кнопка ) findViewById (.. R ID Button8);
Button9 знак равно ( Кнопка ) findViewById (.. R ID Button9);
Button10 знак равно ( Кнопка ) findViewById (.. R ID Button10);
buttonAdd знак равно ( Кнопка ) findViewById (R ID buttonadd..);
buttonSub знак равно ( Кнопка ) findViewById (.. R ID buttonsub);
buttonMul знак равно ( Кнопка ) findViewById (.. R ID buttonmul);
buttonDivision знак равно ( Кнопка ) findViewById (. R ID buttondiv.);
buttonC знак равно ( Кнопка ) findViewById (. R ID buttonC.);
buttonEqual знак равно ( Кнопка ) findViewById (.. R ID buttoneql);
crunchifyEditText знак равно ( EditText ) findViewById (.. R ID edt1);
кнопка1 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + «1» ) ;
}
} ) ;
кнопка2 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + 2 ) ;
}
} ) ;
кнопка3 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + «3» ) ;
}
} ) ;
кнопка4 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + 4 ) ;
}
} ) ;
кнопка5 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + 5 ) ;
}
} ) ;
кнопка6 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + «6» ) ;
}
} ) ;
кнопка7 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + 7 ) ;
}
} ) ;
кнопка8 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + «8» ) ;
}
} ) ;
кнопка9 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + 9 ) ;
}
} ) ;
кнопка0 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + «0» ) ;
}
} ) ;
Кнопка Добавить . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
если ( crunchifyEditText == ноль ) {
crunchifyEditText . setText ( ) ;
} еще {
mValueOne знак равно Поплавок. parseFloat ( crunchifyEditText . getText ( ) + ) ;
crunchifyAddition знак равно правда ;
crunchifyEditText . setText ( null ) ;
}
}
} ) ;
ButtonSub . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
mValueOne знак равно Поплавок. parseFloat ( crunchifyEditText . getText ( ) + ) ;
mSubtract знак равно правда ;
crunchifyEditText . setText ( null ) ;
}
} ) ;
ButtonMul . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
mValueOne знак равно Поплавок. parseFloat ( crunchifyEditText . getText ( ) + ) ;
crunchifyMultiplication знак равно правда ;
crunchifyEditText . setText ( null ) ;
}
} ) ;
ButtonDivision . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
mValueOne знак равно Поплавок. parseFloat ( crunchifyEditText . getText ( ) + ) ;
crunchifyDivision знак равно правда ;
crunchifyEditText . setText ( null ) ;
}
} ) ;
КнопкаEqual . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
mValueTwo знак равно Поплавок. parseFloat ( crunchifyEditText . getText ( ) + ) ;
если ( crunchifyAddition == правда ) {
crunchifyEditText . setText ( mValueOne + mValueTwo + ) ;
crunchifyAddition знак равно ложь ;
}
если ( mSubtract == правда ) {
crunchifyEditText . setText ( mValueOne — mValueTwo + ) ;
mSubtract знак равно ложь ;
}
если ( crunchifyMultiplication == правда ) {
crunchifyEditText . setText ( mValueOne * mValueTwo + ) ;
crunchifyMultiplication знак равно ложь ;
}
если ( crunchifyDivision == правда ) {
crunchifyEditText . setText ( mValueOne / mValueTwo + ) ;
crunchifyDivision знак равно ложь ;
}
}
} ) ;
buttonC. setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( ) ;
}
} ) ;
кнопка10 . setOnClickListener ( new Просмотр. OnClickListener ( ) {
@ Override
общественности недействительным OnClick ( Просмотр v ) {
crunchifyEditText . setText ( crunchifyEditText . getText ( ) + ) ;
}
} ) ;
}
}
|
Здесь у нас есть 1 EditText. Он определяет тип контента.
Давайте разберемся в коде немного больше.
- Строка 11 — 14: Здесь мы создали ссылку на кнопки и EditText.
- Строка 16: здесь мы создали две переменные типа float для значений1 и 2.
- Строка 21: мы переопределяем метод onCreate (), который является методом класса Activity .
- Строка 45 — 50: мы устанавливаем onClickListener на Button1. Если мы нажмем кнопку1, EditText будет отображаться.
- Мы реализовали одинаковую логику для каждой кнопки.
- Строка 115 — 127: Здесь мы установили прослушиватель щелчков на кнопке «Добавить».
- Здесь мы ставим условие так: если EditText равен Null, тогда мы устанавливаем EditText как пустое значение. В противном случае мы добавляем два значения, которые нажимаются до нажатия кнопки добавления и после нажатия кнопки добавления.
- Мы также установили
crunchifyAdditionЛогическое значение True. Это верно означает, что кнопка добавления нажата, и она будет использоваться, когда пользователь нажимает кнопку «=». - Мы реализуем ту же логику для других кнопок, таких как buttonSub, ButtonMul, buttonDivision.
- Строка 156 — 183: здесь мы устанавливаем clickListener на кнопку «=». Здесь мы ставим условие, как будто пользователь нажимает кнопку Добавить
crunchifyAdditionЗначение установлено в True для прослушивания щелчка кнопки «Добавить». - В соответствии с этим будет выполнено соответствующее действие, соответствующее нажатию кнопки.
|
1
2
3
4
|
если ( crunchifyAddition == правда ) {
crunchifyEditText . setText ( mValueOne + mValueTwo + ) ;
crunchifyAddition знак равно ложь ;
}
|
если кнопка «Добавить» нажата до кнопки «=», то действие «Добавить» будет выполнено, как показано выше.
- После выполненного действия мы устанавливаем
crunchifyAdditionзначение false, чтобы мы могли снова выполнить действие Add.
Ниже приведен файл макета, с помощью которого можно создать внешний интерфейс для калькулятора:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
|
xml version = 1.0 encoding = utf-8 ?>
< RelativeLayout xmlns : android = http://schemas.android.com/apk/res/android
xmlns : tools = http://schemas.android.com/tools
Android : ID = @ + ID / родственник1
android : layout_width = match_parent
android : layout_height = match_parent
tools : context = .MainActivity >
< EditText
android : id = @ + id / edt1
android : layout_width = match_parent
android : layout_height = wrap_content / >
< Кнопка
android : id = @ + id / button1
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignEnd = @ + id / button4
android : layout_alignRight = @ + id / button4
android : layout_below = @ + id / edt1
android : layout_marginTop = 94dp
android : text = 1 / >
< Кнопка
android : id = @ + id / button2
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignTop = @ + id / button1
android : layout_toLeftOf = @ + id / button3
android : layout_toStartOf = @ + id / button3
android : text = 2 / >
< Кнопка
android : id = @ + id / button3
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignTop = @ + id / button2
android : layout_centerHor horizontal = true
android : text = 3 / >
< Кнопка
android : id = @ + id / button4
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_below = @ + id / button1
android : layout_toLeftOf = @ + id / button2
android : text = 4 / >
< Кнопка
android : id = @ + id / button5
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignBottom = @ + id / button4
android : layout_alignLeft = @ + id / button2
android : layout_alignStart = @ + id / button2
android : text = 5 / >
< Кнопка
android : id = @ + id / button6
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignLeft = @ + id / button3
android : layout_alignStart = @ + id / button3
android : layout_below = @ + id / button3
android : text = 6 / >
< Кнопка
android : id = @ + id / button7
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_below = @ + id / button4
android : layout_toLeftOf = @ + id / button2
android : text = 7 / >
< Кнопка
android : id = @ + id / button8
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignLeft = @ + id / button5
android : layout_alignStart = @ + id / button5
android : layout_below = @ + id / button5
android : text = 8 / >
< Кнопка
android : id = @ + id / button9
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignLeft = @ + id / button6
android : layout_alignStart = @ + id / button6
android : layout_below = @ + id / button6
android : text = 9 / >
< Кнопка
android : id = @ + id / buttonadd
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignEnd = @ + id / edt1
android : layout_alignRight = @ + id / edt1
android : layout_alignTop = @ + id / button3
android : layout_marginLeft = 46dp
android : layout_marginStart = 46dp
android : layout_toRightOf = @ + id / button3
android : text = + / >
< Кнопка
android : id = @ + id / buttonsub
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignEnd = @ + id / buttonadd
android : layout_alignLeft = @ + id / buttonadd
android : layout_alignRight = @ + id / buttonadd
android : layout_alignStart = @ + id / buttonadd
android : layout_below = @ + id / buttonadd
android : text = — / >
< Кнопка
android : id = @ + id / buttonmul
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignLeft = @ + id / buttonsub
android : layout_alignParentEnd = true
android : layout_alignParentRight = true
android : layout_alignStart = @ + id / buttonsub
android : layout_below = @ + id / buttonsub
android : text = * / >
< Кнопка
android : id = @ + id / button10
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_below = @ + id / button7
android : layout_toLeftOf = @ + id / button2
android : text = . / >
< Кнопка
android : id = @ + id / button0
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignLeft = @ + id / button8
android : layout_alignStart = @ + id / button8
android : layout_below = @ + id / button8
android : text = 0 / >
< Кнопка
android : id = @ + id / buttonC
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignLeft = @ + id / button9
android : layout_alignStart = @ + id / button9
android : layout_below = @ + id / button9
android : text = C / >
< Кнопка
android : id = @ + id / buttondiv
style = ? android: attr / buttonStyleSmall
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignEnd = @ + id / buttonmul
android : layout_alignLeft = @ + id / buttonmul
android : layout_alignRight = @ + id / buttonmul
android : layout_alignStart = @ + id / buttonmul
android : layout_below = @ + id / buttonmul
android : text = / / >
< Кнопка
android : id = @ + id / buttoneql
android : layout_width = wrap_content
android : layout_height = wrap_content
android : layout_alignEnd = @ + id / buttondiv
android : layout_alignLeft = @ + id / button10
android : layout_alignRight = @ + id / buttondiv
android : layout_alignStart = @ + id / button10
android : layout_below = @ + id / button0
android : layout_marginTop = 37dp
android : text = = / >
< / RelativeLayout >
|

Теперь все должно работать нормально, и мы готовы запустить наше приложение-калькулятор для Android. Для запуска нашего приложения я использовал свой мобильный, вы можете использовать эмулятор или ваше устройство.
Запуск нашего калькулятора для Android
- Нажмите на диспетчер устройств Android. После выбора вашего пользовательского устройства в
Android device managerокно, нажмитеSTART, - Нажмите на кнопку «Выполнить».
- Выберите Ваше устройство или эмулятор и нажмите ОК.
- Теперь вы можете увидеть калькулятор для Android, работающий как этот скриншот .
Поздравляю !! Если вы выполнили все шаги и достигли этой точки, значит, вы выполнили все шаги правильно, и ваше приложение калькулятор для Android запущено и работает нормально.
0.00 (0%) 0 votes







