首先,创建一个util,在ToastUtil里面调用方法
在里面编写Toast类的代码,方便以后调用
package com.example.appdemo.util;
import android.content.Context;
import android.widget.Toast;
public class ToastUtil {
public static Toast mToast;
public static void showMsg(Context context,String msg){ //其他地方调用这个showMsg方法就行了
if(mToast == null){
mToast = Toast.makeText(context,msg,Toast.LENGTH_LONG);
}else {
mToast.setText(msg);
}
mToast.show();
}
}
其次,
如此调用方法
ToastUtil.showMsg(getApplicationContext(),"文本文字");
最后、放一下全部代码
package com.example.appdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.appdemo.util.ToastUtil;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
//1.声明控件
private Button mBtnLogin; //mBynLogin 是关键字,可以换
private EditText mEtUser;
private EditText mEtPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//2.找到控件
mBtnLogin = findViewById(R.id.btn_longin); //将前面声明的关键字,根据按钮的唯一标识id
mEtUser = findViewById(R.id.et_1);
mEtPassword = findViewById(R.id.et_2);
mBtnLogin.setOnClickListener(this);
}
//实现密码操作正确,才能实现跳转
public void onClick(View v){
//需要用户输入的用户名和密码
String username = mEtUser.getText().toString();
String password = mEtPassword.getText().toString();
String success = "登录成功";
String fail = "登录失败";
Intent intent = null;
//假设正确的账号和密码分别是YZX 123456
if(username.equals("root")&& password.equals("123456")){
//如果正确的话,则进行跳转
//封装好的类
ToastUtil.showMsg(getApplicationContext(),success);
intent = new Intent(MainActivity.this,FunctionActivity.class);
startActivity(intent);
}else{
//不正确,弹出登录失败toast
ToastUtil.showMsg(getApplicationContext(),fail);
}
}
}
标签:Toast,String,public,ToastUtil,Studio,import,Android,android
From: https://www.cnblogs.com/yzx-sir/p/17406612.html