在Android里面判断输入框EditText是否为空
方法一:通过方法TextUtils.isEmpty(s)进行判断,参数s是获取到输入框的内容
方法二:通过方法str.equals(""),str是获取到的输入框的内容
通过下面一段代码对这两种方法简单测试一下
public class MainActivity extends AppCompatActivity { EditText edit; Button btn1,btn2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edit = (EditText) findViewById(R.id.edit); btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String s = edit.getText().toString().trim(); if(TextUtils.isEmpty(s)){ Toast.makeText(getApplicationContext(), "方法一:输入框为空",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getApplicationContext(), "输入框不为空",Toast.LENGTH_LONG).show(); } } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String s = edit.getText().toString().trim(); if(s.equals("")){ Toast.makeText(getApplicationContext(), "方法二:输入框为空",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getApplicationContext(), "输入框不为空",Toast.LENGTH_LONG).show(); } } }); } }
效果图: