- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在学习 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/
我是一名优秀的程序员,十分优秀!