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

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

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

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

The remaining codeobtains (non-owning) copies of the pointers to the component labelcontrols and then reads in, from the resource file, copies of the textitems that are used to generate the view’s content. These take the form offormattable text, such as:RESOURCE TBUF r_history_view_games_text{buf = "%d games played";}S60 views do not normally use ViewConstructL(). Constructionof an S60 view follows a slightly different course, since it owns a controlrather than being one. The History view’s ConstructL() has to createthe control.void COandXHistoryView::ConstructL(){BaseConstructL(R_OANDX_HISTORY_VIEW);iContainer = COandXHistViewContainer::NewL(ClientRect());}The data used to generate the view’s content is owned by the control,rather than by the view, and is initialized in the control’s ConstructL().void COandXHistViewContainer::ConstructL(const TRect& aRect){IMPLEMENTING THE MCOEVIEW INTERFACE413...iEikonEnv->ReadResourceL(iNumGamesText, R_HISTORY_VIEW_GAMES_TEXT);iEikonEnv->ReadResourceL(iNumOWinsText, R_HISTORY_VIEW_OWINS_TEXT);iEikonEnv->ReadResourceL(iNumXWinsText, R_HISTORY_VIEW_XWINS_TEXT);iEikonEnv->ReadResourceL(iNumDrawsText, R_HISTORY_VIEW_DRAWN_TEXT);iEikonEnv->ReadResourceL(iStatOWonText, R_HISTORY_VIEW_O_WINNER_TEXT);iEikonEnv->ReadResourceL(iStatXWonText, R_HISTORY_VIEW_X_WINNER_TEXT);iEikonEnv->ReadResourceL(iStatDrawText, R_HISTORY_VIEW_NO_WINNER_TEXT);iEikonEnv->ReadResourceL(iHistoryTitle, R_HISTORY_VIEW_HISTORY_TITLE);iEikonEnv->ReadResourceL(iStatsTitle, R_HISTORY_VIEW_STATS_TITLE);...}The remainder of the container’s ConstructL() code was describedin Section 14.3.History View ContentAlthough the topic is not directly related to the MCoeView interfacefunctions, this is a convenient place to discuss the generation of thecontent for the Noughts and Crosses application’s History view.

Thekey function is CreateNewItemsL(), whose UIQ implementation is asfollows:void COandXHistoryView::CreateNewItemsL(){// Clear all existing dataTBuf<KFormatBufSize> itemName;iEikonEnv->ReadResourceL(itemName, R_HISTORY_VIEW_NO_DATA_TEXT);for (TInt i=0; i<KNumDataLines; i++){iDataLines[i]->SetTextL(itemName);}// Insert the data to be displayedTUint played = Controller().GamesPlayed();if (iDisplayingHistory){// Set the title in the labeliTitle->SetTextL(iHistoryTitle);// Add all available hstory data to the listboxfor (TInt i=0; i<KNumHistoryRecords; i++){switch (Controller().GameRecord(i)){case ETileNought:itemName.Format(iStatOWonText, played - i);break;case ETileCross:itemName.Format(iStatXWonText, played - i);break;case ETileDraw:itemName.Format(iStatDrawText, played - i);break;414VIEWS AND THE VIEW ARCHITECTUREdefault:iEikonEnv->ReadResourceL(itemName, R_HISTORY_VIEW_NO_DATA_TEXT);break;}iDataLines[i]->SetTextL(itemName);}}else // Displaying statistics{// Set the title in the labeliTitle->SetTextL(iStatsTitle);// Total games playeditemName.Format(iNumGamesText, played);iDataLines[0]->SetTextL(itemName);// Wins by NoughtsTUint oWins = Controller().WonByO();itemName.Format(iNumOWinsText, oWins);iDataLines[1]->SetTextL(itemName);// Wins by CrossesTUint xWins = Controller().WonByX();itemName.Format(iNumXWinsText, xWins);iDataLines[2]->SetTextL(itemName);// Drawn (or abandoned) gamesitemName.Format(iNumDrawsText, played - oWins - xWins);iDataLines[3]->SetTextL(itemName);}}The function’s purpose is to set the text in each of the label controlsused to display the History view’s content.

For efficiency, the labelsare accessed by the pointers that were copied into member data byConstructL(), rather than having to look them up each time they areneeded.Since the history data and statistical data will, in general, occupydifferent numbers of the labels, the first action is to clear them of allcontent.If the view is displaying historical data, each available past result isread from the Controller and used to determine which text item to display.The text is formatted to contain the corresponding game number and thenset into the appropriate label.

A similar process is used to construct thetext to be displayed if the view is to display statistical data.The various text items are supplied from member data, rather thanhaving to be repeatedly read from the resource file.14.6Command MenusWe’ve already seen, in Chapter 12, the basics of how command menusbehave in both S60 and UIQ. From the point of view of implementation,COMMAND MENUS415the main differences between the two approaches for an application witha single view are that:• in S60, menu content is updated when the framework calls the application UI’s DynInitMenuPaneL() function, immediately before amenu is made visible, whereas UIQ requires the application to updatethe menu content itself at the time that the application’s state changes• UIQ provides a HandleCommandL() function in the view, whereasS60 implements it in the application UI.The second of these differences largely disappears in applications thatmake use of the view architecture, since the S60 CAknView class provides a HandleCommandL() function.

The default implementation doesnothing and should be overridden in each of your application’s views.Changes for UIQIn the example application, the only difference in the UIQ version of theGame view is that we have added two more commands, as shown belowin the command resource, to select the additional displays.RESOURCE QIK_COMMAND_LIST r_oandx_portrait_commands{items ={// The first command is only visible in debug mode.QIK_COMMAND{id = EEikCmdExit;type = EQikCommandTypeScreen;// Indicate that this command will only be visible in debugstateFlags = EQikCmdFlagDebugOnly;text = STRING_r_oandx_close_debug_cmd;},QIK_COMMAND{id = EOandXNewGame;type = EQikCommandTypeScreen;text = "New game";},QIK_COMMAND{id = EOandXFirstPlayer;type = EQikCommandTypeScreen;text = "Noughts move first";},QIK_COMMAND{id = EOandXDisplayStats;type = EQikCommandTypeScreen;text = "Game statistics";},416VIEWS AND THE VIEW ARCHITECTUREQIK_COMMAND{id = EOandXDisplayHistory;type = EQikCommandTypeScreen;text = "Game history";}};}The History view also has its own set of commands.RESOURCE QIK_COMMAND_LIST r_history_view_commands{items={// The first command is only visible in debug mode.QIK_COMMAND{id = EEikCmdExit;type = EQikCommandTypeScreen;// Indicate that this command will only be visible in debugstateFlags = EQikCmdFlagDebugOnly;text = STRING_r_oandx_close_debug_cmd;},QIK_COMMAND{id = EOandXDisplayStats;type = EQikCommandTypeScreen;text = "Game statistics";},QIK_COMMAND{id = EOandXDisplayHistory;type = EQikCommandTypeScreen;text = "Game history";},QIK_COMMAND{id = EOandXResetHistory;type = EQikCommandTypeScreen;text = "Reset history";},QIK_COMMAND{id = EOandXDisplayGame;type = EQikCommandTypeScreen;text = "Return to game";}};}The first three of these commands are ones that also appear in theGame view’s command menu.

Although a view-based application willnormally have a different set of menu options in each of its views, themenus will frequently contain common items. In such a case it is perfectlyCOMMAND MENUS417acceptable for the common commands to have not only the same text,but also the same ID.We have already discussed the additional code to handle the newcommands by activating the appropriate view. The updating of the available commands needs to be changed to take the additional commandsinto account. In the History view, for example, the updating code is:void COandXHistoryView::UpdateCommandsL(){iCommandManager.SetAvailable(*this, EOandXDisplayHistory,!iDisplayingHistory);iCommandManager.SetAvailable(*this, EOandXDisplayStats,iDisplayingHistory);}Since the UIQ version of the application in Chapter 12 already used aview, there are no other significant changes to be described.Changes for S60In Chapter 12, the S60 version of the Noughts and Crosses applicationdid not use a view for its display, so there are more command-menuchanges to describe.As in the UIQ version, the Game view has two additional menu items.RESOURCE MENU_PANE r_oandx_game_menu{items ={MENU_ITEM{command = EOandXNewGame;txt = "New game";},MENU_ITEM{command = EOandXFirstPlayer;txt = "Noughts move first";},MENU_ITEM{command = EOandXDisplayStats;txt = "Game statistics";},MENU_ITEM{command = EOandXDisplayHistory;txt = "Game history";}};}418VIEWS AND THE VIEW ARCHITECTUREThe new menu resource for the History view is as follows:RESOURCE MENU_PANE r_oandx_history_menu{items ={MENU_ITEM{command = EOandXDisplayStats;txt = "Game statistics";},MENU_ITEM{command = EOandXDisplayHistory;txt = "Game history";},MENU_ITEM{command = EOandXDisplayGame;txt = "Show game";},MENU_ITEM{command = EOandXResetHistory;txt = "Reset history";}};}As with the UIQ version, the updating of the available commands needsto be modified.

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

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

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

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