Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 76

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 76 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 762018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

In the History view, the new DynInitMenuPaneL() isas follows:void COandXHistoryView::DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane){if (aResourceId == R_OANDX_HISTORY_MENU){if (IsDisplayingHistory()){aMenuPane->DeleteMenuItem(EOandXDisplayHistory);}else{aMenuPane->DeleteMenuItem(EOandXDisplayStats);}}}The most significant change in the handling of commands is the needto implement HandleCommandL() in each view. In the Game view theimplementation is as follows:void COandXGameView::HandleCommandL(TInt aCommand){COMMAND MENUS419switch (aCommand){case EAknSoftkeyBack:{AppUi()->HandleCommandL(EEikCmdExit);break;}default:{AppUi()->HandleCommandL(aCommand);break;}}}The implementation in the History view follows the same pattern.Although it would be possible to handle the bulk of the commandsin the views, as in UIQ, we’ve taken the decision in this case todelegate all responsibility for processing the commands to the applicationUI’s HandleCommandL() function.

Doing so reduces the differencesbetween the old and new S60 examples, but at the cost of having moredifferences between the S60 and UIQ view-based examples than strictlynecessary.The application UI’s implementation of HandleCommandL() becomes:void COandXAppUi::HandleCommandL(TInt aCommand){_LIT8(KDummy, "");switch(aCommand){case EEikCmdExit:case EAknSoftkeyExit:{SaveL();Exit();}break;case EOandXNewGame:{iController->Reset();iAppView->Container()->ResetView();}break;case EOandXFirstPlayer:{iController->SwitchTurn();}break;case EOandXDisplayStats:{if (iHistView->IsActivated()){iHistView->ChangeDisplayL(EOandXSetStats);}420VIEWS AND THE VIEW ARCHITECTUREelse{ActivateViewL(TVwsViewId(KUidOandXApp, KUidOandXHistoryView),TUid::Uid(EHistoryViewDisplayStats), KDummy);}break;}case EOandXDisplayHistory:{if (iHistView->IsActivated()){iHistView->ChangeDisplayL(EOandXSetHistory);}else{ActivateViewL(TVwsViewId(KUidOandXApp, KUidOandXHistoryView),TUid::Uid(EHistoryViewDisplayHistory), KDummy);}break;}case EOandXDisplayGame:{ActivateViewL(TVwsViewId(KUidOandXApp, KUidOandXView));break;}case EOandXResetHistory:{Controller().ResetStats();iHistView->ChangeDisplayL(iHistView->IsDisplayingHistory());break;}default:break;}}The decision to handle all commands in the application UI has madethe processing of some of the commands a little more complicated.

Forexample, the EOandXDisplayHistory command might have comefrom either the History view (when it is currently displaying statisticaldata) or from the Game view. In the first case, all that is needed isto call the view’s ChangeDisplayL() function, while the secondis asking for a true switch to the History view and needs a call toActivateViewL().The processing would be simpler if it were clear from where thecommands originated. One solution would be to transfer the handlingof such commands into the originating view’s HandleCommandL()function, as in the UIQ version. A less elegant solution would be to assigndifferent command IDs to the two versions of each such command,depending on the view to which it belongs.SUMMARY421SummaryThe Symbian OS view architecture supports the notion of task-basedusage across multiple applications.Though the concepts are similar, the implementations of the viewarchitecture on different platforms are significantly different.Your applications are not obliged to participate in the view architectureor to register any views.

The view architecture will treat such applicationsas having a single, default view.15ControlsControls are the principal means of interaction between an applicationand the user. This chapter covers the basic principles of writing and usingcontrols, explaining what a control is and its place in UI development.The examples provided in this chapter have deliberately been keptgeneral but, where applicable, the differences between the S60 UI andthe UIQ UI are explained.

You still need to consult the Style Guideand other documentation in the appropriate SDK for information ontopics specific to a particular phone, such as preferred layout and colorschemes.15.1 What Is a Control?In Symbian OS, controls provide the principal means of interactionbetween an application and the user. Applications make extensive use ofcontrols: each application view is a control, and controls form the basisof all dialogs and menu panes.Every control is derived from the abstract class CCoeControl (definedin coecntrl.h), which gives fundamental features and capabilities toa control.

A control occupies a rectangular area on the screen and,in addition to responding to user-, application- and system-generatedevents, may display any combination of text and image.Depending upon the particular user interface, the user-generatedevents may include:• key presses, either alphanumeric or from device-specific buttons• pointer events, generated by the user touching the screen with a pen.424CONTROLSDrawing a control’s content can be initiated in two ways.

The application itself can initiate the drawing, for example when the control’sdisplayable data changes. Alternatively, the system may initiate drawing,for example when all or part of the control is exposed by the disappearance of an overlying control belonging to the same or another application.Symbian OS is a full multitasking system, in which multiple applications may run concurrently, and the screen is a single resource thatmust be shared among all these applications. Symbian OS implementsthis sharing by associating one or more windows with each application,to handle the interaction between the controls and the screen.

The windows are managed by the window server, which ensures that the correctwindow(s) are displayed, managing overlaps and exposing and hidingwindows as necessary.In order to gain access to the screen, each control must be associatedwith a window. However, there is not necessarily a separate window foreach control. Some controls, known as window-owning controls, use anentire window, but many others, known as non-window-owning controlsor lodger controls, share a window owned by another control.You can test whether a control owns a window by checking whetherOwnsWindow() returns ETrue or EFalse, although its main use iswithin CCoeControl’s framework code.For a system such as Symbian OS, which runs on devices withlimited power and resources, windows are expensive.

Each window usesresources in its associated application, and also needs correspondingresources in the window server. Furthermore, each window results inadditional client–server communication between the application and thewindow server. It therefore makes sense to use lodger controls as much aspossible. Fortunately, there isn’t a great deal of difference in programmingterms between the two types.Any application with a graphical user interface requires access to thescreen, and so must contain at least one window-owning control.

Othercontrols might need to own a window if they require the properties of awindow, such as the ability to overlap another window.15.2Control TypesControls may be either simple or compound. A compound controlcontains one or more component controls; a simple control does not.Simple ControlsPerhaps the simplest of simple controls is one that draws a blank rectangleand does not respond to any user- or system-generated events.

As anexample, we’ll look at the application view used in HelloBlank, a‘Hello World’ application that uses such a blank control for its view. Theclass definition for the application view is as follows:CONTROL TYPES425class CBlankAppView : public CCoeControl{public:void ConstructL(const TRect& aRect);};We don’t need the class constructor or destructor to do anythingspecial, so we’ll simply rely on the default implementations.

For thiscontrol, the only member function we need to write is ConstructL(),the second-stage constructor.void CBlankAppView::ConstructL(const TRect& aRect){CreateWindowL(); // Create a window for this controlSetRect(aRect);// Set the control’s sizeSetBlank();// Make it a Blank controlActivateL();// Activate control, making it ready to be drawn}The four functions that ConstructL() calls are all, in one way oranother, associated with enabling the control to display itself.Since all controls must be associated with a window, and this is the onlycontrol in the application, it follows that it has to be a window-owningcontrol. The CreateWindowL() function both creates the window andsets the control as its owner.SetRect() sets the size and position, in pixel units, of the control’srectangle on the screen, relative to its associated window. Since thiscontrol owns a window, the window’s size is also adjusted to that of thecontrol.

A control is responsible for ensuring that it is capable of drawingevery pixel within the specified area and that its content is correctlypositioned within this rectangle.The call to SetBlank() is what makes this a blank control. All itdoes is enable the control subsequently to fill its rectangle with a plainbackground color. How it does this is explained in Section 15.7.Before the final call to ActivateL(), drawing of the control remainsdisabled. For drawing to be enabled, the control must be both visibleand activated. Controls are visible by default but need explicit activation by means of a call to ActivateL(), because controls are notalways in a fit state to draw their content immediately after construction. For example, the data that a control is to display may not beavailable at the time of its construction, and this may also affect thecontrol’s required size and position.

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

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

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

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