0

我有一个停止录制的按钮,当它被点击时,它当前会弹出一个 toast 通知。我在想,如果我可以有多个 toast 消息并且系统会随机选择(并显示)其中一个 toast,这样用户每次完成录制时都不会收到相同的消息,那会更酷一些。我不知道这是否真的可能,我只是好奇。

我的 onClick() 代码:

stopButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            /*startButton.setEnabled(true);
            stopButton.setEnabled(false); */
            recorder.stop();
            recorder.release();
            addRecordingToMediaLibrary();
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            Toast.makeText(getApplicationContext(), "Awesome Recording!", Toast.LENGTH_LONG).show();
        }
    });
}
4

2 回答 2

1

编辑 2

我的错误,该new Random().nextInt(...)行多次返回相同的整数,因为 Java 中的随机数生成器实际上是伪随机的;它使用种子生成随机值并在Random每次重置种子时创建一个新对象,从而导致重复整数。尝试将此字段添加到您的匿名OnClickListener

private static final Random random = new Random();

和改变

new Random().nextInt(toastMessages.length - 1);

random.nextInt(toastMessages.length - 1);

所以你最终得到以下结果:

stopButton.setOnClickListener(new OnClickListener() {
    private static final Random random = new Random();

    @Override
    public void onClick(View v) {
        recorder.stop();
        recorder.release();
        addRecordingToMediaLibrary();
        startButton.setEnabled(true);
        stopButton.setEnabled(false);

        String[] toastMessages = new String[] {"Great!", "Awesome!", "..."};
        int randomMsgIndex = random.nextInt(toastMessages.length - 1);
        Toast.makeText(getApplicationContext(), toastMessages[randomMsgIndex], Toast.LENGTH_LONG).show();
    }
});

此解决方案并非特定于 Android,但您可以使用一组预定义消息(最好从 加载这些消息strings.xml):

String[] toastMessages = new String[] {"Great!", "Awesome!", "..."};

然后从该数组中随机选择一个索引:

new Random().nextInt(toastMessages.length - 1);

为你带来:

String[] toastMessages = new String[] {"Great!", "Awesome!", "..."};

// Get an index between 0 and the last index in the messages array 
int randomMsgIndex = new Random().nextInt(toastMessages.length - 1);

Toast.makeText(getApplicationContext(), toastMessages[randomMsgIndex], Toast.LENGTH_LONG).show()

编辑:Eclipse 应该为你处理这个,但只是为了确保:

import java.util.Random;
于 2013-08-18T03:42:14.727 回答
0

当然这是可能的。如果要显示一定数量的消息,我能想到的最简单的方法是简单地创建一个String Array保存不同消息的方法。然后onClick()只需使用随机数生成器从Array.

所以喜欢

Random randomNumber = new Random();
int number = randomNumber.nextInt(5); // where 5 is the number of Strings minus 1
Toast.makeText(YourActivityName.this, YourStringArray[number], Toast.LENGTH_LONG).show();
于 2013-08-18T03:43:21.133 回答