每一个app都不可或缺的需要使用登录页面,下面写一个最简单的登陆页面
简单的布局文件
<LinearLayout
android:layout_marginTop="150dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户名:"
android:textColor="#000"
android:textSize="20sp"
/>
<EditText
android:id="@+id/name_Edit"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="用户名"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密 码:"
android:textColor="#000"
android:textSize="20sp"
/>
<EditText
android:id="@+id/pass_Edit"
android:layout_width="150dp"
android:layout_height="50dp"
android:password="true"
android:text="密码"
/>
</LinearLayout>
<Button
android:id="@+id/btn_login"
android:layout_marginTop="150dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="登录"
/>
其中的有关数据请求的信息,这里使用的是OKHttp的数据请求,首先为按钮添加点击事件,点击按钮进行登录,进行数据的请求,然后在请求的数据中比较返回值为多少一般请求成功为200,所以进行判断,为200则可以将伴随一起的数据信息放到一个公共类中,方便在用到的地方使用。
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name = nameEdit.getText().toString().trim();
pass = passEdit.getText().toString().trim();
new Thread() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", name);
jsonObject.put("password", pass);
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
Request request = new Request.Builder().url(url_login).post(requestBody).build();
try {
Response response = okHttpClient.newCall(request).execute();
final String string = response.body().string();
System.out.println("登录信息"+string);
runOnUiThread(new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
Login_message login_message = gson.fromJson(string, Login_message.class);
int code = login_message.getCode();
if(code == 200){
Toast.makeText(LoginActivity.this, "登陆成功!", Toast.LENGTH_SHORT).show();
String token = login_message.getToken();
Login_token.token = token;
System.out.println("LOgin:+"+Login_token.token);
Login_token.password = pass;
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}else{
Toast.makeText(LoginActivity.this, "用户名不存在或密码错误", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
});