如何在Android Studio中为EditText设置默认值

5

我尝试将一个值放入EditText中,但是我无法实现。

我正在编辑的代码:

<EditText android:textColor="@color/white" android:id="@id/input_username" 
    android:layout_width="wrap_content" android:layout_height="wrap_content" 
    android:layout_marginTop="20.0dip" android:hint="@string/input_username_hint" 
    android:ems="10" android:singleLine="true" android:maxLength="140" 
    android:layout_below="@id/input_room_name" android:layout_centerHorizontal="true" />

当我将android:text="user"放入代码中时,生成的apk文件无法打开。

请解释一下“无法打开”的含义。如果你的意思是应用程序崩溃了,请使用LogCat来检查与崩溃相关的Java堆栈跟踪:https://dev59.com/iGAg5IYBdhLWcg3wpMSz - CommonsWare
2个回答

5

请执行以下操作:

editText.setText("Your default text");

如果你想展示那些在用户开始输入时就消失的灰色文本,你需要使用android:hint属性。

在xml中:

android:hint="Your default text"

关于Java:

editText.setHint("Your default text");

关于Kotlin:

editText.hint = "Your default text"

3
在您的 .xml 文件中,

指定

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="user" />

或者
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="user" />

如果您想在程序中实现这一点,请执行以下操作:
执行此操作
EditText et = (EditText)findViewById(R.id.your_edittext_id);
et.setText("user");

或者

et.setHint("user");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接