2014-04-03 24 views
0

很簡單的問題:擴展查看和添加監聽到其子

我誇大一個觀點:

final View dialogView = inflater.inflate(R.layout.dialog_location, null); 

final EditText location_input   = (EditText) dialogView.findViewById(R.id.location_input); 
final View location_button_clear  = dialogView.findViewById(R.id.location_button_clear); 
final Button current_location_dialog = (Button) dialogView.findViewById (R.id.current_location_dialog); 

而且我後來路過很多聽衆對每個子視圖例如

location_button_clear.setOnClickListener(new View.OnClickListener() { ... } 
current_location_dialog.setOnClickListener(new View.OnClickListener() { ... } 
location_input.addTextChangedListener(new TextWatcher() { ... } 

這使得我的代碼是spageti,我不喜歡它。爲了可維護性的原因,我想創建一個新的單獨的類內有該文件的聽衆等

是否有可能擴展dialogView作爲一個視圖?例如

public class DialogView extends View{ 
    // somehow here inflate the R.layout.dialog_location 
    // get the children and set the listeners 
} 

或我的唯一的選擇就是DialogView延伸作爲Fragment例如

public class DialogView extends Fragment{ 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.dialog_location, container, false); 
    } 

    // other stuff here 
} 

更新:

我的主要問題是如何膨脹R.layout.dialog_location如果我延長視圖

回答

0

可以完美擴展View這一點,你原來節目dialogViewView型。然而,由於您沒有指定如何計劃組織它,我不確定這將如何強化您的代碼可讀性。

爲了維護原因,我想最好建議如下:

  • 如果您使用相同Listener幾個View S,分別定義並分配相同的Listener所有View小號那會有相同的行爲。

  • 如果你有很多Listener s,我會創建一個單獨的類作爲Singleton並定義整個實現。之後,如果您需要將它們分配給您的某些View s,那麼您可以撥打myView.setOnWhateverListener(...)上的mySingleton.getMyFooListener()

+0

我只是想創建一個「增強視圖」。聽衆不是那麼重要(只用一次來回答你的問題),但我只想用一些額外的功能(嵌入的孩子和他們的聽衆)來製作這個視圖,而不是再次參與該代碼。檢查更新 – Diolor

+0

最好的方法是膨脹具有其佈局的類內的'View'。很難甚至不鼓勵從沒有包含它的佈局的類訪問'View'。這就是爲什麼我建議將「硬代碼」分離成一個單獨的類,這樣你就可以在佈局實現的地方將輔助代碼(監聽器和類似的東西)放在一個單獨的類中,你可以簡單地調用'getMyListener )'來獲得它,而不是讓你的代碼混淆。 – nKn