【问题标题】:Detecting if EditText contains only a decimal point检测 EditText 是否仅包含小数点
【发布时间】:2014-01-02 17:43:58
【问题描述】:
<EditText
    android:id="@+id/edtxt1"
    android:layout_below="@+id/txt1"
    android:layout_width="fill_parent"
    android:gravity="center_horizontal"
    android:maxLength="15"
    android:textColor="#ffffff"
    android:paddingTop="10dp"
    android:layout_marginLeft="30dp"
    android:background="@drawable/edittxt"
    android:inputType="numberDecimal"
    android:layout_centerInParent="true"
    android:layout_height="50dp" />

我有一个单位转换器应用程序。一切正常,但我遇到的唯一问题是,如果用户在 EditText 中仅输入小数点 "." 并尝试将一个参数转换为另一个参数,则应用程序崩溃!

我如何检测是否只输入了小数点(即没有数字;例如输入了"." 而不是"3.03"".3")。

当用户尝试从一个参数转换为另一个参数时,我使用下面的代码检测 EditText 是否为空,但它不适用于小数点。

if (cel1.matches(""))
{
    Toast.makeText(getApplicationContext(), "Enter the content!",
                                                         Toast.LENGTH_LONG).show();
}

【问题讨论】:

  • if (cel1.equals("") || cel1.equals(".")) ?
  • 请看看我的回答,给我一些你想要的反馈。如果它适合你,请接受它。

标签: java android android-edittext


【解决方案1】:

检查只是一个小数点:

EditText et = (EditText)findViewById(R.id.edtxt1);
if (et.getText().toString().equals("."))
{
    // run your code here
}

使用您的代码:

if (cel1.equals("") || cel1.equals("."))
{
    Toast.makeText(getApplicationContext(), "Enter the content!",
                                                       Toast.LENGTH_LONG).show();
}

也许您想将cel1.equals(".") 更改为cel1.trim().equals(".") 只是为了确保条件有效,即使其中也有空格。不过,我不确定您是否首先允许空格。

【讨论】:

  • @AshwinShirva 我马上就做到了。我是第一个哈哈。
【解决方案2】:

您可以检查 EditText 中是否只有小数点:

//从EditText中获取文本并检查是否为点。

if (editText.getText().toString().equals("."))
{
    //display error message
}

【讨论】:

  • 这甚至无法编译。
  • 为什么不能编译?
  • 您需要将 if 条件用引号括起来。 if editText.getText().toString().equals(".") 需要是 if (editText.getText().toString().equals("."))。我建议在发布代码之前在 Android/Java 中创建一个“TestCode”工作区来试用代码。
  • 啊,你是对的,这只是一种习惯,哈哈
【解决方案3】:

你可以检查一下:

正如你询问without the numbers,like "." is entered instead of "3.03" or ".3"

EditText edittext1=(EditText)findViewById(R.id.edtxt1)
String cel1= edittext1.getText().toString();

if (cel1.trim().length()!=0 && cel1.startsWith("[.]");)
{
    Toast.makeText(getApplicationContext(), "Wrong content here, please Try again!!",
                                                         Toast.LENGTH_LONG).show();
}

【讨论】:

  • 他的意思是只输入一个小数,不是一个小数和一个数字。所以你的代码对他不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
相关资源
最近更新 更多