3

嗨,我在编程方面有点菜鸟,但我想创建一个 IF 语句,无论 textview 是否(我已经引用过)在它的侧面包含一个字母,并且只有那个字母,例如我想改变任何带有“1”的文本视图是什么代码?这就是我所拥有的,有人可以帮我完成吗?

if ("!".contains(stuff.getText()) {
    stuff.setText("Incorrect Symbol");
}else {

}

我知道我可以使用键盘来控制可以输入的内容,但我希望有人能告诉我如何这样做。顺便说一句,我一直在 stuff.gettext 上画一条红线,所以有人可以告诉我问题吗?

4

5 回答 5

4

我认为这里有两个主要问题:

  • 你对语法有点困惑
  • Android 经常将 CharSequence 用于其文本值,而不是 String,因此它使其更复杂一些。

假设“stuff”是您的 TextView,您可以执行以下操作:

String stuffText = stuff.getText().toString();
if(stuffText.contains("1")) {
    stuff.setText("Incorrect Symbol");
} else {

}

我不确定为什么在 stuff.getText() 上出现红线,但该行应该有相应的编译器错误,您可以在适当的视图中检查(假设您在 Eclipse 之类的 IDE 中)。

至于整体设计,这是一条糟糕的路。您可以通过设置 XML 来指定字段接受的字符:

<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="phone|numberSigned"
    android:digits="0123456789" />

如果您真的想获得反馈,您可能需要使用TextWatcher,这样您就可以在用户输入时做出响应。

于 2013-02-13T17:12:42.493 回答
1

使用String.contains("yourCharacter")检查字符串中是否存在 yourCharacter。

所以,你的代码看起来像

if (stuff.getText().contains("!")) {
    stuff.setText("Incorrect Symbol"); // your text contains the symbol
}else {
    ..... // your text does not contain the symbol
}
于 2013-02-13T17:05:09.753 回答
1

如果你想看看它是否只有一个“1”——也就是说,所有输入的都是一个“1”——那么你会想使用一个equals,而不是一个包含。

假设stuff.getText()返回输入的文本:

if("1".equals(stuff.getText())) {
    // we'll end up here if the only thing in the input is 1
} else {
    // otherwise we'll end up here
}

对于字母,您需要使用equalsIgnoreCase不区分大小写的比较。

如果您想检查输入是否包含字符,您将使用该contains方法而不是 equals:

if(stuff.getText().contains("1")) {
    // we end up here if the input text contains 1 somewhere in it
} else {
    // otherwise we'll end up here
}
于 2013-02-13T17:05:30.373 回答
1
if(stuff.gettext().toString().contains("!") {
    stuff.setText("Incorrect Symbol");
} else {

}
于 2013-02-13T17:07:19.773 回答
1

你可以做:

if (stuff.getText().contains("!"))

或者

if(stuff.getText().indexOf("!") != -1)

如果给定的字符不在字符串中,因为indexOf将返回。-1

如上所述,indexOf将单个字符作为参数,因此如果要查看字符串是否包含某个子字符串,请使用contains.

文档

返回: 此对象表示的字符序列中字符第一次出现的索引,如果字符没有出现,则返回 -1。

于 2013-02-13T17:08:41.070 回答