2017-01-17 1 views
0

왜이 오류가 발생합니까? 실패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; 
} 

제대로 작동합니다.

답변

1

당신은이 같은 뷰 얻기 위해 코드에서 다른 곳을 호출 할 수 있습니다 당신이 블록 다음

onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState){ 
     //Previous code 
     view = inflater.inflate(R.layout.article_view, container, false); 
    } 

에서 팽창 된 뷰를 절약 할 수있다 :

view.findViewById(R.id.view_searched); 

대신를 : findViewById 때문에

getActivity().findViewById(R.id.view_searched); 
+0

이 코드는 기본 Android 튜토리얼의 Google 예제에서 나온 것입니다. –

+0

시도해 보셨습니까? – thushcapone

2

아마 대신

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

호출 당신은 활동의 생성이 그 시간에 의해 완성된다 당신은 조각의 활동의 컨텍스트를 액세스하고 필요하지 않은

TextView article = (TextView) getView().findViewById(R.id.article); 
+0

이전에 시도했으나 작동하지 않습니다. 이 코드는 기본 Android 튜토리얼의 Google 예제에서 나온 것임을 언급해야합니다. –

1

호출해야합니다. onCreate 외부에서 이것을 호출해야하는 경우 조각의 OnActivityCreated 메소드에서 호출하십시오.

그러나 당신의 텍스트 뷰가 단편에 아닌 활동

2

텍스트 뷰가 활동이 단편에 아니라 때문에 작동하지 않습니다에있는 것 같다. getActivity()는 프래그먼트가 아닌 활동을 반환합니다. 따라서 조각에 대한 textView 로컬을 찾을 수 없습니다.

반면 onCreateView에서는 'view'가 조각 인 view.findViewById()를 언급합니다.

0

이 아닌년, 뷰 개체의 ID를 얻기 위해 수행됩니다개체. 당신이 Fragment를 인스턴스화 할 때 당신은 onCreateView 방법 뷰를 만들 : 당신은 당신의보기에 그 ID를 검색

View view = inflater.inflate(R.layout.article_view, container, false);; 
article = (TextView) view.findViewById(R.id.article); 
return view; 

(컨테이너 R.layout.article_view입니다 함께).

getActivity.findViewById()을 작성하면 ID로 찾을 수있는보기가 없습니다.

+0

이 코드는 기본 Android 튜토리얼의 Google 예제에서 나온 것입니다. –

+0

그래도보기가 자신의 활동에 있지 않은 조각에 있습니까? – Alvaro

관련 문제