Android:如何使用随机抽取的SetTag()?

时间:2014-12-13 04:50:25

标签: java android random

我还是新手,所以我希望我能在这里得到一些帮助。 所以这里我有两张图片/ drawable随机。 我可以随机拍照,但我想根据出现的图片播放匹配声音。

这是我进行随机化的方式:

apple.setBackgroundResource(imgDeck[random.nextInt(imgDeck.length)]);
apple.setTag(R.drawable.image_a);

问题:我想将setTag的参数更改为我之前做过的随机化R.drawable.*(在setbcakground资源中)。

以下是fragment_a.java的完整代码。

public class fragment_a extends Fragment implements OnClickListener {

ImageButton a, apple;
MediaPlayer sound;

// Random object
private final static Random random = new Random();

// Tampung Image
private final static int[] imgDeck = new int[] { 
    R.drawable.image_a,
    R.drawable.image_b };

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_a, container, false);

    // Inflate the layout for this fragment
    a = (ImageButton) v.findViewById(R.id.imageButton_a);
    a.setOnClickListener(fragment_a.this);

    apple = (ImageButton) v.findViewById(R.id.imageButton_apple);
    apple.setOnClickListener(fragment_a.this);

    return v;
}

@Override
public void onClick(View view) {
    // TODO Auto-generated method stub

    if (view == getView().findViewById(R.id.imageButton_a)) {

        apple.setBackgroundResource(imgDeck[random.nextInt(imgDeck.length)]);
        apple.setTag(R.drawable.image_a);

        a.setVisibility(view.INVISIBLE);
        apple.setVisibility(view.VISIBLE);

        if (apple.getTag().equals(R.drawable.image_a)) {

            sound = MediaPlayer.create(getActivity().getBaseContext(),
                    R.raw.sound_apple);
            sound.setVolume(5, 5);
            sound.start();
        } else if (apple.getTag().equals(R.drawable.image_b)) {
            sound = MediaPlayer.create(getActivity().getBaseContext(),
                    R.raw.sound_banana);
            sound.setVolume(5, 5);
            sound.start();
        }

    } else if (view == getView().findViewById(R.id.imageButton_apple)) {

        a.setVisibility(view.VISIBLE);
        apple.setVisibility(view.INVISIBLE);
        sound = MediaPlayer.create(getActivity().getBaseContext(),
                R.raw.sound_a);
        sound.setVolume(5, 5);
        sound.start();
    } else {
        a.setVisibility(view.VISIBLE);
        apple.setVisibility(view.INVISIBLE);
        sound = MediaPlayer.create(getActivity().getBaseContext(),
                R.raw.sound_apple);
        sound.setVolume(5, 5);
        sound.start();
    }

}

}

0 个答案:

没有答案