gpt4 book ai didi

android - 如何在 Android 中的 Edittext 上设置占位符并在用户未输入任何输入时使用它?

转载 作者:太空狗 更新时间:2023-10-29 15:31:14 24 4
gpt4 key购买 nike

我想在 android 中有一个 EditText,其中我有一个占位符,如果用户什么都不输入,它将用作我的输入。在我的案例中,编辑文本用于提示。

我知道“提示”existing,它是一个占位符,但它不会将其用作输入。如果我将提示设置为“AAA”并且用户什么都不输入并按“确定”,我将得到一个空字符串,而不是“AAA”。

这是我的代码:

private void promptForUsername(){
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(context);

View promptView = layoutInflater.inflate(R.layout.prompts, null);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

// set prompts.xml to be the layout file of the alertdialog builder
alertDialogBuilder.setView(promptView);

final EditText input = (EditText) promptView.findViewById(R.id.userInput);


//setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
addEvent(levelSelected, input.getText().toString(), Integer.parseInt(points), time + "s");
sqlLogic();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
sqlLogic();
dialog.cancel();
}

});
// create an alert dialog
AlertDialog alertD = alertDialogBuilder.create();
alertD.show();

input.setFocusableInTouchMode(true);
input.requestFocusFromTouch();

InputMethodManager lManager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
lManager.showSoftInput(input, 0);

}

version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type username:"
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/userInput"
android:layout_width="match_parent"
android:inputType="text"
android:layout_height="wrap_content"
android:maxLength="13"
android:hint="AAA">

<requestFocus />
</EditText>
</LinearLayout>

最佳答案

在某处添加这个静态方法:

static CharSequence getTextOrHint(TextView tv) {
return(TextUtils.isEmpty(getText()) ? getHint() : getText());
}

然后使用该方法检索您的值,如果存在则返回文本,如果不存在则返回提示。

关于android - 如何在 Android 中的 Edittext 上设置占位符并在用户未输入任何输入时使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23699723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com