0

我对黑莓很陌生,我想将项目动态添加到列表视图中,我在列表字段中静态添加项目,但我想在我的代码中动态添加一些项目

ListCallBack.java

import java.util.Vector;

import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;

public class ListCallBack implements ListFieldCallback{

private Vector listElements = new Vector();
public void drawListRow(ListField listField, Graphics graphics, int index,
        int y, int width) {
    // TODO Auto-generated method stub
    String text = (String)listElements.elementAt(index);
    graphics.drawText(text, 0, y, 0, width);
 // Draw a line separator above each field except the first one
    if (index != 0) {
        graphics.setColor(Color.BLACK);
        graphics.drawLine(0, y, width, y);
    }

}

public Object get(ListField listField, int index) {
    // TODO Auto-generated method stub
    return listElements.elementAt(index);
}

public int getPreferredWidth(ListField listField) {
    // TODO Auto-generated method stub
    return Display.getWidth();
}

public int indexOfList(ListField listField, String prefix, int start) {
    // TODO Auto-generated method stub
    return listElements.indexOf(listField);
}

public void insert(String toInsert, int index) {
    listElements.insertElementAt(toInsert, index);
}

public void erase() {
    listElements.removeAllElements();
}

}

和 ListView.java

listItem = new ListField();
listCallBack =new ListCallBack();
listItem.setCallback(listCallBack);

listItem.insert(0);
listCallBack.insert("Can't Text Now Driving", 0);       
listItem.insert(1);
listCallBack.insert("Going to school", 1);    
listItem.insert(2);
listCallBack.insert("Picking Up the Kids", 2);
add(listItem);

任何人都可以帮助我吗?

4

2 回答 2

2

您可以在 ListField 对象上调用 invalidate() 或 invalidate(int index) 来验证更改。只需尝试以下

// after calling insert(int index) call 
listItem.invalidate(index);

// and after calling erase call 
listItem.invalidate();
于 2012-05-24T06:53:51.647 回答
1

if you want to show new items to the List field then add the item to the vector(in your case add to listElements) then call setsize() method on listfield object with the size of the increased vector.

listItem.setSize(listElements.size());

you dont directly add items to the listfield. you add it to your collection or array. when ever drawlist will be called for a row it read the data from the collection and render itself.

so simple do the following steps,

listElements.add(Object);

listItem.setSize(listElements.size());

you can then call invalidate over itemlist.

I hope i could give you have an idea so that you can find a way...

let me know if you have any doubt.

于 2012-05-28T21:00:17.143 回答