ARTS - 4

416 阅读3分钟

A


题目

166. 分数到小数

给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。

如果小数部分为循环小数,则将循环的部分括在括号内。

解法

写的时候的思路是模拟长除法的过程,每次获取整除和余数的值,然后取余数重复计算。循环节的判断则通过余数是否出现过来进行判断。

看其他人的题解时发现个有意思的思路,不是通过模拟长除法不断循环来实现,而是直接推导循环节来实现。虽然实现起来比长除法要复杂,但也提供了不同的解法。

这道题很明显是个简单的找循环节的题,但是我想到一个特殊的方法,推导公式来解决这个问题

感觉测试数据里有很多分母为 0 的情况。我提交了 2 次,第 1 次没有在最开始判断分母为 0 时的情况,第 2 次判断了。结果第 2 次的时间是第 1 次的 2/3 。

R


A New Way to Pass Data Between Fragments

文章首先介绍了一种不通过 contextinterfaceshare view modelApplication 级的数据来在 Fragment 之间传递数据的方法。即通过 targetFragment 来传递数据。

首先为展示的 Fragment 设置 targetFragment

private fun showOptionsDialog() {
        val optionsDialogInstance = OptionsDialogFragment()
        optionsDialogInstance.setTargetFragment(this, 1)
        optionsDialogInstance.show(parentFragmentManager, optionsDialogInstance.tag)
}

然后在展示的 Fragment 里通过 OnActivityResult() 方法传递数据。

fun onExit(selectionValue: String){
        val intent = Intent()
        intent.putExtra("selection",selectionValue)
        intent.putExtra(TYPE,type)
        targetFragment?.onActivityResult(targetRequestCode, Activity.RESULT_OK, intent)
}

这样在原来的 Fragment 里的 onActivityResult() 方法里就能接收到数据了。

但是这种要求两个 Fragment 必须是在同一个 FragmentManager 中,否则就无法使用。

不过在 Fragment 1.3.0-alpha04 中,可以在父子 FragmentManager 中通过对关键字的监听来传递数据。

首先在要接收数据的 Fragment 里设置监听:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    // Use the Kotlin extension in the fragment-ktx artifact
    setFragmentResultListener("requestKey") { key, bundle ->
        val result = bundle.getString("name")
        // Do something with the result...
    }
}

然后在要传递数据的 Fragment 里传递数据:

tvSave.setOnClickListener {
    setResult("requestKey", bundleOf("name" to updatedValue))
}

如果传递数据的 Fragment 在接收数据的 Fragmentchildfragmentmanager 里,则监听的设置方式如下:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    // We set the listener on the child fragmentManager
    childFragmentManager.setResultListener("uniquerequestKey") { key, bundle ->
        val result = bundle.getString("name")
        // Do something with the result..
    }
}

T


Transformations.map() : 在 MutableLiveDataLiveData 的过程中转换数据类型。

在使用 LiveData 时。经常会将 privateMutableLiveDatapublicLiveData 共同使用。

在实际使用过程中有时会遇到从数据源获取的是 DataObject ,但最后和外部交互的 LiveData 所需要是 ViewObject ,同时 DataObject 还需要保存起来供其他方法调用的情况。

一种处理方式是 MutableLiveDataLiveData 的数据类型都是 ViewObjectDataObject 单独用属性保存。

但通过 Transformations.map() 的方式,可以在 MutableLiveData 里保存 DataObjectLiveData 里保存 ViewObject 。这样既可以不需要单独保存 DataObject ,也可以减少一部分 LiveData 只是单纯用来防止外部修改数据的情况。

private val mCurrentDate = MutableLiveData<LocalDate>()
val currentDate: LiveData<String> = Transformations.map(mCurrentDate) {
    it.toString()
}

S


Paging 3 的初步使用