其實官方出了一個關於LISTBOX的例子,例子很全基本包含了所有關於LISTBOX的
應用.小弟根據自己的研究和自己開發中的經驗在此總結一下.
其實LISTBOX有多種方格用法都非常接近,精通一個後基本都會了.
1.建立listbox
void CSingleListBoxContainer::CreateList()
{
iListBox = new (ELeave)CAknSingleStyleListBox;//建立listbox
iListBox->SetContainerWindowL(*this);//綁定視窗
// Second Phase Construction
TResourceReader reader;//載入資源
CEikonEnv::Static()->CreateResourceReaderLC
(reader,R_LISTBOX_SINGLE);//R_SIMPLELIST_LISTBOX);
iListBox->ConstructFromResourceL(reader);//用資源初始化
CleanupStack::PopAndDestroy(); // reader
///Add icon//載入表徵圖這裡的表徵圖可以有很多,不同類型的表徵圖代使用者使用
CArrayPtr<CGulIcon>* icons = new (ELeave) CArrayPtrFlat<CGulIcon>(1);
CleanupStack::PushL(icons);
icons->AppendL(iEikonEnv->CreateIconL(KDoubleListBoxmbm,EMbm20028c74Marked,
EMbm20028c74Marked_mask));
CleanupStack::Pop();
iListBox->ItemDrawer()->ColumnData()->SetIconArray(icons);
****AppUi* pAppui = static_cast<****AppUi*>(iCoeEnv->AppUi());//通常用的技巧.用UI儲存全
局變數資料
iOldIndex = pAppui->iSChoicendex;//得到上次選擇的索引
//以下是建立動態LISTBOX,根據需要建立listbox項
TInt len = pAppui->iNameArray.Count();
pAppui->iChoice = pAppui->iNameArray[iOldIndex]->GetName();//得到上次選擇的檔案名稱
if(len > 0)
{
//添加文本
CDesCArrayFlat* array = new (ELeave) CDesCArrayFlat(len);
CleanupStack::PushL(array);
for(TInt i=0;i<len;i++)
{
TBuf<50> buf;
buf.Append(_L("/t"));
buf.Append(pAppui->iNameArray[i]->GetName()->Des());
if(i == iOldIndex)
{
buf.Append(_L("/t0"));//在檔案最後添加/t0的方式選擇表徵圖
}
array->AppendL(buf);
}
CleanupStack::Pop();
iListBox->Model()->SetItemTextArray(array);
}
if(pAppui->iPriviewIndex < 0)
{
iListBox->SetCurrentItemIndex(iOldIndex);//建立完成LISTBOX後,設定選中的項
}
else
{
iListBox->SetCurrentItemIndex(pAppui->iPriviewIndex);//建立完成LISTBOX後,設定選
中的項
}
}
//響應使用者按OK鍵
void CSingleListBoxContainer::HandleListBoxEventL(CEikListBox* aListBox, TListBoxEvent
aListBoxEvent)
{
if (aListBoxEvent == MEikListBoxObserver::EEventEnterKeyPressed)
{
//響應OK鍵
}
}
//根據需求,重新設定LISTBOX上的文本.或者調整表徵圖
void CSingleListBoxContainer::ModifyItem()
{
CDesCArray* iListBoxArray= STATIC_CAST(CDesCArray*, iListBox->Model()->ItemTextArray());
//得到LISTBOX上的所有文本,並轉換成數組
TInt len = iListBoxArray->Count();
for(TInt i=0;i<len;i++)
{
if(i == iOldIndex)
{
TBuf<120> buf;
buf.Append(_L("/t"));
buf.Append(pAppui->iNameArray[i]->GetName()->Des());
iListBoxArray->Delete(i);//先刪掉原有文本
iListBoxArray->InsertL(i,buf);//再重新插入文本.
//用此方式才能修改內容
}
if(i == index)
{
TBuf<120> buf;
buf.Append(_L("/t"));
buf.Append(pAppui->iNameArray[i]->GetName()->Des());
buf.Append(_L("/t0"));
iListBoxArray->Delete(i);
iListBoxArray->InsertL(i,buf);
}
}
iListBox->DrawNow();//設定完成後,記得一定要重繪
}
TKeyResponse CSingleListBoxContainer::OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode
aType)
{
//響應上下左右鍵
if (iListBox)
return iListBox->OfferKeyEventL (aKeyEvent, aType);
else
return EKeyWasNotConsumed;
}
//得到當將使用者選中的項
TInt CSingleListBoxContainer::GetListBoxIndex()
{
if(iListBox)
{
return iListBox->CurrentItemIndex();
}
return 0;
}