正确密码更改图像

问题描述:

所以我是一个完整的newb,目前正在介绍我们使用Android的移动编程课程(我有一些Java经验)。我正在尝试做一个显示文本字段和图像的简单分配,并在输入正确的“密码”并按下回车键后,图像会改变。正确密码更改图像

应该这么简单!但是我在这方面遇到了很多困难,即使在做了一些搜索之后,我也无法弄清楚自己做错了什么(我认为这是非常明显的东西,我错过了它)。

这里是我的代码:

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); 
    }  
    } 

} 

和我的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> 

我原先以为我是不正确的“enteredText”提取字符串,因此相较于“密码”没有正确地发生,但我从那以后只是试图打印输入的文本,它工作正常。

完全沮丧 - 任何帮助将不胜感激!

丹尼尔

if(enteredText.getText().toString() == pass)应该if(enteredText.getText().toString().equals(pass))

作为一种风格问题,您不应该在切换图像功能中进行检查 - 您应该检查密码是否匹配,然后,然后调用切换图像功能。

+0

非常感谢,I82Much!我希望有一天我能够支付给另一个任性的程序员......! – malfunction 2010-10-11 02:24:38

+0

如果这对你有效,请按答案左边的复选框:) – I82Much 2010-10-11 02:26:18

+0

完成。我是否碰到了2500? – malfunction 2010-10-11 02:35:45