我有一个片段,我想使用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()。
答案 0 :(得分:1)
您可以这样:
@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>
android:layout
标签中的ViewStub
属性是对视图的引用,该视图将在inflate()调用之后被夸大。