I have a TextView block defined in a layout.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/article"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textSize="18sp" />
I define private attribute of a class as:
View inflatedView;
Later, in onCreateView method, it's given the value of:
inflatedView = inflater.inflate(R.layout.article_view, container, false);
When accessing the TextView field from the onCreateView method, it makes no problem, however, trying to access it from other methods, returns null reference.
Here's the code I'm using:
TextView article = (TextView) inflatedView.findViewById(R.id.article);
I managed to get it to work by setting the article as private attribute, initializing it's value in onCreateView method, then using it in all other methods, however, I can't understand what's the problem with the approach above.
EDIT:
View inflatedView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
//article_view contains the article TextView
inflatedView = inflater.inflate(R.layout.article_view, container, false);
return inflatedView;
}
public void updateArticleView(int position) {
TextView article = (TextView) inflatedView.findViewById(R.id.article);
article.setText(Ipsum.Articles[position]);
mCurrentPosition = position;
}
findViewById(...)- the call toinflate(...)will return the TextView directly.inflatedViewvariable to aTextView