2016-04-25 33 views
0

通過製作一個簡單的猜謎遊戲來學習android,我已經在Arraylist中設置圖像並對其應用隨機操作,但現在我很困惑如何將編輯文本值與圖像名稱進行匹配我可以設置分數。無法將圖片名稱與edittext匹配

public class MainActivity extends AppCompatActivity { 
    private EditText editText; 
    private Button button; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ArrayList<Integer> list = new ArrayList<Integer>(); 
     ImageView random_image = (ImageView) findViewById(R.id.imageView); 
     final int[] images = {R.drawable.kung_fu_panda, R.drawable.mr_nobody, R.drawable.toy_story}; 
     list.add(R.drawable.kung_fu_panda); 
     list.add(R.drawable.mr_nobody); 
     list.add(R.drawable.toy_story); 
     int position = new Random().nextInt(list.size()); 
     random_image.setImageResource((Integer) list.get(position)); 
     list.remove(position); 

     button = (Button) findViewById(R.id.button); 
     editText = (EditText) findViewById(R.id.editText); 

     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       validateInput(); 
      } 
     }); 

    } 

    private void validateInput() { 
     String input = editText.getText().toString(); 

    } 

回答

0

您可以嘗試定義名稱的陣列圖像,並通過隨機位置獲取名稱,並使用currentName保存名稱。

String currentName; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    ArrayList<Integer> list = new ArrayList<Integer>(); 
    ImageView random_image = (ImageView) findViewById(R.id.imageView); 
    final String imageNames = {"kung fu panda", "mr nobody", "toy story"}; 
    list.add(R.drawable.kung_fu_panda); 
    list.add(R.drawable.mr_nobody); 
    list.add(R.drawable.toy_story); 
    int position = new Random().nextInt(list.size()); 
    random_image.setImageResource((Integer) list.get(position)); 
    currentName = imageNames[position]; 
    list.remove(position); 

    button = (Button) findViewById(R.id.button); 
    editText = (EditText) findViewById(R.id.editText); 

    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      validateInput(); 
     } 
    }); 

} 

然後,在你validateInput()方法,你可以使用currentName比較,通知的情況下,使用String.toLowerCase()格式輸入字符串。

private boolean validateInput() { 
    String input = editText.getText().toString(); 
    if(!TextUtils.isEmpty(input)){ 
     input = input..toLowerCase(); 
     if(input.equeals(currentName)){ 
      return true; 
     } 
    } 
    return false; 
}