无法解析片段中的方法'findViewById(int)'



我正在尝试将按钮实现到片段中,以便使用soundPool来播放带有按钮的声音。目前,playSound1 从未使用过,我试图实现 onClick 方法,但现在它说它无法解析该方法。如何将声音池链接到片段中的按钮?这是.java文件

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

将方法更改为:

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

你在这里犯了很多错误。所以我不确定我的方法是否对你有足够的帮助)将您的程序结果写到注释中,我们会尝试更多。

代码中有多个错误。

  1. 你以早的方式返回一个值,你的 return 语句之外的代码没有执行

  2. 您正在膨胀视图,但您的所有内部元素(例如您的按钮)都在该视图中,因此您必须在该视图中通过 id 找到该视图。

我纠正了它:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_one_layout, container, false);
        Clubb1 = new SoundPool(10, AudioManager.STREAM_MUSIC, 1);
        clubb1Id = Clubb1.load(getActivity(), R.raw.clubb1, 1);
        Button buttonA = (Button) root.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);}
        });
       return root;
}

相关内容

最新更新