我在文本视图上设置了位于片段上的文本,它返回一个NullPointerException。当静态添加片段时它会起作用,但是当我使用动态添加的片段时它会崩溃。
当我想在片段上设置文本时,这是调用的函数。
@Override
public void countrySelected(String wordIn) {
word = wordIn;
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
display.setCountryText(wordIn);
}else{
display = new DisplayFragment();
//display.setCountryText(wordIn);
fragmentTransaction.addToBackStack(list.getTag());
fragmentTransaction.replace(R.id.fragment_place,display,"disp");
fragmentTransaction.commit();
display.setCountryText(wordIn);
}
}
这是片段。
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right,container, false);
txt = (TextView) view.findViewById(R.id.txtView);
Log.d("LOOOOADED", "Loaded");
return view;
}
public void setCountryText(String word){
txt.setText(word);
}
当我在静态添加的片段上设置文本时,它工作得很好。但是当我在动态添加的片段上设置文本时,它不会记录“LOOOOADED”,这意味着它从未到达onCreateView()
方法。
答案 0 :(得分:1)
在片段附加到活动之前,您正在调用方法display.setCountryText(wordIn);
。
看看framgent生命周期。您需要等到片段附加到活动,然后调用display.setCountryText(wordIn)
。