【问题标题】:How to avoid duplicate code in the activity and fragment?如何避免 Activity 和 Fragment 中的重复代码?
【发布时间】:2019-07-23 00:28:54
【问题描述】:

当一个activity启动时,会在其中检查条件,如果条件为真,则调用openNewActivity方法并结束当前activity。但是如果条件为假,则对片段进行转换,在该片段中该条件可以变为真,然后您需要调用活动中定义的openNewActivity方法。我不想在片段中复制此方法,如何正确实现从片段中对该方法的调用?在这种情况下,最佳做法是什么?

【问题讨论】:

  • 把它移到一个单独的类?
  • @TaseerAhmad 我可能是错的,但在我看来,将此方法带入一个单独的类是一个非常合适的解决方案,我正在考虑调用 In fragment ((MyActivity) getActivity()) 的选项。 CallMethod(),不过不知道这个方法好不好
  • 你也可以这样做,但它是关于将活动方法暴露给另一个类。就个人而言,我会创建一个单独的类,将方法放在那里,然后在您的项目中访问它。非 UI 逻辑通常应该放在一个单独的类中
  • @TaseerAhmad 为什么打开一个新活动是一个非 UI 逻辑?
  • 对不起,我以为你的意思是条件,打开一个新的活动不是非UI线程,事实上,只有活动应该处理打开另一个活动。您可以使用interfaces 来解决问题。片段告诉活动打开新活动。让我写一个例子。

标签: android code-duplication


【解决方案1】:

活动

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.
   }

}

创建一个接口。由于代码中提到的原因,在活动的onAttachFragment中初始化片段的接口。这样启动一个新activity的函数只在activity中定义,不需要在fragment中重复。

【讨论】:

  • 这种方式在我看来很繁琐,但是如果从fragment调用activity方法是一个糟糕的决定,那我就照你说的做。感谢您的帮助。
  • 你会习惯的,有时必须编写“繁琐”的代码来尊重干净的软件设计
猜你喜欢
  • 2011-08-29
  • 1970-01-01
  • 2021-04-28
  • 2020-08-31
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
相关资源
最近更新 更多