很简单的问题:扩展查看和添加监听到其子
我夸大一个观点:
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