【问题标题】:What is the best way of communicating between a Fragment and an Activity in Android?Android 中 Fragment 和 Activity 之间通信的最佳方式是什么?
【发布时间】:2020-08-08 16:04:02
【问题描述】:

几乎在我读过的所有文章中,人们都使用this approach 在 Fragment 和 Activity 之间进行通信:

在 Activity 和 Fragment 之间进行通信的最简单方法是 使用接口。这个想法基本上是在里面定义一个接口 给定的片段 A 并让 Activity 实现该接口。

一旦它实现了那个接口,你就可以做任何你想做的事情 在它覆盖的方法中。

但是为什么人们使用这种方法,而我们可以传递Interfacefunction 作为 Fragment 的构造函数参数然后使用它?

我的意思是我们可以在 Fragment 中做这样的事情(我使用 Kotlin 函数作为构造函数参数,但我们也可以使用 Interfaces):

class CategoryListFragment(private val onBtnAddCategoryClick: () -> Unit) : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val content = inflater.inflate(R.layout.fragment_category_list, container, false)
        return content
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        fab_add_category.setOnClickListener {
            onBtnAddCategoryClick()
        }
    }

}

并在 Activity 中像这样使用它:

class MainActivity : AppCompatActivity() {

    companion object{
        const val TAG_ADD_CATEGORY_DIALOG = "TAG_ADD_CATEGORY_DIALOG"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.container, CategoryListFragment{
            Toast.makeText(this@MainActivity, "show add category", Toast.LENGTH_SHORT).show()
        })
        fragmentTransaction.commit()
    }

}

我认为第二种方法更好,因为我们可以做Dependency-Injection,而且不需要做任何upcasting等。

【问题讨论】:

    标签: java android kotlin fragment


    【解决方案1】:

    问题在于,在您的应用程序生命周期中,系统可能需要再次销毁并重新创建您的片段,但它会调用不带参数的构造函数,因此您的 onBtnAddCategoryClick 不会设置。所以你必须从你的活动中设置它。这也是为什么你应该使用bundle在活动和片段之间传递数据的原因

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多