很簡單的問題:擴展查看和添加監聽到其子
我誇大一個觀點:
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
如果我延長視圖
我只是想創建一個「增強視圖」。聽衆不是那麼重要(只用一次來回答你的問題),但我只想用一些額外的功能(嵌入的孩子和他們的聽衆)來製作這個視圖,而不是再次參與該代碼。檢查更新 – Diolor
最好的方法是膨脹具有其佈局的類內的'View'。很難甚至不鼓勵從沒有包含它的佈局的類訪問'View'。這就是爲什麼我建議將「硬代碼」分離成一個單獨的類,這樣你就可以在佈局實現的地方將輔助代碼(監聽器和類似的東西)放在一個單獨的類中,你可以簡單地調用'getMyListener )'來獲得它,而不是讓你的代碼混淆。 – nKn