2015-11-02 65 views
4

我試圖讓我的片段工作,我不能做任何我想做的事情。Android片段和空對象引用

我正的錯誤是:

顯示java.lang.NullPointerException:嘗試上的空對象引用調用虛擬方法「無效android.widget.TextView.setText(java.lang.CharSequence中)」

下面是代碼:

public class FragmentOne extends Fragment { 

    private TextView one; 

    public FragmentOne() { 
     // Required empty public constructor 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     one = (TextView) getActivity().findViewById(R.id.one); 

     // Displaying the user details on the screen 
     one.setText("kjhbguhjg"); 

    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     return inflater.inflate(R.layout.fragment1, container, false); 

    } 
} 

不知道爲什麼,這是行不通的。我正在測試這個類,只是爲了看文本將在textview中被改變。我使用正確的ID,因爲我檢查了10次,但我認爲這個問題是因爲textview one是一個空對象。但爲什麼它沒有找到該ID?

回答

7

onCreate()onCreateView()之前被調用,因此您將無法在onCreate()中訪問它。

解決方案: 移動

one = (TextView) getActivity().findViewById(R.id.one); 

onViewCreated()代替。

有關fragment lifecycle的概述,請參見下圖。

新片段看起來是這樣的:

public class FragmentOne extends Fragment { 


    private TextView one; 

    public FragmentOne() { 
     // Required empty public constructor 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     return inflater.inflate(R.layout.fragment1, container, false); 
    } 

    @Override 
    public void onViewCreated(View view, Bundle savedInstanceState){ 
     one = (TextView) getActivity().findViewById(R.id.one); 
     // Displaying the user details on the screen 
     one.setText("kjhbguhjg"); 
    } 
} 

Fragment lifecycle

+0

試過,之前......在這種情況下,我得到不到的語句錯誤... – AlwaysConfused

+0

你從無法訪問錯誤的** **編譯。請仔細檢查語法錯誤。發佈完整的代碼。 –

+0

我所有的代碼都在問題中,我按照你的建議做了。我將'one =(TextView)getActivity()。findViewById(R.id.one);'放到'return inflater.inflate(R.layout.fragment1,container,false)正下方的onCreateView;' – AlwaysConfused

2

或者。而不是重寫

public void onViewCreated(View view, Bundle savedInstanceState) 

你可以稍微改變你的onCreateView所以它看起來像

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
// Inflate the layout for this fragment 
View rootView = inflater.inflate(R.layout.fragment1, container, false) 
one = (TextView) rootView.findViewById(R.id.one) 
return rootView; 
} 
+0

謝謝!我會牢記它! – AlwaysConfused

+1

你得到了無法訪問的語句錯誤,導致你在返回語句之後放一個=(TextView)rootView.findViewById(R.id.one),這是該方法的最後一個語句。 – JDRussia