Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 49

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 49 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 492018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

If traverse() is not overridden then it is notpossible to handle the directional keys: they will be used to change theform’s current focus item.The selector item uses traverse() to handle the left and rightkeys so that the currently selected month can be changed. The list itemoverrides both keyPressed() and traverse(). keyPressed() isused to view an expense claim in the details form. traverse() is usedto change the current row selection and ensure that the current row isalways visible on the screen.The following code shows the implementation of keyPressed()for the list item. Only the joystick press is trapped; any registered statelisteners (in this case, the parent form) are notified that a row has beenselected and the expense detail form should be shown.// Series 60 List Custom Item keyPressed() methodprotected void keyPressed(int key) {// trap the joystick press for the item selectionif (key == JOYSTICK_PRESS) {notifyStateChanged();}}The implementation of the traverse() method in the list item iscertainly a great deal longer.

The method returns a boolean that signifieswhether the item is currently performing internal traversal. While internaltraversal is occurring, the item will retain the focus.The traverse() method takes four parameters:• direction is the key code of the button that was pressed; only theleft, right, up and down buttons are sent to the traverse() method260MIDP 2.0 CASE STUDIES(Item orientation 0,0)RowRowRow(Visible in [0], [1])RowRow(Visible out [0], [1])RowCurrent RowRow(Visible out [2], [3])View HeightRowRowRowRowRow(Visible in [2], [3])RowRow(Item width, height)View WidthFigure 5.7List item visible rectangles.• viewHeight and viewWidth specify the size of the region thatthe item is currently painting into and is constrained by the size ofthe screen• visRect_inout is the array that defines the currently visibleregion of the item (see Figure 5.7): visRect_inout[0] and visRect_inout[1] are the x and y coordinates of the top right cornerand visRect_inout[2] and visRect_inout[3] are the widthand height of the region.visRect_inout must be updated to reflect the currently visible regionof the item.

It comes into play when the item size is larger than thescreen. In the case of the list item, visRect_inout is set to thebounding rectangle of the currently selected row in the list. The selectoritem, which will always be visible on the screen, leaves the contents ofvisRect_inout unchanged.Below is the traverse() method of the list item. The first sectionof code checks if the item is currently being traversed internally, if notthen the current selection is set based on the direction from which theitem was traversed into. If the item is currently traversing internally then aswitch statement is used to update the current row selection based on thedirection.

If the current selection is no longer within the list, for exampleless than 0 or greater than the row count, then the user is traversing outTHE EXPENSE APPLICATION261of the list item; false is returned and the neighboring form item gets thefocus. Finally, if the item is still traversing internally, the currently visibleregion is calculated and a repaint() call is made to ensure that thehighlighted row has a chance to be painted; true is returned to ensurethat the item retains focus.// Series 60 List Custom Item traverse() methodprotected boolean traverse(int direction, int viewWidth, int viewHeight,int[] visRect_inout) {// is this the current item, i.e. we are traversing inside currently??if (!isCurrentItem) {isCurrentItem = true;// set the current selected rowif (direction == Canvas.DOWN)currentSelection = 0;else if (direction == Canvas.UP)currentSelection = model.getRowCount() - 1;} else {// we are currently traversing so handle the keypressswitch (direction) {case Canvas.UP :currentSelection--;if (currentSelection < 0) {currentSelection = 0;return false; // traverse out}break;case Canvas.DOWN :currentSelection++;if (currentSelection >= model.getRowCount()) {return false; // traverse out}break;}}// set the visible rectangle, i.e.

just the current item, allow the// implementation to do the screen managementint currentItemTopY = headerHeight + (rowHeight * currentSelection);visRect_inout[1] = currentItemTopY;visRect_inout[3] = rowHeight;repaint();return true;}There are three methods that can be overridden to handle pointerevents: pointerPressed(), pointerReleased() and pointerDragged(). Each method is passed an x and y parameter that representsthe position of the pointer event relative to the top right corner of the itemthat received the event.When the pointer taps on a specific area of a custom item it is generallybetter to handle it with the pointerReleased() method rather thanpointerPressed(), as it gives a more natural feel to the interaction.If the user decides not to perform the action, dragging the pointer away262MIDP 2.0 CASE STUDIESfrom the hotspot will avoid it triggering; and if the screen is redrawn aspart of the pointer event, the pointer is not touching a new hotspot.When a pointer event occurs it is necessary to determine what itactually means to the application, for example the list item must determineif a tap is to signal a change in sorting or to select a row.

As the complexityof the custom item grows, so does the complexity of the logic to determinewhat the pointer event means.The following code shows an example from the UIQ version of the listitem. The code initially determines if the hit was in the list header; if so,the columns in the list are enumerated and each is checked to determinewhich was hit and the sort order updated. If the hit is not in the listheader then the row hit is calculated using the y hit position divided bythe row height.// UIQ List Custom Item pointerReleased() methodprotected void pointerReleased(int x, int y) {// is the hit within the header??if (y <= headerHeight) {// within header, enum and work out which one...Enumeration enum = columnList.elements();int colNum = 0;while (enum.hasMoreElements()) {ListColumn col = (ListColumn)enum.nextElement();if (col.isHit(x, y)) {// found our hit, update sort order...break;}colNum++;}} else {// within the body of the list, work out which entry was selectedcurrentSelection = 1 + ((y - headerHeight) / rowHeight);notifyStateChanged();}}5.2.4.4 Designing Custom Items for Series 60 and UIQAs the user interface evolved during the development of the expenseapplication it became apparent from an early stage that the UIQ andSeries 60 user interfaces have sufficient differences that each MIDlet mustbe tailored specifically to the device.

The differences are only skin-deep;all other application code remains identical.This section aims to highlight the differences between the user interfacemetaphors and suggest a few considerations that can help simplify theimplementation of device-specific versions of a MIDlet.Device Look and FeelThe most notable difference between UIQ and Series 60 is that UIQ usesa pen and a jog dial as the primary input methods and Series 60 has aTHE EXPENSE APPLICATION263keypad and a joystick.

Each interface has its own unique look and feel;users interact differently and expect different responses from them.When creating a user interface the strengths of each interface metaphorshould be used to provide an interface that is consistent, or at least fitsbroadly, with the expected characteristics of the device. For UIQ, thismeans regions to tap with the pen; for Series 60, longer menus and simplescreen layouts.A good example of how the user interface must be adapted for adevice is the implementation of the list item on Series 60. The itemis navigable using only the joystick. The column sort order cannot bemodified as it is not easy to fit this into the user interface – it wouldrequire lengthy menu options that would only be available when the listitem has the focus. While context-sensitive commands are available inMIDP, they may confuse the user. Menu options should generally remainas consistent as possible, no matter what the currently selected item, toaid application usability.Conversely, the UIQ version of the list item allows rows to be selectedusing the pen or jog wheel.

Changing the sort order on the columns can beachieved by tapping a column header. This is intuitive and consistent withhow a user might expect a UIQ application to work. Similar differencesexist between the different versions of the selector custom item.Separation of Business Logic and Presentation CodeIf the business logic and the presentation layer code are intertwined thenupdating the user interface inevitably has effects on the business logicand errors could be introduced. Of more concern is that you would haveto maintain a different version of the business logic for each device.It also makes the both the business logic and UI code more difficultto understand.To avoid this, there should be a clear separation of the user interfaceand the business logic.

Most developers understand this need for separation; the model–view–controller (MVC) pattern is a good example ofhow this separation can be achieved when creating a user interface.In the expense application, we have already seen separation in actionwith the definition of the MIDlet object itself. For different versions of theapplication there are different versions of the main form. Keeping thesetwo objects separate allows the MIDlet code to remain the same whilethe code that produces the form changes independently.Code ManagementSeparating the code into layers does not prevent us from having to keepmultiple branches of the application source code, one for each deviceplatform.

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

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

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

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