我在布局中定义了一个 TextView block 。
<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" />
我将类的私有(private)属性定义为:
View inflatedView;
稍后,在 onCreateView 方法中,它的值是:
inflatedView = inflater.inflate(R.layout.article_view, container, false);
当从 onCreateView 方法访问 TextView 字段时,没有问题,但是,尝试从其他方法访问它时,返回空引用。
这是我使用的代码:
TextView article = (TextView) inflatedView.findViewById(R.id.article);
我设法通过将文章设置为私有(private)属性,在 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;
}
最佳答案
所以我解决了这个问题,方法是将 TextView block 放在 LinearLayout 中,然后调用 findViewById(R.id.article);
设法通过使用以下方式获取 TextView:
inflatedView.findViewById(R.id.article);
和
getView().findViewById(R.id.article);
关于java - 无法从其他方法访问 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33312529/