java - 无法从其他方法访问 TextView

标签 java android

我在布局中定义了一个 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/

相关文章:

java - 使用 JDBC 将 Android 连接到 SQL Server

android - 如何在android xml中的gridview中添加 TextView

java - Gradle 构建因 TransformException 失败

android - 如何只扫描(单播扫描)一个特定的 AP 而不是扫描信道?

java - sbt assembly fat JAR 的 Bigtable 错误(Jetty ALPN 和 OpenSSL 都不可用)

java - 在 Java 客户端和 Twisted Python 套接字服务器之间发送缓冲图像

java - com.deliveryrunner.vendor.MainActivity 无法转换为 android.app.Application

安卓SDK : how to read a USB device's class?

java - 有没有可能的方法从 OnClickListener 方法检索 ArrayList 值并将其保存在其父方法中?

java - 如何在scala中处理文本限定符分隔文件