왜이 오류가 발생합니까? 실패findViewById가 OnCreateView 외부에서 사용되는 경우 null을 반환합니다.
public class ArticleFragment extends Fragment {
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// If activity recreated (such as from screen rotate), restore
// the previous article selection set by onSaveInstanceState().
// This is primarily necessary when in the two-pane layout.
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
// Inflate the layout for this fragment
return inflater.inflate(R.layout.article_view, container, false);
}
@Override
public void onStart() {
super.onStart();
// During startup, check if there are arguments passed to the fragment.
// onStart is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method
// below that sets the article text.
Bundle args = getArguments();
if (args != null) {
// Set article based on argument passed in
updateArticleView(args.getInt(ARG_POSITION));
} else if (mCurrentPosition != -1) {
// Set article based on saved instance state defined during onCreateView
updateArticleView(mCurrentPosition);
}
}
public void updateArticleView(int position) {
TextView article = (TextView) getActivity().findViewById(R.id.article);
article.setText(Ipsum.Articles[position]);
mCurrentPosition = position;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current article selection in case we need to recreate the fragment
outState.putInt(ARG_POSITION, mCurrentPosition);
}
}
라인은 다음과 같습니다 기사가 null
article.setText(Ipsum.Articles[position]);
때문이다. 따라서 :
getActivity().findViewById(R.id.article)
이 null을 반환합니다.
그러나, 나는이 같은 onCreateView의 기사 설정 한 경우 :
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// If activity recreated (such as from screen rotate), restore
// the previous article selection set by onSaveInstanceState().
// This is primarily necessary when in the two-pane layout.
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
View view = inflater.inflate(R.layout.article_view, container, false);;
article = (TextView) view.findViewById(R.id.article);
return view;
}
과 같이 updateArticle 변경 :
public void updateArticleView(int position) {
article.setText(Ipsum.Articles[position]);
mCurrentPosition = position;
}
제대로 작동합니다.
이 코드는 기본 Android 튜토리얼의 Google 예제에서 나온 것입니다. –
시도해 보셨습니까? – thushcapone