<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="Hello World!"
/>
<ProgressBar
android:id="@+id/bar"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
/***主界面:点击事件(用来获取用户名和密码)*实现接口*/ public class MainActivity extends AppCompatActivity implements LoginView {
private TextView text;
private ProgressBar bar;
private LoginPresenter mLoginPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoginPresenter = new LoginPresenter(this);
text = findViewById(R.id.text);
bar = findViewById(R.id.bar);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mLoginPresenter.login("张文龙","zhangwenlong");
}
});
}
@Override
public void onSucess(String result) {
Toast.makeText(this,result,Toast.LENGTH_SHORT).show();
}
@Override
public void onFailer(String msg) {
Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
}
@Override
public void show() {
bar.setVisibility(View.VISIBLE);
}
@Override
public void hide() {
bar.setVisibility(View.GONE);
}
}
/**定义一个接口(实现成功与失败的方法)/
public interface LoginCallBack {
void onLoginSuccess(String result);
void onLoginFailer(String msg);
}
/1.实例化接口跟类2.定义有参构造3.测试登录/
public class LoginPresenter {
private LoginView mLoginView;
private LoginBiz mLoginBiz;
public LoginPresenter(LoginView mLoginView){
this.mLoginView = mLoginView;
mLoginBiz = new LoginBiz();
}
public void login(String name,String password){
mLoginView.show();
mLoginBiz.login(name, password, new LoginCallBack() {
@Override
public void onLoginSuccess(String result) {
mLoginView.onSucess(result);
mLoginView.hide();
}
@Override
public void onLoginFailer(String msg) {
mLoginView.onFailer(msg);
mLoginView.hide();
}
});
}
}
/**接口view的实现四个方法/
public interface LoginView {
void onSucess(String result);
void onFailer(String msg);
void show();
void hide();
}
/*进行验证给progress睡眠时间(抛异常)此时会报错,因为子线程不能更新UI添加Handler方法用来更新UI/
public class LoginBiz {
public void login(String name, String password, final LoginCallBack loginCallBack){
new Thread(){
@Override
public void run() {
super.run();
try {
Thread.sleep(2000);
handler.post(new Runnable() {
@Override
public void run() {
String result = “登陆成功”;
loginCallBack.onLoginSuccess(result);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
handler.post(new Runnable() {
@Override
public void run() {
loginCallBack.onLoginFailer(“密码不对”);
}
});
}
}
}.start();
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
}