我很困惑...我正在尝试学习MVP模式,并且在该代码中实现此问题:
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
Log.d(TAG, "onDataSet: dd/mm/yyyy: " + year + "/" + month + "/" + dayOfMonth);
String date = dayOfMonth + "/" + month + "/" + year;
dateText.setText(date);
}
};
和:
@OnClick(R.id.date_text)
public void onClickDate() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog_MinWidth, mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
有人可以教我如何在MVP中正确编写此代码吗? 我知道它是如何工作的,但是对于初学者来说,这个例子很难理解。
答案 0 :(得分:2)
我要去的方式是:
定义视图(活动)的界面
public interface MyView {
public void setDateText (String date);
public void displayDatePickerDialog(int year, int month, int day);
}
然后,演示者将如下所示:
public class MyPresenter {
MyView view;
public MyPresenter (MyView view){
this.view = view;
}
public void onDateSet(int year, int month, int dayOfMonth){
month = month + 1;
String date = dayOfMonth + "/" + month + "/" + year;
view.setDateText(date);
}
public void onDateClicked (){
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
view.displayDatePickerDialog(year, month, day);
}
您的活动应如下所示:
public class MainActivity extends AppCompatActivity implements MyView{
MyPresenter myPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
myPresenter = new MyPresenter(this);
}
@OnClick(R.id.date_text)
public void onClickDate() {
myPresenter.onDateClicked();
}
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
myPresenter.onDateSet(year, month, dayOfMonth);
}
};
@Override
public void setDateText (String date){
dateText.setText(date);
}
@Override
public void displayDatePickerDialog(int year, int month, int day){
DatePickerDialog dialog = new DatePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog_MinWidth, mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
}