EditText : 输入框
<EditText/> 继承了 TextView
案例功能:EditText的使用及 点击按钮 ,获取用户名 打印到控制台
step1 drawable 里添加两张图片
ic_person_black_24dp.xml
ic_phone_iphone_black_24dp.xml
step2 activity_main.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:hint="请输入用户名"
android:id="@+id/username"
android:textColorHint="@color/grey"
android:inputType="text"
android:drawableLeft="@drawable/ic_person_black_24dp"
android:drawablePadding="10dp"
android:paddingLeft="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:hint="请输入手机号"
android:textColorHint="@color/grey"
android:inputType="phone"
android:drawableLeft="@drawable/ic_phone_iphone_black_24dp"
android:drawablePadding="20dp"
android:padding="50dp"
android:background="@color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn"
android:text="获取用户名"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
step3 MainActivity.java
package com.example.myedittext;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn);
username = findViewById(R.id.username);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = username.getText().toString();
Log.e("cs","输入的内容:"+text);
}
});
}
}
结果