2016-10-01 55 views
0

我正在嘗試使用製表符和PagerAdapter來製作選項卡布局。訪問視圖的片段錯誤

我在Fragment下面的表達式:

cpPrecTextView = (BootstrapLabel) getView().findViewById(R.id.cpPrec); 
cpPrecTextView.setText(cpPrecTextView.getText() + cpPrec); 

我的應用程序崩潰,出現以下錯誤:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference 
         at com.pgoiv.pokemongoiv.TabFragment1.onCreateView(TabFragment1.java:45) 

有什麼不對?

+0

告訴你'getView()'爲null –

回答

0

您的getView()返回null。我假設您沒有爲Fragment正確膨脹容器視圖。因此,在您的onCreateView中,您需要先像這樣膨脹視圖。

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

    // Inflate the layout and get the reference of the view 
    View v = inflater.inflate(R.layout.fragment_my_tickets, container, false); 

    // Now find any view inside that 
    cpPrecTextView = (BootstrapLabel) v.findViewById(R.id.cpPrec); 
    cpPrecTextView.setText(cpPrecTextView.getText() + cpPrec); 

    return v; 
} 
0

getView()返回null

爲了解決這個問題,你應該運行依賴於onCreateView一個視圖中的所有代碼。這樣,您將始終參考用於查找其他視圖的視圖。

您可以參考Android Developers page瞭解關於片段生命週期的更多信息!