将数据从片段传递到另一个

时间:2018-06-07 11:10:38

标签: android android-fragments

我在片段1中有一个编辑文本,在片段2中有一个文本视图,当我更改编辑文本时,另一个片段中的文本视图也会发生变化

1 个答案:

答案 0 :(得分:0)

使用接口在两个片段之间进行通信。 fragment_2将实现接口,fragment_1将在输入更改时调用该接口方法。

FragmentOne

class FragmentOne : Fragment() {
    var listener: DataPassCallback? = null

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        et_input.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                listener?.dataChaged(s.toString())
            }
        })
    }
}

FragmentTwo

class FragmentTwo : Fragment(), DataPassCallback {

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

    override fun dataChaged(data: String) {
       td_output.text = data
   }
}

传递数据的接口

interface DataPassCallback {
    fun dataChaged(data: String)
}

添加这些片段的活动(这只是一个例子)

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val fragOne = FragmentOne()
        supportFragmentManager.beginTransaction().add(R.id.layout_fragment_one, fragOne).commit()

        val fragTwo = FragmentTwo()
        supportFragmentManager.beginTransaction().add(R.id.layout_fragment_two, fragTwo).commit()

        fragOne.listener = fragTwo
    }
}