【发布时间】:2020-11-07 13:17:04
【问题描述】:
在我的项目中,我将三个片段附加到一个活动,其中一个片段再次使用自定义视图显示文本。所以它们基本上是片段中的片段。
在主片段中,我将这些代码用于在文本显示片段之间切换。它在其子片段传递的代码上触发。
private fun diagCommence(target: Fragment) {
val transaction = activity?.supportFragmentManager?.beginTransaction()
if (transaction != null) {
transaction.replace(R.id.ig1_Diag_Layout, target)
transaction.disallowAddToBackStack()
transaction.commit()
}
}
文本显示片段具有自定义视图 - AppCompatTextView - 显示文本。
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.layoutx2, container, false)
}
override fun onStart() {
super.onStart()
val scene = getString(R.string.sceneX2)
tv01.commenceOnLifecycle(SceneX2(), scene, textanimspeed.toLong(), textanim) // the custom view that displays texts, triggers NPE
}
我现在有三个相同的文本显示片段,第一个文本显示片段显示正常。但是当我尝试将值传递给主片段并触发 diagCommence() 时,应用程序崩溃了。奇怪的是,当我尝试访问第二个文本显示片段时,它给了我空指针异常。
根据日志,在 beginOnLifecycle() 方法中调用了错误,该方法调用了我制作的 AppCompatTextView。将其移动到不同的生命周期,例如 onCreate()、onViewCreated() 似乎无助于解决这个问题。我想知道我错过了什么?
编辑:SceneX2的布局XML,是一个文本显示片段:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/x2Layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.textia1.TypeWriterView
android:id="@+id/x2Twv01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/colorAccent" />
<TextView
android:id="@+id/x2Choice01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/X2toX1" />
<TextView
android:id="@+id/x2Choice02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/X2toX3" />
</LinearLayout>
以及使用打字动画显示文本的自定义 TextView:
class TypeWriterView: AppCompatTextView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
suspend fun commence(txt: CharSequence?, delay: Long, animOnOff: Boolean) {
if (txt != null) {
if(animOnOff) {
var index = 0
while (index < txt.length) {
text = txt.subSequence(0, ++index)
delay(delay)
}
} else {text = txt}
} else return
}
fun commenceOnLifecycle(owner: LifecycleOwner, txt: CharSequence?, delay: Long, animOnOff: Boolean): Job =
owner.lifecycleScope.launch { commence(txt, delay, animOnOff) }
}
【问题讨论】: