Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code for Identifying a Single letter?

Tags:

java

android

Hi there I am a bit of a noob at programming but I want to create an IF statement , whether or not a textview , (which i have already referenced) contains a letter in side of it and only that letter for example I want to change any textview which has a "1" in it whats the code? this is what I have got can some one please help me complete it?

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

}

I know that I can use the keyboard to control what can be entered but I would prefer that someone would tell me how to do it this way. By the way I keep on get a little red line over stuff.gettext so can some one please tell me the problem?

like image 307
vhkjgck Avatar asked Jul 17 '26 14:07

vhkjgck


2 Answers

I think there are two main issues here:

  • You are a little confused with the syntax
  • Android often uses CharSequence for its text values, rather than String, so it makes it a bit more complicated.

Assuming "stuff" is your TextView, you can do the following:

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

}

I'm not sure why you are getting the red line on stuff.getText(), but that line should have a corresponding compiler error that you can check in the appropriate view (assuming you're in an IDE like Eclipse).

And as for overall design, this is a bad way to go. You can specify what characters the field accepts by setting up the 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" />

If you really want to have the feedback, you may want to use TextWatcher, so you can respond as the user types.

like image 90
tdn120 Avatar answered Jul 20 '26 04:07

tdn120


Use String.contains("yourCharacter") to check if yourCharacter is present in the String or not.

So, your code will look like

if (stuff.getText().contains("!")) {
    stuff.setText("Incorrect Symbol"); // your text contains the symbol
}else {
    ..... // your text does not contain the symbol
}
like image 30
Swayam Avatar answered Jul 20 '26 04:07

Swayam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!