如何在Fragment中设置onClickListener

时间:2014-12-04 03:35:14

标签: android android-fragments onclicklistener

我无法弄清楚如何在onClickListener中设置Fragment。我觉得我错过了一些愚蠢的东西。我知道这可以在一个简单的活动中工作,但我不知道为什么它不能在片段中工作。我想我可能需要将除this之外的其他内容传递给onClickListener()方法,但如果是这样,我无法弄清楚它是什么。

感谢有人看到这个!

 public class LogFragment extends Fragment implements OnClickListener{


    Button logButton;


   public LogFragment() {

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

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

     logButton = (Button) rootView.findViewById(R.id.logButton);
     logButton.setOnClickListener(this);

       return rootView;  //Changed it to this and still doesn't work
     //return inflater.inflate(R.layout.fragment_log, container, false);

   }

   @Override
   public void onClick(View arg0) {

      Toast.makeText(getActivity(), "You clicked it!", Toast.LENGTH_SHORT).show();

}

 }

2 个答案:

答案 0 :(得分:1)

在onCreateView中,您应该返回已经充气的视图,而不是给另一个视图充气(它的按钮没有附加点击监听器)。

答案 1 :(得分:1)

它没有用,因为你在onCreateView方法上返回一个内联新膨胀的视图。

而不是

return inflater.inflate(R.layout.fragment_log, container, false);

return rootView;