无法将edittext与图片名称

时间:2016-04-25 00:48:12

标签: java android

通过制作一个简单的猜谜游戏来学习机器人,我已经在Arraylist中设置了图像并在其上应用了随机操作,但是现在我很困惑如何将编辑文本值与图像名称相匹配以便我可以设置得分

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

  }

1 个答案:

答案 0 :(得分: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;
}