如何将短语分成单词并在每个单词中显示相应的图像?

时间:2018-03-16 04:29:49

标签: android android-studio

我已经尝试过以下代码,但它只读取单词而不是短语,这些代码有效且不符合我的要求。用户输入的每个单词只会添加并添加到空数组列表中。我想要实现的是当用户输入一个短语时,它将按空格分割并存储在空的数组列表中。该数组列表将与另一个包含单词的数组列表进行比较,当条件为真时,它将显示相应的图像,现在将读取该短语中的下一个单词。

 private List<String> wordsList;
private ArrayList<String>wordsToDisplay=new ArrayList<>();
boolean missingGIF;
int counter;

wordsList = new ArrayList(Arrays.asList(getResources()。getStringArray(R.array.sample)));

button.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String input = editText.getText().toString();
            String[]splited = input.split("//s+");
            int count = splited.length;

            for(int i=0;i<count;i++){

                String word = splited[i];

                if(wordsList.contains(word)){
                    wordsToDisplay.add(splited[i]);
                }
                    else
                        missingGIF = true;
            }
        sample();

        }
    });
}

这是示例方法。

if(wordsToDisplay.size()>0){

        counter=0;

        gifImageView.setImageResource(getResources().getIdentifier(wordsToDisplay.get(0),"drawable",getPackageName()));

        animation = (GifDrawable)gifImageView.getDrawable();
        resetAnimation();
        startAnimation();

    animation.addAnimationListener(this);

}

这是我的动画监听器,它在用户输入的所有单词中显示相应的图像。

@Override
public void onAnimationCompleted(int loopNumber) {

    if(wordsToDisplay.size()>1){

        if(counter<wordsToDisplay.size()){


            try{

                counter++;

                gifImageView.setImageResource(getResources().getIdentifier(wordsToDisplay.get(counter),"drawable",getPackageName()));
                animation = (GifDrawable)gifImageView.getDrawable();
                resetAnimation();
                startAnimation();
                animation.addAnimationListener(this);




            }
            catch(IndexOutOfBoundsException e){
                Log.d("Expected",e.toString());
            }


        }
    }

}

1 个答案:

答案 0 :(得分:1)

删除counter并使用以下逻辑

@Override
public void onAnimationCompleted(int loopNumber) {

    if(!wordsToDisplay.isEmpty()){
        String nextWord = wordsToDisplay.remove(0);
        gifImageView.setImageResource(getResources().getIdentifier(nextWord,"drawable",getPackageName()));
        animation = (GifDrawable)gifImageView.getDrawable();
        resetAnimation();
        startAnimation();
        animation.addAnimationListener(this); 
    }
}