0

所以我是一个完全的新手,目前正在学习我们使用 Android 的移动编程课程的介绍(我有一些 Java 经验)。我正在尝试做一个显示文本字段和图像的简单分配,输入正确的“密码”并按 Enter 后,图像会发生变化。

应该这么简单!但是我很难解决这个问题并且无法弄清楚我做错了什么,即使在做了很多搜索之后(我认为这是非常明显的事情,我错过了它)。

这是我的代码:

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”中提取字符串,因此与“password”的比较没有正确发生,但我已经尝试只打印enteredText,它工作正常。

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

丹尼尔

4

1 回答 1

1

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

作为文体问题,您不应该在 switch image 函数中进行检查 - 您应该检查密码是否匹配,然后调用 switch image 函数。

于 2010-10-10T23:28:26.300 回答