简体   繁体   中英

Can't access TextView from another method

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;
}

So I solved the problem, by putting the TextView block inside the LinearLayout, and then calling the findViewById(R.id.article);

Managed to get the TextView both by using:

inflatedView.findViewById(R.id.article);

and

getView().findViewById(R.id.article);

使用此方法之前,请确保inflatedView不为null。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM