在实际开发中,我们经常会处理登录的相关逻辑,先上登录界面吧:
我想要做的效果是,输入用户名后监听弹出全删按钮,在键盘上点击下一步可从用户名到密码栏。
以下是界面布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/index_bg"
>
<LinearLayout
android:layout_marginTop="260dp"
android:layout_marginLeft="@dimen/default_margin_50dp"
android:layout_marginRight="@dimen/default_margin_50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/transparent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="@dimen/default_margin_40dp"
>
<ImageView
android:id="@+id/iv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/name_s"
android:layout_centerVertical="true"
/>
<EditText
android:id="@+id/et_username"
android:layout_marginLeft="@dimen/default_margin_40dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:imeOptions="actionNext"
android:nextFocusForward="@+id/et_password"
style="@style/telephone_style"
/>
<ImageView
android:clickable="true"
android:focusable="true"
android:layout_alignParentRight="true"
android:layout_marginRight="@dimen/default_margin_10dp"
android:id="@+id/iv_username_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/clear_search_content_icon"
android:layout_centerVertical="true"
/>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="@color/color_DDDDDD"/>
<RelativeLayout
android:layout_marginTop="@dimen/default_margin_20dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@color/transparent">
<ImageView
android:id="@+id/iv_key"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/key_s"
android:layout_centerVertical="true"
/>
<EditText
android:layout_marginLeft="@dimen/default_margin_40dp"
android:id="@+id/et_password"
style="@style/et_password"
/>
<ImageView
android:clickable="true"
android:focusable="true"
android:id="@+id/iv_password_delete"
style="@style/delete_img_style"/>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="@color/color_DDDDDD"/>
</LinearLayout>
<Button
android:id="@+id/btn_login"
android:layout_marginTop="@dimen/default_margin_60dp"
android:layout_marginLeft="@dimen/default_margin_50dp"
android:layout_marginRight="@dimen/default_margin_50dp"
android:layout_width="match_parent"
android:layout_height="@dimen/default_margin_60dp"
android:textColor="@color/white"
android:textSize="@dimen/default_text_size_20sp"
android:background="@mipmap/denglu"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/ib_setting"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_width="@dimen/default_margin_50dp"
android:layout_height="@dimen/default_margin_50dp"
android:src="@mipmap/setting"
android:scaleType="center"
android:background="#666666"
/>
</RelativeLayout>
</LinearLayout>
以下是登录逻辑代码:
public class LoginActivity extends BaseActivity
implements View.OnClickListener{
private EditText etUserName;
private EditText etPsw;
private ImageView ivUserNameDelete;
private ImageView ivPasswordDelete;
private Button btnLogin;
private ImageButton ibSetting;
/**
* 需要进行检测的权限数组
*//*
protected String[] needPermissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE
};
private static final int PERMISSON_REQUESTCODE = 0;
*//**
* 判断是否需要检测,防止不停的弹框
*//*
private boolean isNeedCheck = true;
@Override
protected void onResume() {
super.onResume();
if(isNeedCheck){
checkPermissions(needPermissions);
}
}
*//**
*
* @param
* @since 2.5.0
* requestPermissions方法是请求某一权限,
*//*
private void checkPermissions(String... permissions) {
List<String> needRequestPermissonList = findDeniedPermissions(permissions);
if (null != needRequestPermissonList
&& needRequestPermissonList.size() > 0) {
ActivityCompat.requestPermissions(this,
needRequestPermissonList.toArray(
new String[needRequestPermissonList.size()]),
PERMISSON_REQUESTCODE);
}
}
*//**
* 获取权限集中需要申请权限的列表
*
* @param permissions
* @return
* @since 2.5.0
* checkSelfPermission方法是在用来判断是否app已经获取到某一个权限
* shouldShowRequestPermissionRationale方法用来判断是否
* 显示申请权限对话框,如果同意了或者不在询问则返回false
*//*
private List<String> findDeniedPermissions(String[] permissions) {
List<String> needRequestPermissonList = new ArrayList<String>();
for (String perm : permissions) {
if (ContextCompat.checkSelfPermission(this,
perm) != PackageManager.PERMISSION_GRANTED) {
needRequestPermissonList.add(perm);
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this, perm)) {
needRequestPermissonList.add(perm);
}
}
}
return needRequestPermissonList;
}
*//**
* 检测是否所有的权限都已经授权
* @param grantResults
* @return
* @since 2.5.0
*
*//*
private boolean verifyPermissions(int[] grantResults) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
*//**
* 申请权限结果的回调方法
*//*
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] paramArrayOfInt) {
if (requestCode == PERMISSON_REQUESTCODE) {
if (!verifyPermissions(paramArrayOfInt)) {
showMissingPermissionDialog();
isNeedCheck = false;
}
}
}
*//**
* 显示提示信息
*
* @since 2.5.0
*
*//*
private void showMissingPermissionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");
builder.setMessage("当前应用缺少必要权限。请点击\"设置\"-\"权限\"-打开所需权限。");
// 拒绝, 退出应用
builder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setPositiveButton("设置",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startAppSettings();
}
});
builder.setCancelable(false);
builder.show();
}
*//**
* 启动应用的设置
*
* @since 2.5.0
*
*//*
private void startAppSettings() {
Intent intent = new Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
this.finish();
return true;
}
return super.onKeyDown(keyCode, event);
}*/
@Override
protected void initAdapter() {
}
@Override
protected void initListener() {
ivUserNameDelete.setOnClickListener(this);
ivPasswordDelete.setOnClickListener(this);
btnLogin.setOnClickListener(this);
ibSetting.setOnClickListener(this);
checkEditText();
etUserName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
checkEditText();
}
@Override
public void afterTextChanged(Editable s) {
}
});
etPsw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
checkEditText();
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
private void checkEditText() {
ivUserNameDelete.setVisibility(TextUtils.isEmpty(etUserName.getText()) ?
View.GONE : View.VISIBLE);
ivPasswordDelete.setVisibility(TextUtils.isEmpty(etPsw.getText()) ?
View.GONE : View.VISIBLE);
}
@Override
protected void updateView() {
}
@Override
protected void initData() {
}
@Override
protected void initView() {
etUserName = findId(R.id.et_username);
etPsw = findId(R.id.et_password);
ivUserNameDelete = findId(R.id.iv_username_delete);
ivPasswordDelete = findId(R.id.iv_password_delete);
btnLogin = findId(R.id.btn_login);
ibSetting = findId(R.id.ib_setting);
}
@Override
public int getLayoutId() {
return R.layout.activity_login;
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
loadingProgress.dismiss();
LoginResponse loginResponse = (LoginResponse) msg.obj;
if(null != loginResponse){
if(loginResponse.getRetCode().equals("0")){
PreferenceUtils.setPrefInt(LoginActivity.this,"userId",loginResponse.getMessage().getUserID());
PreferenceUtils.setPrefString(LoginActivity.this,"nickName",loginResponse.getMessage().getNickName());
PreferenceUtils.setPrefString(LoginActivity.this,"deptName",loginResponse.getMessage().getDeptName());
PreferenceUtils.setPrefInt(LoginActivity.this,"deptId",loginResponse.getMessage().getDeptID());
PreferenceUtils.setPrefInt(LoginActivity.this,"companyId",loginResponse.getMessage().getCompanyID());
PreferenceUtils.setPrefString(LoginActivity.this,"userName",loginResponse.getMessage().getUserName());
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}else{
Toast.makeText(LoginActivity.this,loginResponse.getRetMsg(),Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(LoginActivity.this,Constants.ACCESS_SERVER_FAILED,Toast.LENGTH_SHORT).show();
}
break;
}
}
};
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.iv_username_delete:
etUserName.setText("");
break;
case R.id.iv_password_delete:
etPsw.setText("");
break;
case R.id.btn_login:
if(NetWorkUtils.isConnected(this)){
if(vol()){
loadingProgress.show();
String username = etUserName.getText().toString().trim();
String password = etPsw.getText().toString().trim();
String ip = DeviceIpAddressUtil.getIPAddress(this);
String encrypt = MD5Tools.md5("appid=" + Constants.APP_ID + "ipaddress=" + ip
+"password=" + password +"username="+ username + Constants.KEY)
.toUpperCase();
/*String url = "appid=" + Constants.APP_ID + "&username=" + username
+ "&password=" + password + "&ipaddress=" + ip + "&encrypt=" + encrypt;*/
OkHttpClient okHttpClient = new OkHttpClient
.Builder()
.connectTimeout(3,TimeUnit.SECONDS)
.readTimeout(3,TimeUnit.SECONDS)
.writeTimeout(3,TimeUnit.SECONDS)
.build();
RequestBody requestBody = new FormBody
.Builder()
.add("username",username)
.add("password",password)
.add("ipaddress",ip)
.build();
Request requestPost = new Request.Builder()
.url(Constants.BASE_LOGIN_URL + "appid=" + Constants.APP_ID
+ "&encrypt=" + encrypt)
.post(requestBody)
.build();
okHttpClient.newCall(requestPost).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Utils.runOnUIThread(new Runnable() {
@Override
public void run() {
loadingProgress.dismiss();
Toast.makeText(LoginActivity.this,Constants.CONNECTION_TIMEOUT,Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String s = response.body().string();
Log.e("login",s);
LoginResponse loginResponse = GsonUtils.paserJsonToBean(s,LoginResponse.class);
Message msg = new Message();
msg.obj = loginResponse;
msg.what = 1;
handler.sendMessage(msg);
}
});
/*Request request = new Request
.Builder()
.url(Constants.BASE_LOGIN_URL + url)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Utils.runOnUIThread(new Runnable() {
@Override
public void run() {
loadingProgress.dismiss();
Toast.makeText(LoginActivity.this,Constants.CONNECTION_TIMEOUT,Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String s = response.body().string();
Log.e("login",s);
LoginResponse loginResponse = GsonUtils.paserJsonToBean(s,LoginResponse.class);
Message msg = new Message();
msg.obj = loginResponse;
msg.what = 1;
handler.sendMessage(msg);
}
});*/
}
}else{
Toast.makeText(this,Constants.NETWORK_UNLINKED,Toast.LENGTH_SHORT).show();
}
break;
case R.id.ib_setting:
startActivity(new Intent(this,SettingActivity.class));
break;
}
}
private boolean vol(){
String username = etUserName.getText().toString().trim();
String password = etPsw.getText().toString().trim();
if(TextUtils.isEmpty(username)){
Toast.makeText(this,"请输入用户名!",Toast.LENGTH_SHORT).show();
return false;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"请输入密码!",Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
}