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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23699723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:21:53  来源:igfitidea点击:

How do I set a placeholder on Edittext in Android and use it if no input has been typed by user?

androidandroid-edittextplaceholder

提问by Vanquiza

I would like to have an EditText in android where I have a placeholder, which will be used AS my input if the user types nothing. The edit text is used in a prompt in my case.

我想在 android 中有一个 EditText,我有一个占位符,如果用户没有输入任何内容,它将用作我的输入。在我的情况下,在提示中使用了编辑文本。

I am aware of "hint" excisting, which is a placeholder, but it doesn't use it as an input. If I have hint set to "AAA" and the user types nothing and presses "OK" I will get an empty string, not "AAA".

我知道“提示” excisting,这是一个占位符,但它不将其用作输入。如果我将提示设置为“AAA”并且用户不输入任何内容并按“OK”,我将得到一个空字符串,而不是“AAA”。

Here's my code:

这是我的代码:

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>

回答by CommonsWare

Add this static method somewhere:

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

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

Then use that method to retrieve your value, which will return the text if it exists, or the hint if it does not.

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

回答by Nicholas Pickering

Add android:hint="Hint Text"to the EditTextdeclaration.

添加android:hint="Hint Text"EditText声明中。

回答by zgc7009

Just create a string variable and check conditionally to see what it should be.

只需创建一个字符串变量并有条件地检查它应该是什么。

String text = (input.getText().toString().equals("")? "AAA": input.getText().toString();
ddEvent(levelSelected, text, Integer.parseInt(points), time + "s");

As a note, in case you aren't up on your ternary formatting the first line is the same as the following (in it's most simple form)

请注意,如果您不了解三元格式,则第一行与以下内容相同(以最简单的形式)

String text = "";
if(input.getText().toString().equals(""){
    text = "AAA";
}
else{
    text = input.getText().toString();
}