You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将短语拆分为单词并为每个单词显示对应图片?

看起来你遇到的核心问题有两个:一是输入短语的拆分逻辑错误,导致无法正确分割成单个单词;二是现有代码在处理连续显示GIF时存在索引越界风险,且每次点击按钮没有清空历史数据,容易累积旧的匹配结果。下面是针对性的解决方案:

1. 修复输入拆分的正则表达式

你当前用的split("//s+")是错误的——Java中匹配空白字符的正则需要用\\s+(因为\在字符串里必须转义成\\),这个正则会匹配一个或多个空格、制表符等空白字符,完美拆分短语为单个单词:

String[] splited = input.split("\\s+");

2. 每次点击按钮清空历史匹配列表

现在你的代码会不断往wordsToDisplay里追加新单词,不会清空之前的内容,导致重复显示旧GIF。处理输入前先清空列表,并重置缺失标记:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String input = editText.getText().toString().trim();
        if (input.isEmpty()) return; // 空输入直接返回
        
        // 清空历史数据,重置标记
        wordsToDisplay.clear();
        missingGIF = false;
        List<String> missingWords = new ArrayList<>(); // 记录无对应GIF的单词
        
        String[] splited = input.split("\\s+");
        for (String word : splited) {
            if (wordsList.contains(word)) {
                wordsToDisplay.add(word);
            } else {
                missingWords.add(word);
            }
        }
        
        // 提示用户缺失的单词(可选)
        if (!missingWords.isEmpty()) {
            missingGIF = true;
            Toast.makeText(getApplicationContext(), "无对应GIF的单词:" + missingWords, Toast.LENGTH_SHORT).show();
        }
        
        sample();
    }
});

3. 修复动画监听器的索引越界问题

你的动画监听器逻辑会导致最后一次切换时触发索引越界,同时重复添加监听器可能引发多次回调。调整逻辑如下:

@Override
public void onAnimationCompleted(int loopNumber) {
    // 先移除当前监听器,避免重复触发
    animation.removeAnimationListener(this);
    
    counter++;
    if (counter < wordsToDisplay.size()) {
        try {
            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());
        }
    } else {
        // 所有GIF显示完成后的收尾操作,比如清空输入框
        editText.setText("");
        counter = 0; // 重置计数器
    }
}

4. 完善sample()方法的初始化逻辑

在初始化第一个GIF时,记得移除之前的监听器,避免干扰新的动画回调:

public void sample() {
    if (wordsToDisplay.size() > 0) {
        counter = 0;
        // 移除旧监听器
        if (animation != null) {
            animation.removeAnimationListener(this);
        }
        gifImageView.setImageResource(getResources().getIdentifier(wordsToDisplay.get(0), "drawable", getPackageName()));
        animation = (GifDrawable) gifImageView.getDrawable();
        resetAnimation();
        startAnimation();
        animation.addAnimationListener(this);
    }
}

内容的提问来源于stack exchange,提问作者typo_18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:20:44