这个实在是太简单了,但是也要有始有终。除了认识EditText这个基本组件外,值得一提的就是一个函数:
TextUtils.isEmpty(str);它是用来判断一个字符串为空的很方便的一个函数。
本例子是点击按钮如果EditText中有字符串,则Toast显示出来。如果无字符串则Toast显示“字符串为空!”。
布局文件:edittext_layout.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" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btn_get"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取文本" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
</LinearLayout>
AtyEditText.java文件:
package com.fxj.composit;
import com.fxj.compractice.R;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AtyEditText extends Activity {
private Button btnGet;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edittext_layout);
btnGet = (Button) findViewById(R.id.btn_get);
editText = (EditText) findViewById(R.id.editText1);
btnGet.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 获取EditText中的字符串
String str = editText.getText().toString();
// 如果字符串为空
if (TextUtils.isEmpty(str)) {
Toast.makeText(AtyEditText.this, "字符串为空!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AtyEditText.this, str, Toast.LENGTH_SHORT)
.show();
}
}
});
}
}
运行效果:
结束。