Главная » Просмотр файлов » John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG

John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (779881), страница 13

Файл №779881 John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (Symbian Books) 13 страницаJohn.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG2018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 13)

You’ve been taken througha huge number of OPL commands, what they do, and how they relate toeach other.If you’ve got this far and have followed everything, then congratulations. If you’re still unsure, re-read this chapter and experiment. Onceyou understand the principles in this chapter, the rest of the book willmake a lot more sense.We finally looked at reading input through pen taps on the screen,and direct presses of the keys.

Chapter 4 will introduce you to the mainuser elements of your operating system, the Menu bar and Dialog boxes.This will allow you to quickly and efficiently get information and contentfrom the user, as well as present options and information to them.4A Conversion Program: Event Corein PracticeIn this chapter you will learn:• how to turn Event Core into a practical program• creating and using a Menu system• creating and using Dialog boxes• working with variables, doing calculations, and displaying the results.4.1 First Steps with Event CoreNow that we have the Event Core framework, we can use this to createour first real program – one that does more than doing nothing (althoughEvent Core does this so well)!4.1.1The Conversion ProgramOur first program will be a conversion tool.

It will take in measurementsof one type, and convert them into another type. We will use thefour conversions listed below, and show you how to add in your ownconversions to replace or augment these:• temperature: between degrees Celsius and degrees Fahrenheit• long distance: between miles and kilometers• short distance: between centimeters and inches• weight: between pounds and kilograms.4.1.2 Starting the New ProjectTake the Event Core source code and copy it into a new folder for yourproject.

If you’re using the conventions of the book, then create a folder62A CONVERSION PROGRAM: EVENT CORE IN PRACTICEcalled Convert, and in that folder create a folder called Source (foryour source code). Rename the Core.tpl to Convert.tpl (or Core.opl toConvert.tpl if you are working directly on the Symbian OS phone).Opening Convert.tpl you’ll want to change the first few constants toreflect the new program:CONSTCONSTCONSTCONSTKAuthorEmail$="ewan@izzyhack.org"KAuthorName$="Ewan Spence"KAppName$="Convert"KAppVer$="1.00"I always like to translate the code now and see the new empty programdisplay its own name – it’s a bit like conception. Now we have to helpthis program grow and reach its potential. And to do that, we need a plan.4.1.3 Planning ConvertWe’ve already defined in bullet points what we want the program to do(the four conversion criteria listed above). We need to think what inputswe’re going to need, and what outputs we’ll use.

What I do here is forgetabout any limitations of OPL and sketch out on paper what the programwould be expected to do, no matter which language it was written in.We would need a menu system that would let us choose the conversionwe want to perform. It would then display a box asking for the initialinformation (how many miles, in this case let’s say 500). The userwould then see the result in a second dialog box (which would be804.67 kilometers).Now let’s think how that could relate to Event Core.

As you remember,Event Core loops around waiting for something to happen. In Convert,we’re going to wait until the menu is called. When this happens, we’lldisplay all the available conversions, and if one is selected we’ll moveonto the dialog box to get the relevant figures.Once this dialog box is completed, we’ll show the results in a seconddialog box, and then close the dialog box and the menu, returning to thestate where we wait for something to happen.4.1.4 Recognizing and Acting on Menus in OPL CodeThe commands to define a menu are as follows:mINITmCARD "Convert","Option 1",%a,"Option 2",%bMenuResult%=MENU(LastMenu%)FIRST STEPS WITH EVENT CORE63Starting the MenumINIT is an initialization command, and lets the runtime know thata menu is about to be created and called. It must always be the firstcommand when you call a menu.A Single Pane MenuThe mCARD command defines a single menu card.

Second and subsequentmenu cards can be defined by having additional mCARD commands.The first part of the mCARD command is the name of the menu card.This is the name that appears in the top menu bar of your program.This name does not appear in a menu on Series 60. You then have asmany paired commands as you need to define your menu. The first textstring will be the text shown on the menu, and the second value is theinteger that will be returned by the MENU command. For obvious reasons,this number must not be repeated in any of the mCARDs defined for thisinstance of the menu system.You could have any number here, but we’re using a value of %a for'Option 1'.

This represents the value of the letter 'a' if pressed. If we wereto use %b, it would be 'b' and %B would be 'B' (so %b is not the sameas %B). %a actually means ‘‘the character code for the letter ‘a’ which inthis case is 97’’. These values mean that the relevant menu option will belabeled with the relevant hot key on compatible devices (e.g. Series 80).So %a would be shown with 'Ctrl+A' as the hot key, and %B would beshown with 'Shift+Ctrl+B'.These returned values will be used to jump to the correct procedurewhen we act on the command received by the menu. More on this ina minute.Two or More Menu PanesLet’s say we want a second menu card, so our top menu bar reads''Convert'' and ''Edit''.

To add in a second card, we simply list it after thefirst card, ensuring the name of the card is unique, and that we do notrepeat any of the hot key numbers:mINITmCARD "Convert","Option 1",%a,"Option 2",%bmCARD "Edit","Option 3",%c,"Option 4",%dMenuResult%=MENU(LastMenu%)You can add in as many menu cards as you feel the need, but there willcome a point where your menu bar is too crowded to make any sense.In all cases, LastMenu% should be a GLOBAL variable into which thelast selected menu item will be stored. This ensures that (on compatibledevices) the menu can be brought up offering the last-selected item asthe initial choice for the user if required.64A CONVERSION PROGRAM: EVENT CORE IN PRACTICEReading the ResultNow we have defined all the elements of a menu, we will want to displayit on the screen and read the result. We do this with the MENU commandMenuResult%=MENU(LastMenu%)This displays the menu system, and once we choose a menu option, itwill return the value that is listed after that menu option (the hot keyvalue).Calling the Menu with a Key PressBoth Series 60 and Series 80 call up menus with a key press.

Series 80has a dedicated key (KKeyMenu32&), while Series 60 will generally usethe CBA1 button (the left soft key). When the Event Core picks up thisvalue, it will call the menu procedure.Calling the Menu with the TouchscreenIn a similar way to the Series 60 and Series 80 devices, the UIQ menucall is represented by a constant (in this case KMenuSilkScreen&).When the menu area is tapped, it acts as if it was a keypress sendingthe KMenuSilkScreen& value to the Event Core, which is handledin exactly the same way as any other keypress calling for the menu tobe displayed.Hot KeysWe’ve stressed that we use hot key values in the menu system.

We alsohave a separate routine in Event Core that reads in hot keys from thekeyboard (if present).As you know, Symbian OS applications can often achieve the sameresult in many different ways. One example of this is choosing a menuoption. For example, the option to show an About box can be called bya hot key combination on the keyboard or by selecting the menu itemitself. This is how we implement menu functions – by ensuring that thehot keys in our menu system (even if the key combination is not shownon our target device) can re-use the PROC ActionKey: procedure toprocess the menu input.Rather than read the value returned by MENU into an arbitrary variable,we can re-use the Key& variable:Key&=MENUFIRST STEPS WITH EVENT CORE65and modify PROC KeyboardDriver: by adding the following fourlines:rem Call MenuIF Key&=KKeyMenu32& OR Key&=KMenuSilkScreen&DisplayMenu:ENDIFrem Check for Hot Keys hereIF Key&<=300ActionKey:ENDIFSo when we choose a menu option, through a pen interface, or usingthe cursor keys and a select button, the value is passed back to PROCActionHotKey: as if a hot key was pressed (even if the device does nothave a keyboard).

PROC ActionHotKey: can now jump to the correctprocedure, carry out the operation, and then return to the main loop ofthe program.4.1.5 Building a Menu System in OPL CodeCascading MenusAs well as separate menu cards, there is another way to present information in a menu. This is through the use of cascading menus. A cascade inthis respect is a menu option that, when selected, will pop up a secondlist of menu options the user can choose from.To use this feature, you firstly define the cascading menu by usingthe mCASC command, in the same way as you would use the mCARDsystem.

The title (first string) in mCASC must be the same text as the menuoption that will call up the cascade. Now, as long as the cascade isdefined before the menu card it will appear in, you can place it in themenu card by using the title of the cascade (as defined at the start of themCASC command) and appending a ">" symbol.

Характеристики

Тип файла
PDF-файл
Размер
3,18 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6549
Авторов
на СтудИзбе
300
Средний доход
с одного платного файла
Обучение Подробнее