So I am a complete newb, and am currently taking an intro to Mobile Programming course in which we use Android (I have some experience with Java). I am trying to do a simple assignment which displays a text field and an image, and upon entering the correct "password" and pressing enter, the image changes.
Should be so simple! But I am having a really hard time with this and can't figure out what I am doing wrong, even after doing a good bit of searching (I assume it is something super obvious and I'm missing it).
Here is my code:
package CS285.Assignment1;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ImageView;
public class DisplayImage extends Activity
implements OnKeyListener{
private EditText enteredText;
private String pass = "monkey";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
enteredText = (EditText)findViewById(R.id.passField);
enteredText.setOnKeyListener(this);
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
// Perform action on key press
switchImage();
return true;
}
return false;
}
public void switchImage(){
if(enteredText.getText().toString() == pass){
ImageView imgView = (ImageView)findViewById(R.id.Image);
imgView.setImageResource(R.drawable.marmoset);
}
}
}
and my main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/textPrompt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff993300"
android:text="Please enter password to see my real picture:"
>
</TextView>
<EditText android:id="@+id/passField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</EditText>
<ImageView
android:id="@+id/Image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:src="@drawable/airplane"
/>
</LinearLayout>
I thought at first that I was not properly extracting the String from "enteredText" so the comparison to the "password" wasn't happening correctly, but I have since tried just printing the enteredText and it works fine.
Totally frustrated--Any help would be greatly appreciated!
Daniel