【问题标题】:Can't compare strings in Java Android无法在 Java Android 中比较字符串
【发布时间】:2017-07-12 18:20:47
【问题描述】:

我一直在寻找与我的标题类似的其他问题。但是,这些答案都不起作用。

public void clickedCheck(View view) {

    String input = emojiconTextView.getText().toString();
    String input2 = myRandomImage.getDrawable().toString();

    if (input.equals(input2)) {
        checkingText.setText("Well Done!");
    }
}

但是,文本不会更改为“做得好!”。它保持我输入的默认值。

我将 EmojiconTextView 对象与 ImageView 对象进行比较。如果 2 个图像相等,则应显示“做得好!”。 EmojiconTextView 来自我添加的 Gradle 依赖项和库。

【问题讨论】:

  • 因为myRandomImage.getDrawable() 不会是您在 emojiconTextView 中的内容。它是图像的可绘制对象
  • 打印两个值input & input2,你就会明白为什么不相等了
  • @tyczj - 那么有没有办法做到这一点?
  • 您尝试做的事情毫无意义,您怎么可能将字符串与图像进行比较?
  • @FirozMemon - 会尝试

标签: java android string


【解决方案1】:

这是因为您比较了 TextView 中的文本值并使其成为字符串,以及可绘制对象的文本表示。

在 Drawable 上调用 toString 将返回 drawable 的字符串表示形式,而不是 drawable 名称。所以字符串永远不会相等。

//this is the string value of whatever is in the textview
String input = emojiconTextView.getText().toString();
// this is the text representation of a drawable. not the name of the drawable
String input2 = myRandomImage.getDrawable().toString();

为图片设置标签

<ImageView ...
    android:tag="some tag"
/>

尝试使用myRandomImage.getTag().toString()

【讨论】:

  • 但是现在,如果图像不相等,我该如何让它显示“不幸”?
  • @MSP 只需将 if 语句中的右括号替换为 } else { checkingText.setText("Unlucky"); }
  • @Dewick47 - 我也是这么想的,但我试过了,它仍然显示“做得好!”
  • @MSP 那么你应该调试为什么input 现在总是等于input2。如果您在那之后仍然卡住,请发布一个新问题。
  • @Dewick47 - 现在将尝试调试并等待正确答案的响应。
【解决方案2】:

我认为,如果您尝试获取“可绘制”并使用它的 toString 方法,您可能会得到与预期不同的东西。不确定,也没有尝试过。但根据经验,似乎在“getDrawable”上使用 toString 方法会产生一些奇怪的东西。如果您调试并检查 input2 的值,您就会知道。只是我的 0.02 美分。

【讨论】:

  • 这听起来更像是一条评论。没有答案。
  • 是的,我知道.. 但是你必须有 50 个声望点才能发表评论,显然。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 2022-01-16
  • 1970-01-01
  • 2014-11-11
相关资源
最近更新 更多