UI层级结构:
TasksActivity
NavigationView
headerLayout="@layout/nav_header"//自定义navigation的头部
menu="@menu/drawer_actions"//自定义菜单
ToolBar
setHomeAsUpIndicator(R.drawable.ic_menu);//生成菜单项 case android.R.id.home:
onOptionsItemSelected(MenuItem item) //菜单的回调
TasksFragment
setHasOptionsMenu(true);
onCreateOptionsMenu(Menu menu,MenuInflater inflater){
inflater.inflate(R.menu.tasks_fragment_menu,menu);
}
mvp结构
BaseView
public interface BaseView{
void setPresenter(T presenter);//通过泛型将对应的本view对应的presenter赋值给view
}
BasePresenter
public interface BasePresenter{
void start();
}
TasksContract
public interface TasksContract{
//这是是interface还是class 都无所谓,主要用户给内部类一个包装。
interface View extends BaseView{
......//对应UI层逻辑接口
}
interface Presenter extends BasePresenter{
......//对应业务层逻辑接口
}
}
TasksPresenter
通过让View,Presenter 互相持有来让presenter实现逻辑后回调给View;
如:
//TasksFragment.java
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mPresenter.result(requestCode, resultCode);
}
...
//TasksPresenter.java
@Override
public void result(int requestCode, int resultCode) {
// If a task was successfully added, show snackbar
if (AddEditTaskActivity.REQUEST_ADD_TASK == requestCode && Activity.RESULT_OK == resultCode) {
mTasksView.showSuccessfullySavedMessage();
}
}
public class TasksPresenter implements TasksContract.Presenter{
private final TasksContract.View mTasksView;//持有view
public TasksPresenter(@NonNull TasksRepository tasksRepository,@NotNull TaskConract.View tasksView){
...
mTasksView=checkNotNull(taskView,"tasksView cannot be null");
mTasksView.setPresenter(this);//baseView基类方法,view持有presenter。
}
@Override
public void start(){
loadTask(false);
}
页面的点击逻辑都在view中
单看view接口的协议定义,主要交互动作的方法和UI显示方法
点击之后的不同反应都放到presenter里面,在presenter里实现完逻辑后,回调View的接口定义方法。
单看presenter接口的协议定义,主要业务逻辑方法(用来实现对数据获取,修改)