EditText
EditText是可输入控件,同样继承自TextView,可以使用期所有属性和事件
🌲通过本例子,我们将制作一个简单的登录界面:
🚩步骤
我们先用模板新建一个EmptyActivity名为EditTextActivity用于存放登陆界面相关的功能及样式:
我们想要实现以下控件:
- 一个用户名输入框
- 一个密码输入框
- 一个登录按钮
🔨使用到的属性:
| 名称 | 解释 | 格式 |
|---|---|---|
| android:hint | 不输入时的提示信息 | 字符串 |
| android:inputType | 输入文本格式 | number/textPassword/tex…t |
| android:drawableLeft | 在控件内部左侧放置资源 | @drawable/XXX |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EditTextActivity"
android:padding="15dp"
>
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textColor="#FFAD33"
android:hint="请输入手机号"
android:inputType="number"
android:background="@drawable/round_edit_text"
android:drawableLeft="@drawable/icon_user32"
android:drawablePadding="10dp"
android:padding="10dp"
android:layout_marginTop="50dp"
android:maxLines="1"
/>
<EditText
android:id="@+id/et_passwword"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textColor="#FFAD33"
android:hint="请输入密码"
android:layout_below="@id/et_username"
android:layout_marginTop="15dp"
android:inputType="textPassword"
android:background="@drawable/round_edit_text2"
android:drawableLeft="@drawable/icon_password32"
android:drawablePadding="10dp"
android:padding="10dp"
android:maxLines="1"
/>
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="登录"
android:layout_below="@id/et_passwword"
android:layout_marginTop="30dp"
android:textSize="20sp"
android:background="@drawable/touch_bg_btn"
/>
</RelativeLayout>
在这里,我们参照Button篇,引用和创建了一些自定义的样式
EditTextAcitivity的功能由绑定的java代码实现:
登录按钮同样经历 声明控件->寻址控件位置->绑定点击Onlick事件监听,用户点击按钮后显示
“登录中”消息框;
监听文字改变并在logcat输出查看
参考登录按钮,我们为用户名输入框et_username绑定TextChanged事件监听,在其中使用
Log.d方法将用户输入的用户名实时输出来。
public class EditTextActivity extends AppCompatActivity {
private Button mBtnLogin;
private EditText mEtUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_text);
mBtnLogin = findViewById(R.id.btn_login);
mEtUsername = findViewById(R.id.et_username);
mBtnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(EditTextActivity.this, "登陆中!", Toast.LENGTH_SHORT).show();
}
});
//添加监听
mEtUsername.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//改变前
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//改变中
Log.d("edittext", s.toString());
}
@Override
public void afterTextChanged(Editable s) {
//改变后
}
});
}
}
运行效果:

LogCat监听:

693




被折叠的 条评论
为什么被折叠?



