我在布局中定义了TextView块。
<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" />
我将类的私有属性定义为:
View inflatedView;
稍后,在onCreateView方法中,它的值为:
inflatedView = inflater.inflate(R.layout.article_view, container, false);
当从onCreateView方法访问TextView字段时,它没有问题,但是,尝试从其他方法访问它,返回null引用。
这是我正在使用的代码:
TextView article = (TextView) inflatedView.findViewById(R.id.article);
我通过将文章设置为私有属性,在onCreateView方法中初始化它的值,然后在所有其他方法中使用它来设法让它工作,但是,我无法理解上述方法的问题是什么。
编辑:
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;
}
答案 0 :(得分:1)
所以我解决了这个问题,把TextView块放在LinearLayout中,然后调用findViewById(R.id.article);
使用以下方法管理以获取TextView:
inflatedView.findViewById(R.id.article);
和
getView().findViewById(R.id.article);
答案 1 :(得分:0)
在使用此方法之前,请确保 inflatedView 不为空。