2014-04-03 22 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