2014-12-04 103 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; 
相關問題