2015-04-18 80 views
2

在嘗試使用GWT的ListEditor系統時,我無法找到一個工作示例,其中列表中每個項目的UI都有一個刪除/刪除按鈕。如何讓單個項目/子編輯器的GWT編輯器將其本身從包含它的ListEditor中移除?例如點擊刪除按鈕

我發現的例子是所有喜歡this one [1]和具有EditorSource.create()實現創建的每個項目Editor並出現要連接的處理程序經由listEditor.getList().remove(index)從底層列表中刪除該項目。

但是,刪除處理程序的匿名實現會在創建子編輯器時關閉索引值,導致IndexOutOfBoundExceptions或錯誤的項目被刪除,因爲每次刪除都會更改所有項目的索引之後。

我把頭髮拉出去了一會兒,試圖查看我在發生這種事情的例子中缺少的東西,但是從我所能告訴他們真的都有這個問題,所以雖然修復非常簡單,我仍然會在這裏發佈它,所以至少有一個例子可以讓人發現它能正確刪除項目。我認爲我發現的所有例子都是從我鏈接的例子中派生出來的,儘管那個例子在remove()中有更多的邏輯,並且可能一直在做某些事情來避免像修正列表順序不知何故,我還沒有挖掘到該項目中的其他代碼。

回答

4

以下是最小的ListEditor示例,用於糾正其他示例中發現的問題。

public abstract class FooEditor extends Composite implements Editor<Foo> { 

    Widget root; // Instantiated explicitly or through uibinder 

    // Implemented as one of uibinder+fields, fields, methods, or LeafValueEditor.set/getValue() 

    public FooEditor() { 
     initWidget(root); 
    } 

    // Used for brevity, could be any triggering mechanism, click handler, event handler, etc. 
    abstract void onDeleteClicked(); 
} 

public class FooListEditor extends Composite implements IsEditor<ListEditor<Foo, FooEditor>> { 

    private class FooEditorSource extends EditorSource<FooEditor> { 

     @Override 
     public FooEditor create(int index) { 

      FooEditor subEditor = new FooEditor() 
      { 
       @Override 
       public void onDeleteClicked() 
       { 
        // ======================================================= 
        // 
        // This fixes the problem present in other examples 
        // by determining the current index at the time of removal 
        // 
        // ======================================================= 
        int currentIndex = listEditor.getEditors().indexOf(this); 
        listEditor.getList().remove(currentIndex);  
       } 
      }; 

      setIndex(subEditor, index); 

      return subEditor; 
     } 

     @Override 
     public void dispose(FooEditor subEditor) { 
      subEditor.removeFromParent(); 
     } 

     @Override 
     public void setIndex(FooEditor subEditor, int index) { 
      listPanel.insert(subEditor, index); 
     } 
    } 

    FlowPanel listPanel; // Instantiated explicitly or through uibinder 

    ListEditor<Foo, FooEditor> listEditor = ListEditor.of(new FooEditorSource()); 

    public FooListEditor() { 
     initWidget(listPanel); 
    } 

    @Override 
    public ListEditor<Foo, FooEditor> asEditor() { 
     return listEditor; 
    } 
} 
+1

非常感謝你的加入。絕對有用的社區:) – slugmandrew

相關問題