0

I have a fragment and I want to use a ViewStub for some data.

The problem I have is once I have inflated the ViewStub from the fragments Java class, how can I reference in the fragments java class components inside the ViewStub?

For example I currently use when the component is in the inflated view of the fragment;

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

This will not work if the txtAwayPenStat is moved to the ViewStub.

I have tried a couple of approaches;

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

Where getActivity() is I have also tried getView().

Carl Bruiners
  • 516
  • 1
  • 7
  • 21

1 Answers1

5

You could do like this:

@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");
    }

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

The android:layout attribute in ViewStub tag is a reference to the View that will be inflated next to a call of inflate().

navylover
  • 12,383
  • 5
  • 28
  • 41