如何在此段代码中添加其他按钮?

时间:2015-03-11 14:13:46

标签: android button soundpool

我在这个.java文件中添加了一个名为buttonA的按钮,播放声音文件'clubb1'。如何添加其他按钮,如buttonB和buttonC等,并将这些按钮链接到此代码中的“clubb2”和“clubb3”等新声音文件?我是新编码,因此不知道如何添加更多?

public class FragmentOne extends Fragment  {

    SoundPool Clubb1;
    int clubb1Id;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Clubb1 = new SoundPool(10, AudioManager.STREAM_MUSIC, 1);
        clubb1Id = Clubb1.load(getActivity(), R.raw.clubb1, 1);            

        View rootView = inflater.inflate(R.layout.fragment_one_layout, container, false);

        Button buttonA = (Button) rootView.findViewById(R.id.buttonA);

        buttonA.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Clubb1.play(clubb1Id, 1, 1, 1, 0, 1);
            }
        });

        return rootView;
    }
}

2 个答案:

答案 0 :(得分:0)

试试这个

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    Clubb1 = new SoundPool(10, AudioManager.STREAM_MUSIC, 1);
    clubb1Id = Clubb1.load(getActivity(), R.raw.clubb1, 1);
    clubb2Id = Clubb1.load(getActivity(), R.raw.clubb2, 1);
    clubb3Id = Clubb1.load(getActivity(), R.raw.clubb3, 1);

    View rootView = inflater.inflate(R.layout.fragment_one_layout, container, false);

    Button buttonA = (Button) rootView.findViewById(R.id.buttonA);
    Button buttonB = (Button) rootView.findViewById(R.id.buttonB);
    Button buttonC = (Button) rootView.findViewById(R.id.buttonC);

    View.OnClickListener ocl = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()){
                case R.id.buttonA:
                    //A clicked
                    Clubb1.play(clubb1Id, 1, 1, 1, 0, 1);
                    break;
                case R.id.buttonB:
                    //B clicked
                    Clubb1.play(clubb2Id, 1, 1, 1, 0, 1);
                    break;
                case R.id.buttonB:
                    //C clicked
                    Clubb1.play(clubb3Id, 1, 1, 1, 0, 1);
                    break;                
            }
        }
    };

    buttonA.setOnClickListener(ocl);
    buttonB.setOnClickListener(ocl);
    buttonC.setOnClickListener(ocl);

    return rootView;
}

所以只需加载更多声音。编辑

答案 1 :(得分:0)

不要忘记在fragment_one_layout.xml中添加新按钮!然后,按照Max Vitruk的说法,这应该有用; - )