提问人:Jason W 提问时间:6/27/2023 更新时间:6/27/2023 访问量:16
Android - 如何处理 ViewStubs 的 null 大小写
Android - How to Handle Null Case for ViewStubs
问:
我是一名自学成才的 Android 开发人员,我想在我的(实时)应用程序中使用 ViewStub,但我不确定在 null 情况下该怎么做。
我的 XML - you_win_overlay.xml:
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/stub"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
style="@style/title_style"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
我的主要活动 XML
<ViewStub
android:id="@+id/you_win_stub"
android:inflatedId="@+id/you_win_stub_inflated"
android:layout="@layout/you_win_overlay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent">
</ViewStub>
在我的主活动中,我调用了一个方法,该方法使用 ViewStub 向玩家显示获胜游戏。所以方法看起来像这样:
showTheEndGameOverlay(SharedPreferences memory, ViewStub viewStub, Animation slide) {
View inflated;
if(viewStub != null) {
inflated = viewStub.inflate();
inflated.setZ(12);
TextView theTitle = (TextView) inflated.findViewById(R.id.title);
theTitle.setText(memory.getString("currentTitle", "Default Title"));
} else {
WHAT WOULD I DO HERE???
WHAT WOULD I DO HERE???
WHAT WOULD I DO HERE???
}
}
我不确定在这里如何处理 null 情况。我从几个示例中复制了这段代码,在每个示例中,他们都测试了 viewStub != null。在我的游戏中测试代码时,它工作得很好,每次 viewStub 都不是 null,一切都按预期执行。每次测试时,我都会赢得一场比赛,并且“showTheEndGameOverlay”方法执行 viewStub 不为 null。所以我不确定我什至需要做这个空检查,viewStub 将始终位于主活动的 XML 文件中......那么怎么可能是空的呢?
但是,由于这对我来说是新的,因此我不想犯错误并在需要时忽略处理空情况。谁能帮忙?谢谢。
答: 暂无答案
评论