在 ViewStub 中查找控件 Android

Finding controls inside a ViewStub Android

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

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

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

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()。

你可以这样做:

@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>

ViewStub 标记中的 android:layout 属性是对将在调用 inflate() 后膨胀的视图的引用。