安卓简易开发笔记条例
一、将Toast进行封装
package com.example.myapplication2.util;
import android.content.Context;
import android.view.Gravity;
import android.widget.Toast;
public class ToastUtil {
public static Toast toast;
public static void show(Context context,String msg){
if(toast==null){
toast = Toast.makeText(context,msg,Toast.LENGTH_LONG);
}
else{
toast.setText(msg);
}
//设置Toast信息居中显示
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}
}
二、登录界面
1.声明控件
2.找到相关控件
3.Intent 可以使用方法1也可以使用方法2
//声明msg
String empty = "用户名或密码错误不能为空";
String ok = "登录成功";
String fail = "用户名或密码错误,注意区分大小写";
//实现跳转 方法一
mBtnLogin.setOnClickListener(view -> {
String username = mEtUser.getText().toString();
String password = mEtPsw.getText().toString();
/*方法1
Intent in = null;
in = new Intent(MainActivity2.this,FunctionActivity.class);
startActivity(in);*/
//判断输入的用户名和密码是否为空
if(TextUtils.isEmpty(username)|| TextUtils.isEmpty(password)){
//将Toast进行封装
ToastUtil.show(MainActivity2.this,empty);
}
else if (username.equals(new String("admin")) && password.equals(new String("123456"))){
ToastUtil.show(getApplicationContext(),ok);
//方法2
startActivity(new Intent(MainActivity2.this, SlideActivity.class));
}else {
ToastUtil.show(MainActivity2.this,fail);
//普通版:Toast.makeText(getApplicationContext(),"用户名或密码错误,注意区分大小写",Toast.LENGTH_SHORT).show();
//设置Toast信息居中
//Toast.makeText(getApplicationContext(),fail,Toast.LENGTH_SHORT).setGravity(Gravity.CENTER,0,0);
}
});
三、
.RadioGroup和CheckBox都使用选择改变监听器------setOnCheckedChangeListener
1.先声明控件
private RadioGroup rg;
private CheckBox checkBox1;
2.找到相关控件
rg = findViewById(R.id.rg);
checkBox1=findViewById(R.id.cb_1);
3.控件使用方法实现功能
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton radioButton = radioGroup.findViewById(i);
Toast.makeText(StudyActivity.this,radioButton.getText(),Toast.LENGTH_LONG).show();
}
});
checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Toast.makeText(StudyActivity.this,b?"选中":"未选中",Toast.LENGTH_LONG).show();
}
});
使用lamada表达式替代后可以简化代码,将鼠标放在参数的位置 按 Alt+Enter键后替换
rg.setOnCheckedChangeListener((radioGroup, i) -> {
RadioButton radioButton = radioGroup.findViewById(i);
Toast.makeText(StudyActivity.this,radioButton.getText(),Toast.LENGTH_LONG).show();
});
checkBox1.setOnCheckedChangeListener((compoundButton, b) ->
Toast.makeText(StudyActivity.this,b?"选中":"未选中",Toast.LENGTH_LONG).show());