我試圖讓我的片段工作,我不能做任何我想做的事情。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?
試過,之前......在這種情況下,我得到不到的語句錯誤... – AlwaysConfused
你從無法訪問錯誤的** **編譯。請仔細檢查語法錯誤。發佈完整的代碼。 –
我所有的代碼都在問題中,我按照你的建議做了。我將'one =(TextView)getActivity()。findViewById(R.id.one);'放到'return inflater.inflate(R.layout.fragment1,container,false)正下方的onCreateView;' – AlwaysConfused