Главная » Просмотр файлов » Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007

Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 75

Файл №779887 Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (Symbian Books) 75 страницаWiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887) страница 752018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

If, for example, thedata items it is displaying are the fields of a database record, you canimplement the commands described above to add, delete, or modifyentire records.You can specify that the form should be edit-only (via a flag in theFORM resource), so that the form is always in ‘edit’ mode, and in thiscase, the Edit menu option does not appear. You can also overrideits DynInitMenuPaneL() to disable some or all of the other menuoptions.You specify a form in the resource file by creating a FORM resourceand assigning it to the form attribute of a DIALOG resource (or a PAGEresource for multipage dialogs).

The FORM resource contains the listof DLG LINES that specify the label and control for each field in theform’s list.The above description of forms is, of necessity, brief. You shouldrefer to the SDK documentation for examples, and a more completeexplanation.398GUI APPLICATION PROGRAMMINGFor now, let’s look at a form-based implementation of the SimpleExdialog that modifies both the displayed text and its color. This exampleillustrates many of the features of a form, and displays the dialog shownin Figure 12.10.Here is the form’s definition in the resource file:RESOURCE DIALOG r_SimpleEx_dialog{flags=EEikDialogFlagNoDrag|EEikDialogFlagFillAppClientRect|EEikDialogFlagNoTitleBar|EEikDialogFlagWait|EEikDialogFlagCbaButtons;buttons=R_AVKON_SOFTKEYS_OPTIONS_BACK;form=r_SimpleEx_form;}RESOURCE FORM r_SimpleEx_form{flags = EEikFormEditModeOnly | EEikFormUseDoubleSpacedFormat;items={DLG_LINE{type=EEikCtEdwin;prompt="Text";id=ESimpleExText;control=EDWIN { width=10; maxlength=256;};},DLG_LINE{type=EAknCtPopupFieldText;prompt="Color";id=ESimpleExPopup;itemflags=EikDlgItemTakesEnterKey|EEikDlgItemOfferAllHotKeys;control = POPUP_FIELD_TEXT{popupfield=POPUP_FIELDFigure 12.10 Form-Based SimpleEx Dialog for S60DIALOGS399{width=10;};textarray=r_color_list;};}};}RESOURCE{items={LBUFLBUFLBUFLBUF};}ARRAY r_color_list{{{{txt="Black"; },txt="Red"; },txt="Green"; },txt="Blue"; }As you can see, the DIALOG resource defines the flags and softkeys, asin the earlier examples, and the form attribute points to a FORM resource.This resource specifies the dialog’s content which, in this case, consistsof two dialog lines: the text edit box and an S60-specific control, knownas a pop-up field (type EAknCtPopupFieldText and control structurePOPUP FIELD), which is used to select the text color.

The FORM resourcehas an additional flags attribute, which is used here to set each controland its prompt to be displayed on separate lines, and to set the ‘edit only’mode that was mentioned earlier.Here is the dialog class definition:class CSimpleExForm : public CAknForm{public:static CSimpleExForm* NewL(TDes& aText,TRgb& aColor);private:CSimpleExForm(TDes& aText,TRgb& aColor);// Inherited from CAknFormvoid DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane);TBool SaveFormDataL();void PreLayoutDynInitL();TDes& iText;TRgb& iColor;};The corresponding implementation is:#include#include#include#include#include#include"SimpleEx.h""SimpleEx.hrh""eikedwin.h"<AknPopupFieldText.h> // CAknPopupFieldText<avkon.rsg> // R_AVKON_FORM_MENUPANE<eikmenup.h> // CEikMenuPane400GUI APPLICATION PROGRAMMINGconst TInt KNumColors=4;const TRgb colorList[KNumColors] ={KRgbBlack, KRgbRed, KRgbGreen, KRgbBlue};CSimpleExForm* CSimpleExForm::NewL(TDes& aText,TRgb& aColor){CSimpleExForm* self = new (ELeave) CSimpleExForm(aText, aColor);CleanupStack::PushL(self);self->ConstructL();CleanupStack::Pop(self);return self;}CSimpleExForm::CSimpleExForm(TDes& aText, TRgb& aColor):iText(aText), iColor(aColor){}void CSimpleExForm::PreLayoutDynInitL(){static_cast<CEikEdwin*>(Control(ESimpleExText))->SetTextL(&iText);TInt currColorIndex = 0;for ( TInt i = 0; i < KNumColors; i++ ){if ( iColor == colorList[i] ){currColorIndex = i;break;}}CAknPopupFieldText* popupFieldText = static_cast<CAknPopupFieldText*>(ControlOrNull(ESimpleExPopup));if (popupFieldText){popupFieldText->SetCurrentValueIndex (currColorIndex);}}void CSimpleExForm::DynInitMenuPaneL(TInt aResourceId, CEikMenuPane*aMenuPane){CAknForm::DynInitMenuPaneL(aResourceId,aMenuPane);if (aResourceId == R_AVKON_FORM_MENUPANE){aMenuPane->SetItemDimmed(EAknFormCmdLabel, ETrue);aMenuPane->SetItemDimmed(EAknFormCmdAdd, ETrue);aMenuPane->SetItemDimmed(EAknFormCmdDelete, ETrue);}}TBool CSimpleExForm::SaveFormDataL(){CEikEdwin* nameEditor = static_cast <CEikEdwin*>(ControlOrNull(ESimpleExText));if (nameEditor)DIALOGS401{nameEditor->GetText(iText);}CAknPopupFieldText* popupFieldText = static_cast<CAknPopupFieldText*>(ControlOrNull(ESimpleExPopup));if (popupFieldText){iColor = colorList[popupFieldText->CurrentValueIndex()];}return ETrue;}PreLayoutDynInit() is overridden, as in our earlier dialogexample, to set the initial values of the controls in the form.

As before,we use CEikEdwin for the text editor control. For the color list, we usethe CAknPopupFieldText class, which corresponds to the EAknCtPopupFieldText control type that is specified in the resource file.In a form, you override CAknForm’s SaveFormDataL() functionwith the logic needed to have your dialog settings take effect. SaveFormDataL() is called when the user selects the Save option on the formmenu. In this example, SaveFormDataL() reads the control’s valuesand assigns them to the text and color references passed to our form, thusenabling them to take effect.Since we do not want the user to be able to add or delete data, or edit thefield labels for our simple example, we override DynInitMenuPaneL()and disable the corresponding menu items.

Calling SetItemDimmed()on these menu items has the effect of removing them from the form’smenu. We don’t need to dim the Edit menu item (which normallyswitches the form from ‘view’ mode to ‘edit’ mode), since it is automatically suppressed for an ‘edit only’ form.In HandleCommand(), the form dialog is launched as follows:case ESimpleExDialog:CSimpleExForm* form = CSimpleExForm::NewL(iAppView->iDisplayText,iAppView->iTextColor);form->ExecuteLD(R_SIMPLEEX_DIALOG);break;12.5.3 Using Stock DialogsSymbian OS has some predefined dialogs that you can use for convenience, and some of these vary from platform to platform. I will brieflycover some of the main ones in this section.402GUI APPLICATION PROGRAMMINGDialogs common to all UI platformsThe following methods of CEikonEnv are a quick way to put up somesimple, commonly used dialogs without defining a class or creating aresource.

They are available to all UI platforms.static void CEikonEnv::InfoWinL(const TDesC& aLine1, const TDesC& aLine2)This is a static function that displays an information dialog with thespecified lines of text.void CEikonEnv::AlertWin(const TDesC& aLine1, const TDesC& aLine2)This displays an alert dialog with the specified lines of text.TBool CEikonEnv::QueryWinL(TInt aFirstLineId, TInt aSecondLineId=0)This displays a Yes/No query dialog with the specified lines of text,supplied as resource identifiers.

QueryWinL() returns ETrue if Yes wasselected, and EFalse if No.UIQ stock dialogsThese dialogs are straightforward to use, in that no resources need bedefined. You just call the class’s static function RunDlgLD() (with theappropriate arguments) and the dialog will be constructed and displayed.RunDlgLD() will return when the dialog is dismissed, and the dialog data will be returned in the appropriate parameters passed to thefunction.For example, CEikTimeDialogSetTime displays a dialog allowingthe user to enter the time and date. Below is an example of the code todisplay this (you need to include file eiktime.h):TTime currentDateTime;// Launch the dialog and get the date and time from the dialog.if(CEikTimeDialogSetTime::RunDlgLD(currentDateTime)){// currentDateTime now contains the date and time entered.}The TTime class holds the time and date, as well as providing manyformatting functions for text display.

It also supplies comparison functionsfor calculating intervals between two TTime instances.DIALOGS403Other UIQ stock dialog classes include:•CEikSetPasswordDialog sets a password, providing both password and confirmation fields.•CEikTimeDialogSetCity allows the user to set allocation, byselecting a country and city.•CEikEdwinFindDialog allows the user to find text.•CQikZoomDialog allows the user to set the zoom level.To use these dialogs, be sure to include the appropriate include file.

In theLIBRARY section of your MMP file, you also need to add eikcdlg.libto use dialogs that begin with CEik, and qikdlh.lib to use dialogsthat begin with CQik.S60 predefined dialogsS60 provides a set of standard query dialogs to obtain specific types ofdata from the user. Each of these dialogs requires that a DIALOG resourcebe created, with its flags attribute set to EGeneralQueryFlags, plusa DLG LINE with control type set to EAknCtQuery and id set toEGeneralQuery.

Here are a couple of examples.Confirmation query dialogA confirmation query dialog uses class CAknQueryDialog. Below is aresource defined for it:RESOURCE DIALOG r_yes_no_dialog{flags = EGeneralQueryFlags;buttons = R_AVKON_SOFTKEYS_YES_NO;items ={DLG_LINE{type = EAknCtQuery;id = EGeneralQuery;control = AVKON_CONFIRMATION_QUERY{layout = EConfirmationQueryLayout;label = "Are you sure you want to do this?";};}};}And the code to invoke it is:CAknQueryDialog* dlg = CAknQueryDialog::NewL(aQueryTxt);return dlg->ExecuteLD(R_YES_NO_DIALOG);404GUI APPLICATION PROGRAMMINGAlthough not used in this example, AVKON CONFIRMATION QUERY alsohas bitmap and animation attributes.Text queryCAknTextQueryDialog is a class used to display a dialog that promptsthe user for a text entry. Below is an example resource definition for it:RESOURCE DIALOG r_demo_data_query{flags = EGeneralQueryFlags;buttons = R_AVKON_SOFTKEYS_OK_CANCEL;items ={DLG_LINE{type = EAknCtQuery;id = EGeneralQuery;control = AVKON_DATA_QUERY{layout = EDataLayout;label = "Enter Text:"; // prompt textcontrol = EDWIN{width = 5;lines = 1;maxlength = 15;};};}};}And the code to invoke it is:TBuf<20> text; //where the user text will be placedCAknTextQueryDialog* dlg =CAknTextQueryDialog::NewL(text);// Sets the maximum length of the text editor, if you want to expand or// shrink from resource value.dlg->SetMaxLength(20);// Launch the dialogif (dlg->ExecuteLD(R_DEMO_DATA_QUERY)){// ok pressed, text is the descriptor containing// the entered text in the editor.}This displays a text edit box with the prompt ‘Enter text:’.

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

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

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

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