android - 在 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()。
解决方案
你可以这样做:
@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 的引用。
推荐阅读
- nginx - Nginx 错误或功能?
- asp.net-core - 在 .NET Core 中调用 OAuth 保护的 API
- citrus-framework - 柑橘模拟器 | 提取有效载荷
- ios - 使用 VideoToolbox API (kVTVideoDecoderBadDataErr) 解码 H264 流
- python - TypeError: 'DataFrame' 对象是可变的,因此在创建数据帧字典时它们不能被散列
- c++ - 使用 CMake 生成 DLL 配置类型
- javascript - 您如何使用 JS 或 jQuery 从 bootstraps datetimepicker 控制台记录日期
- java - 此处不允许线程“主”映射值中的异常
- css - 如何使用 webpack 将 sass 实现到 ReactJS 应用程序中?
- vue.js - 我正在寻找一种在函数中使用 Vue 道具的方法