如何避免 activity 和片段中的重复代码?
How to avoid duplicate code in the activity and fragment?
当一个activity启动时,检查其中的条件,如果条件为真,则调用openNewActivity
方法,当前的activity结束。但是如果条件为假,则对片段进行转换,在该片段中这个条件可以变为真,然后您需要调用 openNewActivity
方法,该方法定义在 activity 中。我不想在片段中复制此方法,如何从片段中正确实现对此方法的调用?这种情况下的最佳做法是什么?
Activity
class FirstActivity : AppCompatActivity(), MyInterface {
override fun onSomethingDone() { //This function gets called when the condition is true
openNewActivity()
}
override fun onAttachFragment(fragment: Fragment) { //A fragment MUST never know it's an activity, so we exposed fragment interface member to easily initialize it whenever the fragment is attached to the activity.
when (fragment) {
is MyFragment -> fragment.myInterface = this
}
}
override fun onCreate() {
super.onCreate()
}
private fun openNewActivity() {
//opens a new activity
}
}
界面
interface MyInterface {
fun onSomethingDone()
}
片段
class MyFragment : Fragment() {
var myInterface: MyInterface? = null
override fun onCreate() {
if (somethingIsTrue)
myInterface.onSomethingDone() //condition is true, call the interface method to inform the activity that the condition is true and the new activity should be opened.
}
}
创建一个界面。由于代码中提到的原因,在 activity 的 onAttachFragment
中初始化片段的接口。这样,用于启动新 activity 的函数仅在 activity 中定义,不需要在片段中重复。
当一个activity启动时,检查其中的条件,如果条件为真,则调用openNewActivity
方法,当前的activity结束。但是如果条件为假,则对片段进行转换,在该片段中这个条件可以变为真,然后您需要调用 openNewActivity
方法,该方法定义在 activity 中。我不想在片段中复制此方法,如何从片段中正确实现对此方法的调用?这种情况下的最佳做法是什么?
Activity
class FirstActivity : AppCompatActivity(), MyInterface {
override fun onSomethingDone() { //This function gets called when the condition is true
openNewActivity()
}
override fun onAttachFragment(fragment: Fragment) { //A fragment MUST never know it's an activity, so we exposed fragment interface member to easily initialize it whenever the fragment is attached to the activity.
when (fragment) {
is MyFragment -> fragment.myInterface = this
}
}
override fun onCreate() {
super.onCreate()
}
private fun openNewActivity() {
//opens a new activity
}
}
界面
interface MyInterface {
fun onSomethingDone()
}
片段
class MyFragment : Fragment() {
var myInterface: MyInterface? = null
override fun onCreate() {
if (somethingIsTrue)
myInterface.onSomethingDone() //condition is true, call the interface method to inform the activity that the condition is true and the new activity should be opened.
}
}
创建一个界面。由于代码中提到的原因,在 activity 的 onAttachFragment
中初始化片段的接口。这样,用于启动新 activity 的函数仅在 activity 中定义,不需要在片段中重复。