首页 > 解决方案 > 在 ViewStub Android 中查找控件

问题描述

我有一个片段,我想对一些数据使用 ViewStub。

我遇到的问题是,一旦我从片段 Java 类中膨胀了 ViewStub,我如何在 ViewStub 内的片段 Java 类组件中引用?

例如我目前在组件处于片段的膨胀视图时使用;

TextView txtAwayPenStat = (TextView) myResInfoView.findViewById(R.id.txtAwayPenStat);

如果将 txtAwayPenStat 移动到 ViewStub,这将不起作用。

我尝试了几种方法;

        ViewStub viewStub = (ViewStub) getActivity().findViewById(R.id.info_detail_stub);
        View inflatedView = viewStub.inflate();

getActivity() 在哪里,我也尝试过 getView()。

标签: androidviewstub

解决方案


你可以这样做:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewStub stub = (ViewStub) findViewById(R.id.stub);
        View inflated = stub.inflate();
        TextView txtAwayPenStat = (TextView) inflated.findViewById(R.id.txtAwayPenStat);
        txtAwayPenStat.setText("gdgad");
    }

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <ViewStub
        android:id="@+id/stub" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout="@layout/mysubtree" 
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

</android.support.constraint.ConstraintLayout>

mysubtree.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <TextView
        android:id="@+id/txtAwayPenStat"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="HELLO WORLD"
        ></TextView>

</android.support.constraint.ConstraintLayout>

tag 中的android:layout属性ViewStub是对将在调用 inflate() 后膨胀的 View 的引用。


推荐阅读