IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android学习笔记(二):实现登录 -> 正文阅读

[移动开发]Android学习笔记(二):实现登录

一、页面

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<!--线性布局-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/background_2">

    <!--按钮控件,定义了其中的属性-->

    <View
        android:layout_width="match_parent"
        android:layout_height="150dp">

    </View>

    <!-- 登录控件 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="210dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="70dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:gravity="center"
                android:layout_marginStart="120dp"
                android:textSize="25dp"
                android:layout_marginTop="10dp"
                android:text="用户名:">

            </TextView>

            <EditText
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="20dp"
                android:layout_marginRight="30dp"
                android:textColor="#ff000000"
                android:maxLength="13"
                android:textSize="20sp">

            </EditText>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="70dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:gravity="center"
                android:layout_marginStart="120dp"
                android:textSize="25dp"
                android:layout_marginTop="10dp"
                android:text="密    码:">

            </TextView>

            <EditText
                android:id="@+id/pwd"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="20dp"
                android:layout_marginRight="30dp"
                android:textColor="#ff000000"
                android:maxLength="13"
                android:inputType="textPassword"
                android:textSize="20sp">

            </EditText>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/login"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginStart="250dp"
                android:switchMinWidth="60dp"
                android:background="@drawable/login_button"
                android:textColor="#ff000000"
                android:layout_marginTop="20dp"
                android:width="100dp"
                android:textSize="22dp"
                android:text="登录">

            </Button>

        </LinearLayout>

    </LinearLayout>
</LinearLayout>

res/drawable 里的背景
在这里插入图片描述

二、逻辑代码

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zilong.demo1.web.RestApi;
import com.zilong.demo1.web.result.RestResponse;

public class MainActivity extends Activity {

    private Button next = null;
    private EditText username = null;
    private EditText pwd = null;

    protected void onCreate(Bundle savedInstanceState){
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//该方法指定activity与layout文件的对应关系

        next = (Button) findViewById(R.id.login);//通过id查找已经定义好的控件
        next.setOnClickListener(new OnClickListener() {//绑定监听事件,内容为点击该控件跳转到另一个activity,不传参
            @Override
            public void onClick(View v) {
                username = (EditText) findViewById(R.id.username);
                pwd = (EditText) findViewById(R.id.pwd);
                RestResponse res = RestApi.login(username.getText().toString(), pwd.getText().toString());
                if (res.getCode().equals(200)) {
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this,FirstActivity.class);
                    startActivity(intent);
                }
                else {
                    Toast toast = Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        });
    }

}
import com.alibaba.fastjson.JSONObject;
import com.zilong.demo1.web.result.RestResponse;

import static com.zilong.demo1.constant.ApiConstant.BASE_URL;

public class RestApi {

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    public static RestResponse login(String username, String password) {
        JSONObject json = new JSONObject();
        json.put("username", username);
        json.put("password", password);
        return RestUtils.post(BASE_URL + "/login/test", String.valueOf(json));
    }
}
import okhttp3.MediaType;

public class ApiConstant {
    /**
     * 状态码
     */
    public static final Integer SC_OK_200 = 200;
    public static final Integer SC_INTERNAL_SERVER_ERROR_500 = 500;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * base url
     */
    public static final String BASE_URL = "http://127.0.0.1:8080/api";
}
import com.alibaba.fastjson.JSONObject;
import com.zilong.demo1.web.result.RestResponse;

import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import static com.zilong.demo1.constant.ApiConstant.JSON;

public class RestUtils {
    /**
     * get
     *
     * @param url
     * @param params
     * @param token
     * @return
     */
    public static RestResponse get(String url, Map<String, String> params, String token) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                .newBuilder();
        params.forEach((k, v) -> urlBuilder.addQueryParameter(k, v));
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(urlBuilder.build())
                .get()
                .build();
        try {
            ResponseBody responseBody = RequestExecutor.execute(request);
            System.out.println(responseBody.string());
            return null;
        } catch (Exception e) {
            return RestResponse.error(e.getMessage());
        }
    }

    /**
     * post
     *
     * @param url
     * @param body
     * @return
     */
    public static RestResponse post(String url, String body) {
        Request.Builder builder = new Request.Builder()
                .url(url)
                .post(RequestBody.create(JSON, body));
        Request request = builder.build();
        System.out.println("request: " + request);
        try {
            ResponseBody responseBody = RequestExecutor.execute(request);
            return JSONObject.parseObject(responseBody.string(), RestResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.error(e.getMessage());
        }
    }

    public static RestResponse put(String token) {
        Request request = new Request.Builder().addHeader("token",token).build();
        return null;
    }

    public static RestResponse delete(String token) {
        Request request = new Request.Builder().addHeader("token",token).build();
        return null;
    }
}
import com.zilong.demo1.exception.RequestException;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;

/**
 * 请求执行器
 */
public class RequestExecutor {

    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(2, TimeUnit.MINUTES)
            .readTimeout(2, TimeUnit.MINUTES)
            .build();

    public static ResponseBody execute(Request request) throws RequestException {
        try {
            return okHttpClient.newCall(request).execute().body();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestException("请稍后尝试");
        }
    }
}

三、依赖

    implementation "com.squareup.okhttp3:okhttp:3.12.2"
    implementation "org.projectlombok:lombok:1.18.16"
    implementation "com.alibaba:fastjson:1.2.72"

四、配置文件

manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zilong.demo1">

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Demo1">
        <uses-library android:name="org.apache.http.legacy" android:required="false"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".FirstActivity">

        </activity>
    </application>

</manifest>

res/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

五、效果

在这里插入图片描述
在这里插入图片描述

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-07-13 17:34:48  更:2021-07-13 17:36:02 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/28 8:19:03-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码