Android Fragment 倒计时代码错误修正:检查 `ClockFragment` 代码中的错误
在提供的代码中,有几个错误需要修正:
ClockFragment继承自Fragment,需要确保导入了正确的Fragment类。可以在文件开头添加以下导入语句:
import androidx.fragment.app.Fragment;
-
onCreate方法不应该调用setContentView,因为它是在Fragment中使用的,而不是在Activity中使用的。可以将setContentView移除。 -
在获取
countdownTextView的实例时,应该使用getView()方法来获取Fragment的根视图,然后再调用findViewById方法。可以将以下代码:
countdownTextView = countdownTextView.findViewById(R.id.countdown);
修改为:
countdownTextView = getView().findViewById(R.id.countdown);
- 为了确保
countdownTextView不为空,可以在获取实例后添加一个非空检查。可以在以下代码的前面添加一个条件判断:
if (countdownTextView != null) {
// 倒计时逻辑
}
请根据上述修改,更新你的 ClockFragment 类的代码。
原文地址: http://www.cveoy.top/t/topic/GhO 著作权归作者所有。请勿转载和采集!