Java Blackberry ListField:在更新期间保持行焦点
使用下面的代码刷新包含xml web服务中返回的数据的列表字段之后。但在刷新后或刷新时,它会将焦点设置为ListField中的第一行。我不想那样。我希望它在刷新后保持当前焦点,这样用户甚至不会知道有刷新Java Blackberry ListField:在更新期间保持行焦点,java,blackberry,java-me,Java,Blackberry,Java Me,使用下面的代码刷新包含xml web服务中返回的数据的列表字段之后。但在刷新后或刷新时,它会将焦点设置为ListField中的第一行。我不想那样。我希望它在刷新后保持当前焦点,这样用户甚至不会知道有刷新 protected void onUiEngineAttached(boolean attached) { if (attached) { // TODO: you might want to show some sort of animated /
protected void onUiEngineAttached(boolean attached) {
if (attached) {
// TODO: you might want to show some sort of animated
// progress UI here, so the user knows you are fetching data
Timer timer = new Timer();
// schedule the web service task to run every minute
timer.schedule(new WebServiceTask(), 0, 60*1000);
}
}
public MyScreen() {
setTitle("yQAforum");
listUsers.setEmptyString("No Users found", 0);
listUsers.setCallback(this);
add(listUsers);
}
private class WebServiceTask extends TimerTask {
public void run() {
//Fetch the xml from the web service
String wsReturnString = GlobalV.Fetch_Webservice("myDs");
//Parse returned xml
SAXParserImpl saxparser = new SAXParserImpl();
ByteArrayInputStream stream = new ByteArrayInputStream(wsReturnString.getBytes());
try {
saxparser.parse( stream, handler );
}
catch ( Exception e ) {
response.setText( "Unable to parse response.");
}
// now, update the UI back on the UI thread:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
//Return vector sze from the handler class
listUsers.setSize(handler.getItem().size());
// Note: if you don't see the list content update, you might need to call
// listUsers.invalidate();
// here to force a refresh. I can't remember if calling setSize() is enough.
}
});
}
}
如前所述,您需要在刷新列表之前记录当前焦点行,然后在更新后立即再次设置焦点行
例如,在webservicecask
中:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
int currentIndex = listUsers.getSelectedIndex();
int scrollPosition = getMainManager().getVerticalScroll();
//Return vector sze from the handler class
listUsers.setSize(handler.getItem().size());
listUsers.setSelectedIndex(currentIndex);
getMainManager().setVerticalScroll(scrollPosition);
}
});
在您在评论中发布的代码中,您调用了
setSelectedIndex()
,结果是getSelectedIndex()
在执行刷新后,该操作将永远不会执行您想要的操作。在更新数据之前获取当前选定的行,然后使用该索引。检查文档。使用getSelectedIndex()
和setSelectedIndex(int index)
。我应该在代码中的哪一点实现它?因为我试过了,但没用。getSelectedIndex();setSize(handler.getItem().size());listUsers.setSelectedIndex(listUsers.getSelectedIndex());内特,谢谢,成功了!我非常感激。但我仍然无法保持滚动位置。我该怎么办呢?我看不出你的MyScreen
类是如何定义的,但我猜它是MainScreen
之类的。因此,它将包含一个主管理器,通常是垂直字段管理器
。主管理器控制滚动。因此,就像您记录并重置当前选定的列表索引一样,您需要记录并重置当前垂直滚动位置。请参阅我对上述答案的更新。此外,记住接受和/或投票选出对你有帮助的答案。谢谢,内特,谢谢。但是,您认为这种方法是实现列表字段自动刷新的最佳实践吗?用web服务中返回的数据更新它?好的,正如我在回答上一个问题时所说的,还有其他事情需要考虑。您需要添加代码来处理网络故障。您应该保护WebServiceTask
,以便在1分钟前的刷新仍在进行时,它不会尝试刷新。我不知道你的应用程序做什么,但对于很多应用程序,用户不会喜欢他们的手机每分钟自动拨打网络电话。这会耗尽电池电量。如果只在必要时拨打网络电话会更好。但是,如果我不更好地理解这个应用程序,我就不能提出这个建议。这个应用程序就像一个新闻提要应用程序。这意味着该列表需要使用当前新闻进行更新。我真的需要你的推荐。非常感谢。