Cannot resolve method 'findViewById(int)' in Fragment

Jonathan Chappell picture Jonathan Chappell · Mar 11, 2015 · Viewed 14.4k times · Source

I am trying to implement a button into a fragment in order to use the soundPool in order to play a sound with a button. At the moment the playSound1 is coming up as never used and I have tried to implement the onClick Method but it is now coming up saying it cannot resolve the method. How do I link the soundPool to a button in a fragment? this is the .java file

@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);

        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.fragment_one_layout, container, false);

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

        buttonA.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

            }

            public void playSound1()
            {Clubb1.play(clubb1Id,1,1,1,0,1);}
        });

Answer

Max Vitruk picture Max Vitruk · Mar 11, 2015

Change your method to :

  @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 veiw;
    }

You did a lot of mistakes here. So im not sure that my approach help you enough ) Write your program result into comment and we`ll try more.