2014-12-04 105 views
0

我无法弄清楚如何在Fragment中设置onClickListener。我觉得我失去了一些愚蠢的东西。我知道这是一个简单的活动,但我不知道它为什么不能在片段中工作。我想我可能需要通过除this以外的其他方法onClickListener()方法,但如果是这样,我无法弄清楚它是什么。如何在Fragement中设置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(); 

} 

} 

回答

1

在onCreateView,你应该回到你已经膨胀的观点,而不是膨胀另一种看法(它没有连接到它的按钮点击收听)。

+0

如果我跟着你正确的,你说回'rootView'但是当我尝试,它仍然无法正常工作。 – WeVie 2014-12-04 03:46:13

+0

冒着贬低你的风险,你确定它不起作用吗? – tachyonflux 2014-12-04 04:06:06

+0

不用担心。我以为我确定。它确实有效。我在应用程序上有两个按钮,点击了错误的按钮。什么是笨蛋? – WeVie 2014-12-04 04:12:18

1

它不起作用,因为您正在onCreateView方法上返回一个内联新近膨胀的视图。

而不是

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

尝试

return rootView; 
相关问题