GWT单选按钮变化处理程序

6

我有一个投票小部件,其中包含单选按钮和标签投票。

  1. 当用户选择一个选项时,该选项的投票应+1;
  2. 当选择另一个选项时,旧选项的投票应-1,新选项的投票应+1。

我使用了ValueChangeHandler来实现这个功能:

valueRadioButton.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
            @Override
            public void onValueChange(ValueChangeEvent<Boolean> e) {
                if(e.getValue() == true)
                {
                    System.out.println("select");
                    votesPlusDelta(votesLabel, +1);
                }
                else
                {
                    System.out.println("deselect");
                    votesPlusDelta(votesLabel, -1);
                }
            }
        }); 

private void votesPlusDelta(Label votesLabel, int delta)
{
    int votes = Integer.parseInt(votesLabel.getText());
    votes = votes + delta;
    votesLabel.setText(votes+"");
}

当用户选择新的选项时,旧的选项监听器应该跳转到 else 语句,但它并不会(只有 +1 的部分有效)。我该怎么办?
2个回答

9
RadioButton文档中指出,当清除单选按钮时不会接收到ValueChangeEvent。不幸的是,这意味着您需要自己进行所有记录操作。
作为GWT问题跟踪器建议中创建自己的RadioButtonGroup类的替代方案,您可以考虑执行以下操作:
private int lastChoice = -1;
private Map<Integer, Integer> votes = new HashMap<Integer, Integer>();
// Make sure to initialize the map with whatever you need

当您初始化单选按钮时:

List<RadioButton> allRadioButtons = new ArrayList<RadioButton>();

// Add all radio buttons to list here

for (RadioButton radioButton : allRadioButtons) {
    radioButton.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
            @Override
            public void onValueChange(ValueChangeEvent<Boolean> e) {
                updateVotes(allRadioButtons.indexOf(radioButton));
        });
}

更新投票的方法大致如下:
private void updateVotes(int choice) {
    if (votes.containsKey(lastChoice)) {
        votes.put(lastChoice, votes.get(lastChoice) - 1);
    }

    votes.put(choice, votes.get(choice) + 1);
    lastChoice = choice;

    // Update labels using the votes map here
}

虽然不是非常优雅,但它应该能够完成工作。


2

这个特定问题在GWT问题跟踪器上存在一个未解决的缺陷。最后一条评论有一个建议,基本上看起来你需要在所有单选按钮上添加更改处理程序,并自己跟踪分组...

干杯!


1
问题已移至 GitHub:https://github.com/gwtproject/gwt/issues/3467 - Geoffrey Zheng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接