feat: add try-catch for process function in PanguWidget

This commit is contained in:
2025-03-04 02:19:00 +08:00
parent 17b98a541c
commit b85cd1902b

View File

@@ -65,16 +65,23 @@ internal object PanguWidget {
val instance = view ?: name.let { val instance = view ?: name.let {
// There will be commonly used view class names in the XML layout, which is converted here. // There will be commonly used view class names in the XML layout, which is converted here.
if (!it.contains(".")) "android.widget.$it" else it if (!it.contains(".")) "android.widget.$it" else it
}.toClassOrNull()?.let { }.toClassOrNull()?.let { viewClass ->
// Avoid creating unnecessary components for waste. // Avoid creating unnecessary components for waste.
if (it notExtends classOf<TextView>()) return null if (viewClass notExtends classOf<TextView>()) return null
val twoParams = it.constructor { val twoParams = viewClass.constructor {
param(ContextClass, AttributeSetClass) param(ContextClass, AttributeSetClass)
}.ignored().get() }.ignored().get()
val onceParam = it.constructor { val onceParam = viewClass.constructor {
param(ContextClass) param(ContextClass)
}.ignored().get() }.ignored().get()
twoParams.newInstance<View>(context, attrs) ?: onceParam.newInstance<View>(context) // Catching when the attrs value initialization failed.
runCatching { twoParams.newInstance<View>(context, attrs) }.onFailure {
Log.w(PangutextAndroidProperties.PROJECT_NAME, "Failed to create instance of $viewClass using (Context, AttributeSet).", it)
}.getOrNull()
// Try to initialize with the default constructor again, otherwise return null.
?: runCatching { onceParam.newInstance<View>(context) }.onFailure {
Log.w(PangutextAndroidProperties.PROJECT_NAME, "Failed to create instance of $viewClass, this process will be ignored.", it)
}.getOrNull()
} }
// Ignore if the instance is not a [TextView]. // Ignore if the instance is not a [TextView].
if (instance !is TextView) return null if (instance !is TextView) return null