我假設你已經匿名了你的這個網站的代碼。我會建議@Sotirios Delimanolis回答了什麼,但我認爲你實際上做得太多太少。
您已經將控制器綁定到視圖太多,並且您已將視圖綁定到彼此之間。爲什麼他們都應該在相同的switch
聲明?
如果添加其他視圖,您需要更改多少?
相反,您應該讓每個視圖註冊一個PropertyChangeListener
,該對象包含minindex
。順便說一句,這是一個糟糕的名字。當對象更改爲minindex
時,它應該向所有偵聽器發送PropertyChangeEvent
。每個視圖的偵聽器應該檢查事件是否希望該視圖變爲可見;如果是的話,這個觀點應該會喚醒自己。
class ViewController {
private PropertyChangeSupport pcs = new PropertyChangeSupport();
// delegate methods to add and remove listeners to pcs variable.
private int viewIndex; // Changed for documentation. Use String instead?
public void setViewIndex(final int viewIndex) {
int oldIndex = this.viewIndex;
this.viewIndex = viewIndex;
pcs.firePropertyChange("viewIndex", oldIndex, this.viewIndex);
}
}
class ViewOne {
private ViewController vc;
private final Integer myIndex = 1;
// Constructor
public void init() {
// Never add this or an inner class to another object in a constructor.
vc.addPropertyChangeListener("viewIndex",
new PropertyChangeListener() {
public propertyChange(final PropertyChangeEvent evt) {
if (myIndex.equals(evt.getNewValue()) {
setVisibility(View.VISIBLE);
}
}
});
}
}
有關構造函數的警告是,如果你暴露this
或內部類的this
在構造函數中的另一個對象,外部對象可以與this
互動之前,完全構造。您可以在構造函數中構建PCL;使用另一種方法將其添加到控制器。
不知道這是多麼實際,但將視圖的所有引用改爲數組。然後使用視圖[minIndex]來引用它們。 – initramfs
儘管我同意Sotirios的答案,但這是假設。 Y我們目前的代碼給你一個確切的邏輯。如果你的邏輯完好無損,代碼的大小就不重要了。 –