Форум программистов, компьютерный форум, киберфорум
Программирование Android
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
Другие темы раздела
Программирование Android Кнопка "домой", смена ориентации и прочее :) https://www.cyberforum.ru/ android-dev/ thread544429.html
Добрый вечер уважаемые. не могу решить вот такую проблему: Сделал пример отсюда: http://megadarja.blogspot.com/2009/03/android-1-surface.html Там к комментариях правильно сказано, что если нажать домой, то при повторном запуске, приложение валится с ошибкой. Сделал у активи с поверхностью метод: @Override public void onStop(){ super.onStop(); finish();
Программирование Android Большое количество итемов в listView!
При выводе большого количества итемов в listView, используя адаптор, столкнулся с проблемой переполнения памяти. Загуглив, нашел некоторые варианты решений. Как вы фиксите это? Какой на ваш взгляд самый оптимальный способ?
Программирование Android Определение размеров экрана устройства https://www.cyberforum.ru/ android-dev/ thread544249.html
Хочу отцентрировать несколько кнопок на Activity. Кнопки кидаю в контейнер. LinearLayout myContainer = new LinearLayout(this); myContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); myContainer.setOrientation(LinearLayout.VERTICAL); //создание нескльких кнопок setContentView(myContainer); Чтобы кнопки отцентрировать надо получить ширину...
Программирование Android Отловить нажатие кнопки Home Всем привет! Как отловить нажатие кнопки Home. В onKeyDown не получается.... Какие ещё варианты? https://www.cyberforum.ru/ android-dev/ thread544180.html
Доступ к БД из другого Activity. Программирование Android
Очередной нубский вопрос. В главном активити есть dbHelper. Все хорошо. Хочу в одном активити показать результат запроса в виде таблицы, а в другом в виде графика. Такой код, естественно, не компилируется: public void onClick(View v) { Intent intent = new Intent("android.intent.action.WeightAsTable"); intent.putExtra("db", dbHelper); ...
Программирование Android Как загрузить в эмулятор .xml файл https://www.cyberforum.ru/ android-dev/ thread544027.html
ДОбрый день, подскажите пожалуйста, есть основа приложения с кнопкой "каталог" есть хмл файл в котором много всего и он отдельно, надо его в проект как-то вставить запускаю эмулятор, перехожу в режим ддмс, вкладку файл эксплорер, нажимаю на push file onto device ...ничего не меняется может я вообще не так надо делать upload? спасибо
Программирование Android gsm шлюз под андроидом https://www.cyberforum.ru/ android-dev/ thread543623.html
задача такая, я подконекчиваюсь к мобиле од андроидом по wifi и хочу с компа заставить свою мобилу позвонить а главное на мои комп переслать голос, то есть выступить в роли шлюза, вот как реализоать ет функцию ума не приложу, подскажите гуру в какую сторону курить
Программирование Android Подключение к програме сервер на пк
Кто-то может посоветовать, как подключиться к программе сервера на ПК и выполнить какие-то действия. Где хоть искать пример.
Программирование Android Что я делаю не так. Совсем нубский вoпрос. Везде в руководствах говорится, что обработчик нажатия кнопки должен переопределять метод onClick. У меня данный код не компилируется. Если убрать @Override - то все в порядке. Кто прав? public class NewWeightActivity extends Activity{ TextView text; DatePicker date; private int mDay; @Override public void onCreate(Bundle savedInstanceState) { ... https://www.cyberforum.ru/ android-dev/ thread543458.html Программирование Android растровый (2д) редактор https://www.cyberforum.ru/ android-dev/ thread543307.html
Здравствуйте. Задача сделать растровый (2д) редактор. Начать думаю с того, чтобы пользователь мог загружать в него свои изображения, редактировать их а потом использовать в других «частях» программы. Как вы думаете, нужно ли подключать базу SQLite и Dialog класс или тут нужны друкгие элементы интерфейса? Посоветуйте с чего начать. Добавлено через 2 часа 55 минут По идее в других языках...
Добавочный номер при звонке Программирование Android
У меня вопрос как позвонить на номер и, после ответа, набрать добавочный номер, а после этого завершить звонок? Сам звонок просто: Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "12345")); startActivity(dialIntent);А как добавочный номер набрать после ответа?
Программирование Android Управление потоковыми данными (мобильным интернетом) Существует ли какой-нибудь стандартный метод для включения/отключения в классе мобильного интернета по типу такого метода для класса WiFi setWifiEnabled(true/false)? https://www.cyberforum.ru/ android-dev/ thread542194.html
411 / 275 / 22
Регистрация: 18.09.2010
Сообщений: 1,114
11.04.2012, 23:22 0

Калькулятор - Программирование Android - Ответ 2901526

11.04.2012, 23:22. Показов 25832. Ответов 27
Метки (Все метки)

Лучший ответ Сообщение было отмечено как решение

Решение

main.xml
XML
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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
 
    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="number" >
 
        <requestFocus />
    </EditText>
 
 
 
<TableRow
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
 
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:text="   1   " />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   2   " />
 
    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   3   " />
 
    <Button
        android:id="@+id/button4"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   +   " />
 
    <Button
        android:id="@+id/button5"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   -   " />
</TableRow>
 
    <TableRow
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
 
    <Button
        android:id="@+id/button6"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:text="   4   " />
 
    <Button
        android:id="@+id/button7"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   5   " />
 
    <Button
        android:id="@+id/button8"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   6   " />
 
    <Button
        android:id="@+id/button9"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   /   " />
 
    <Button
        android:id="@+id/button10"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   *   " />
</TableRow>
    
   <TableRow
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
 
    <Button
        android:id="@+id/button11"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:text="   7   " />
 
    <Button
        android:id="@+id/button12"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   8   " />
 
    <Button
        android:id="@+id/button13"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="  9   " />
 
    <Button
        android:id="@+id/button20"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   0   " />
    
    <Button
        android:id="@+id/button14"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="   =   " />
 
</TableRow>
 
  <TableRow
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
 
    <Button
        android:id="@+id/button16"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="Decimal" />
 
    <Button
        android:id="@+id/button23"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="Binary" />
    
    <Button
        android:id="@+id/button22"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="Clear" />
</TableRow>
    
</LinearLayout>
Activity.java
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package calc.calc;
 
import java.util.ArrayList;
 
import android.app.Activity;
import android.os.Bundle;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
 
public class CalcActivity extends Activity {
    
    /**Переменная текстбокса*/
    EditText calcDialogDisplay;
    
    /**Переменные кнопок*/
    TextView binary;
    TextView allClear;
    TextView seven;
    TextView eight;
    TextView nine;
    TextView division;
    TextView four;
    TextView five;
    TextView six;
    TextView multiply;
    TextView one;
    TextView two;
    TextView three;
    TextView subtract;
    TextView decimal;
    TextView zero;
    TextView equals;
    TextView addition;
 
    /**Результат который заносится в масив для обработки*/
    ArrayList<Float> result = new ArrayList<Float>();
    
    /**Первое введенное число*/
    float number1;
    
    /**Второе введенное число*/
    float number2;
 
    int currentOperation = 0;
    int nextOperation;
 
    /**Прибавление*/
    final static int ADD = 1;
    
    /**Вычитание*/
    final static int SUBTRACT = 2;
    
    /**Умножение*/
    final static int MULTIPLY = 3;
    
    /**Деление*/
    final static int DIVISION = 4;
    
    /**Равно*/
    final static int EQUALS = 5;
    
    /**Нахождение целого значение из двоичного числа*/
    final static int DECIMAL = 6;
    
    /**Нахождение двоичного числа из целого*/
    final static int BINARY = 7;
 
    final static int CLEAR = 1;
    final static int DONT_CLEAR = 0;
    int clearCalcDisplay = 0;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        calcDialogDisplay = (EditText) findViewById(R.id.editText1);
        binary = (TextView) findViewById(R.id.button23);
        allClear = (TextView) findViewById(R.id.button22);
        seven = (TextView) findViewById(R.id.button11);
        eight = (TextView) findViewById(R.id.button12);
        nine = (TextView) findViewById(R.id.button13);
        division =(TextView) findViewById(R.id.button9);
        four = (TextView) findViewById(R.id.button6);
        five = (TextView) findViewById(R.id.button7);
        six =(TextView) findViewById(R.id.button8);
        multiply = (TextView) findViewById(R.id.button10);
        one = (TextView) findViewById(R.id.button1);
        two = (TextView) findViewById(R.id.button2);
        three = (TextView) findViewById(R.id.button3);
        subtract = (TextView) findViewById(R.id.button5);
        decimal = (TextView) findViewById(R.id.button16);
        zero = (TextView) findViewById(R.id.button20);
        equals = (TextView) findViewById(R.id.button14);
        //addition = (TextView) findViewById(R.id.addition);
        calcDialogDisplay.setKeyListener(DigitsKeyListener.getInstance(true,true));
 
        registerListeners();
    }
 
    /*Обработка нажатия на экран*/
    public void registerListeners () {
 
        seven.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                if (clearCalcDisplay == CLEAR) {
                    calcDialogDisplay.setText("");
                }
                clearCalcDisplay = DONT_CLEAR;
                calcDialogDisplay.append("7");
            }
        });
 
        eight.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                if (clearCalcDisplay == CLEAR) {
                    calcDialogDisplay.setText("");
                }
                clearCalcDisplay = DONT_CLEAR;
                calcDialogDisplay.append("8");
 
            }
        });
 
        nine.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                if (clearCalcDisplay == CLEAR) {
                    calcDialogDisplay.setText("");
                }
                clearCalcDisplay = DONT_CLEAR;
                calcDialogDisplay.append("9");
 
            }
        });
 
        division.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                calcLogic(DIVISION);                    
            }
        });
    
        allClear.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                calcDialogDisplay.setText("");
                number1 = 0;
                number2 = 0;
                result.removeAll(result);
                currentOperation = 0;
                nextOperation = 0;                  
            }
        });
        
    four.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            if (clearCalcDisplay == CLEAR) {
                calcDialogDisplay.setText("");
            }
            clearCalcDisplay = DONT_CLEAR;
            calcDialogDisplay.append("4");
 
        }
    });
 
    five.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            if (clearCalcDisplay == CLEAR) {
                calcDialogDisplay.setText("");
            }
            clearCalcDisplay = DONT_CLEAR;
            calcDialogDisplay.append("5");
 
        }
    });
 
    six.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            if (clearCalcDisplay == CLEAR) {
                calcDialogDisplay.setText("");
            }
            clearCalcDisplay = DONT_CLEAR;
            calcDialogDisplay.append("6");
        }
    });
    
    zero.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            if (clearCalcDisplay == CLEAR) {
                calcDialogDisplay.setText("");
            }
            clearCalcDisplay = DONT_CLEAR;
            calcDialogDisplay.append("0");
        }
    });
    
    decimal.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            calcLogic(DECIMAL);
        }
    });
    
    multiply.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            calcLogic(MULTIPLY);
        }
    });
 
    one.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            if (clearCalcDisplay == CLEAR) {
                calcDialogDisplay.setText("");
            }
            clearCalcDisplay = DONT_CLEAR;
            calcDialogDisplay.append("1");
 
        }
    });
 
    two.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            if (clearCalcDisplay == CLEAR) {
                calcDialogDisplay.setText("");
            }
            clearCalcDisplay = DONT_CLEAR;
            calcDialogDisplay.append("2");
 
        }
    });
 
    three.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            if (clearCalcDisplay == CLEAR) {
                calcDialogDisplay.setText("");
            }
            clearCalcDisplay = DONT_CLEAR;
            calcDialogDisplay.append("3");
 
        }
    });
 
    subtract.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            calcLogic(SUBTRACT);
        }               
    });
    
    equals.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            calcLogic(EQUALS);
 
        }
    });
    
    binary.setOnClickListener(new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            calcLogic(BINARY);
 
        }
    });
}
    
    /*Функция перевода из десятичного в двоичное значение*/
    private float decToBin(float bin) {  
        int i, b;  
        long result = 0;  
        
         for(i=0; bin > 0; i++)  {
            b = (int) (bin % 2);  
            bin = (bin-b)/2;
            result += b * Math.pow(10,i);
        }
         return result;
    }
    
    /*Функция перевода из двличного в десятичное значение*/
    private float binToDec(float dec) {
        int result = 0;
        int mult = 1;
        
        while(dec > 0) {
            result += mult * ((int)dec % 10);
            dec /= 10;
            mult *= 2;
        }
        return result;
    }
 
    /*Функция расчета введенных значений*/
    private void calcLogic(int operator) {
 
    result.add(Float.parseFloat(calcDialogDisplay.getText().toString()));
 
    if (operator != EQUALS) {
        nextOperation = operator;
    }else if (operator == EQUALS){
        nextOperation = 0;
    }
 
    switch (currentOperation) {
    
    /*Прибавление*/
        case ADD:               
            number1 = result.get(0);
            number2 = result.get(1);
    
            result.removeAll(result);
    
            result.add(number1 + number2);
    
            calcDialogDisplay.setText(String.format("%.0f", result.get(0)));
            break;
            
      /*Вычитание*/      
        case SUBTRACT:
            number1 = result.get(0);
            number2 = result.get(1);
    
            result.removeAll(result);
    
            result.add(number1 - number2);
    
            calcDialogDisplay.setText(String.format("%.0f", result.get(0)));
            break;
            
      /*Умножение*/
        case MULTIPLY:
            number1 = result.get(0);
            number2 = result.get(1);
    
            result.removeAll(result);
    
            result.add(number1 * number2);
    
            calcDialogDisplay.setText(String.format("%.0f", result.get(0)));
            break;
       /*Деление*/     
        case DIVISION:
            number1 = result.get(0);
            number2 = result.get(1);
    
            result.removeAll(result);
    
            result.add(number1 / number2);
    
            calcDialogDisplay.setText(String.format("%.0f", result.get(0)));
            break;
            
        /*Получание двоичного числа*/    
        case DECIMAL:
             number2 = result.get(1);
             
             result.removeAll(result);
             
             result.add(decToBin(number2));
             
             calcDialogDisplay.setText(String.format("%.0f", result.get(0)));
            break;
        
       /*Получение десятичного числа*/
        case BINARY:
             number2 = result.get(1);
             
             result.removeAll(result);
             
             result.add(binToDec(number2));
             
             calcDialogDisplay.setText(String.format("%.0f", result.get(0)));
            break;
    }
 
    clearCalcDisplay = CLEAR;
    currentOperation = nextOperation;
    if (operator == EQUALS) {
        number1 = 0;
        number2 = 0;
        result.removeAll(result);
    }
}
    
}


Вернуться к обсуждению:
Калькулятор Программирование Android
3
Заказать работу у эксперта
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
11.04.2012, 23:22
Готовые ответы и решения:

Калькулятор
делаю калькулятор на основе чужого, появились такие проблемы: 1. не работает с отрицательными...

Калькулятор на андроиде
Пытался программно накидать кнопок чтобы калькулятор получился,но в итоге ничего не работает,в логе...

Калькулятор по формуле
При вводе простых чисел, все прекрасно считает, но при вводе десятичных пишет всегда 0.0. Что...

Калькулятор на Android
Дело вот в чем, создается калькулятор, все прекрасно, но не получается сделать так что бы он считал...

27
11.04.2012, 23:22
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
11.04.2012, 23:22
Помогаю со студенческими работами здесь

Калькулятор на Android
Здравствуйте. Есть edit text, в котором все вычисления, затем Textview в котором ответ выводится,...

Подскажите. Калькулятор Android
Ребята, помогите блдондинке, пожалуйста! В изучении java android я еще новичок. Выполняю...

Android, простенький калькулятор
Добрый день! Пишу на андроиде только 2 часа, по-этому ещё многое не понятно. В общем задача...

Калькулятор и деление на ноль
Нужно чтобы при делении на ноль выскакивала ошибка.Помогитееее

0
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru