[英]Why EditText.getText shows null in Android?
我对 EditText 有一个非常奇怪的问题。 我在我的应用程序中使用编辑文本创建了一个表单,我将它们的内容转换为字符串值,但它是空的并且什么也不显示。
XML 代码:
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:id="@+id/name"
style="@style/Edittext_form1"
android:inputType="text"
android:hint="@string/name"/>
java 代码:
private EditText _name;
public static String name;
_name = (EditText) findViewById(R.id.name);
name = _name.getText().toString().trim();
Toast.makeText(getApplicationContext(),name,Toast.LENGTH_LONG).show();;
您的问题是在设置之前获取该资源的内容。
将此行添加到您的 Edittext 标签:
android:text="some default text"
拿一个 EditText、Button 和 TextView 试试这个:
主要活动:
btnName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvName.setText(etName.getText().toString());
}
});
activity_main3
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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=".extras.MainActivity">
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
app:layout_constraintTop_toTopOf="parent"
android:hint="Please enter your name"
/>
<Button
android:id="@+id/btn_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Click Here"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/et_name" />
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
app:layout_constraintTop_toBottomOf="@id/btn_name"
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.