gpt4 book ai didi

java - 是否必须创建内部类来处理 DataBinding 中的事件?

转载 作者:行者123 更新时间:2023-12-04 08:48:05 25 4
gpt4 key购买 nike

我正在学习 DataBinding,特别是关于处理事件和点击事件的部分。现在,我注意到在一些 YouTube 教程中,我的讲师主要使用内部类来处理这些事件。然而,早些时候,我编写了实现 View.OnClickListener 并直接允许我处理点击事件的代码。
这里是:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private ActivityMainBinding activityMainBinding;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
activityMainBinding.enterButton.setOnClickListener(this);
}

@Override
public void onClick(View view) {
if (view == activityMainBinding.enterButton) {
String name = activityMainBinding.nameEditText.getText().toString();
String email = activityMainBinding.emailEditText.getText().toString();
String country = activityMainBinding.countryEditText.getText().toString();

User user = new User(name, email, country);
activityMainBinding.setUser(user);
}
}
}
这有效。
我想知道,这种处理点击事件的形式不被认为是一种好习惯吗?我检查了更多的教程,它们都使用了内部类,从而引起了这个疑问。
谢谢你的帮助。

最佳答案

问:是否需要创建内部类?

A: No, absolutely not. It's merely a useful convention :)


问:这种处理点击事件的形式……是一种好习惯吗?

A: In general, any individual "class" should do "one thing". The class's properties and its methods should match the class's "abstraction".

For example, an "Automobile" class should probably not have an "onClick()" method. Even if your "Automobile" class implementation might have a "button", with an "onClick()" method.

Or your "Automobile" might have a dozen different buttons. In that case, I'd definitely prefer to see a dozen anonymous inner classes, one for each button. It would be shorter; it would be cleaner.

In your example, however, I don't see any problem. It looks fine :)

关于java - 是否必须创建内部类来处理 DataBinding 中的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64214037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com