Поиск по ключевым словам для ListField в Blackberry

Я создаю ListField. в каждой строке я добавляю изображение и 3 поля метки. Может ли кто-нибудь сказать мне, как создать для этого ключевое словоfilterField... Заранее спасибо. Я новичок в ежевике. Небольшой код мне очень поможет. Это мой код для создания пользовательского списка.

class CustomListField extends ListField implements ListFieldCallback
{
String type;
int DISPLAY_WIDTH = Display.getWidth();
int DISPLAY_HEIGHT = Display.getHeight();
Vector mItems = new Vector();
Vector mine = new Vector();
Vector three= new Vector();     
// SizedVFM mListManager = new SizedVFM(DISPLAY_WIDTH, DISPLAY_HEIGHT - 40);
Bitmap searchresult = Bitmap.getBitmapResource("res/searchresult.png");
HorizontalFieldManager hfManager;
Bitmap image ,image1;
int z = this.getRowHeight();
CustomListField(String text1,String text2,String type) 
{
    for (int i = 1; i < 31; i++) 
    {      
        mItems.addElement(text1 +String.valueOf(i));
        mine.addElement("    "+text2);
        three.addElement("31");
    }
    this.type=type;
    this.setRowHeight((2*z));       
    this.setCallback(this);
    this.setSize(20);
    //mListManager.add(mListField);
    //add(mListManager);           
}
public void drawListRow(ListField field, Graphics g, int i, int y, int w) 
{
    // Draw the text.
    image = Bitmap.getBitmapResource("res/searchresult.png");
    String text = (String) get(field, i);
    String mytext = (String)mine.elementAt(i);
    String urtext=(String)three.elementAt(i);
    g.drawBitmap(0, y, image.getWidth(),image.getHeight(), image, 0, 0);
    g.drawText(text, image.getWidth(), y, 0, w);
    g.setColor(Color.GRAY);
    g.drawText(mytext, image.getWidth(), y+getFont().getHeight(), 0, w);
    g.drawText(urtext,Graphics.getScreenWidth()*7/8,y,0,w);
    if (i != 0) 
    {
          g.drawLine(0, y, w, y);
    }       
}

public Object get(ListField listField, int index) 
{
    return mItems.elementAt(index);
}

public int getPreferredWidth(ListField listField) 
{
    return DISPLAY_WIDTH;
}

public int indexOfList(ListField listField, String prefix, int start) 
{
    return 0;
}
protected boolean touchEvent(TouchEvent message) 
{
    // If click, process Field changed
    if ( message.getEvent() == TouchEvent.CLICK ) 
    {
        if(type.equals("Stops"))
            UiApplication.getUiApplication().pushScreen(new SearchScreen("Services")); 
        else if(type.equals("Services"))
            UiApplication.getUiApplication().pushScreen(new SearchScreen("Stops")); 
        return true;
    }
    return super.touchEvent(message);
}
}   

person Community    schedule 18.11.2011    source источник
comment
Вы можете использовать CustomListField с KeywordFilterField?   -  person Vivek Kumar Srivastava    schedule 22.12.2011


Ответы (1)


Проблема с KeywordFilterField заключается в том, что он внутри использует свой собственный ListField, поэтому я думаю, что его будет сложно настроить. Если вы хотите использовать его так, как он предоставлен, вам придется использовать его следующим образом:

    //KeywordFilterField contains a ListField to display and a search edit field to type in the words
    KeywordFilterField keywordFilterField = new KeywordFilterField();  

    //Instantiate the sorted collection:
    CustomList cl = new CustomList(mItems);

    //Pass the custom collection
    keywordFilterField.setSourceList(cl, cl); 


    //Now you have to add two fields: first the list itself
    myManager.add(keywordFilterField);
    //And the search field, probably you'd want it at top: 
    myScreen.setTitle(keywordFilterField.getKeywordField());

Вам нужно будет реализовать пользовательскую сортируемую коллекцию для хранения элементов, которые вы не хотите отображать:

    class CustomList extends SortedReadableList implements KeywordProvider {
        //In constructor, call super constructor with a comparator of <yourClass>
        public CustomList(Vector elements)
        {
            super(new <yourClass>Comparator());  //pass comparator to sort
            loadFrom(elements.elements());      
        } 

        //Interface implementation
        public String[] getKeywords( Object element )
        {        
            if(element instanceof <yourClass> )
            {            
                return StringUtilities.stringToWords(element.toString());
            }        
            return null;
        }  

        void addElement(Object element)
        {
            doAdd(element);        
        }

        //...
    }

У вас есть полная демонстрация, доступная в папке примеров JDE. Это называется демонстрационным фильтром ключевых слов.

Чтобы использовать пользовательский список, подобный тому, который вы разместили, вам, вероятно, придется закодировать много вещей, например, пользовательский EditField для ввода ключевых слов, получающих события для каждого введенного символа, связанного с поиском в отсортированной коллекции (возможно, вы для этого можно использовать SortedReadableList), который выберет в вашем ListField первый результат поиска, возвращаемый этой коллекцией.

person Mister Smith    schedule 18.11.2011