我剛開始使用片段。我在片段中創建了一個編輯文本,我想從活動中填充它,但它給了我空指針異常。可能是在片段事務提交後運行OnCreateView。我用另一種方式使它工作,但我只是有點好奇它爲什麼不起作用。我搜查了它,但找不到我的問題的答案。任何幫助,將不勝感激設置活動給出空指針的片段的編輯文本
這裏是我的代碼在活動:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Myfragment mFragment = new Myfragment();
fragmentTransaction.replace(R.id.fragment_container, mFragment);
fragmentTransaction.commit();
mFragment.set_fragment_editext("Hello world");//setting edit text in fragment throws exception
然後在片段類:您撥打的setText功能,因此空指針後
public class Myfragment extends Fragment {
EditText edittext_fragment;
public static Myfragment newInstance() {
return new Myfragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.Myfragment, container, false);
InitializeFragment(myInflatedView);
return myInflatedView;
}
private void InitializeFragment(View myInflatedView) {
edittext_fragment = (EditText) myInflatedView.findViewById(R.id.edittext_fragment_caption);
}
public void set_fragment_editext(String value) {
edittext_fragment.setText(value);
}
}
非常感謝您的回答似乎是正確的一個 – SimpleMan
@SimpleMan直截了當地說這個解決方案存在問題。 onAttachFragment在片段中的onViewCreated之前被調用。請稍等,我會修復我的解決方案:) –
@SimpleMan我修復了我的答案。對不起,第一個與onAttachFragment() –