小编Hel*_*oCW的帖子

有没有一种简单的方法可以从 Kotlin 的对象列表中获取数组?

我希望从MSetting的列表中得到一个name数组,目前我使用 Code A 来做,但是太复杂了,有没有简单的方法来做?

代码 A

  fun getName(aList:List<MSetting>): Array<CharSequence>{
        if (aList.isEmpty()){
            return emptyArray<CharSequence>()
        }else{
            var aa=Array<CharSequence>(aList.size,{""})
            for (index in aList.indices){
                aa[index]=aList[index].name
            }
            return aa
        }
    }
Run Code Online (Sandbox Code Playgroud)

数据

data class MSetting (
        var _id: Long,  
        var name: String,
        var createdDate: Long,
        var description: String
)
Run Code Online (Sandbox Code Playgroud)

android kotlin

1
推荐指数
2
解决办法
2042
查看次数

为什么我可以在 Kotlin 中的伴生对象之外访问私有 fun?

在我看来,私有函数只能在类内部访问,但在我的示例中bindPreferenceSummaryToValue(findPreference("RestoreItem")),可以访问伴生对象外部的以下代码。为什么?

代码

class UIPreference : AppCompatPreferenceActivity() {

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

        fragmentManager.beginTransaction().replace(R.id.content, MyPreferenceFragment()).commit()

        setControl()
        utility.setAD(adView)
    }


    class MyPreferenceFragment : PreferenceFragment() {

        private lateinit var mContext: Context

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            addPreferencesFromResource(R.xml.mypreference)
            mContext=this.activity
            setPreference()

            bindPreferenceSummaryToValue(findPreference("RestoreItem"))
        }
     }


     companion object {
        private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value ->
            val stringValue = value.toString()
            if (preference is ListPreference) {
                val listPreference = preference
                val index = listPreference.findIndexOfValue(stringValue)

                preference.setSummary(
                        if (index >= 0)
                            listPreference.entries[index]
                        else
                            preference.summary) …
Run Code Online (Sandbox Code Playgroud)

android kotlin

1
推荐指数
1
解决办法
5314
查看次数

如何在kotlin中简化代码?

代码A中有许多重复的代码,我希望简单地说,但代码B不起作用,我该如何解决?谢谢!

代码A.

aMDetail?.findByDeviceDef<BluetoothDef>()?.setDevice(mContext)
aMDetail?.findByDeviceDef<WiFiDef>()?.setDevice(mContext)
aMDetail?.findByDeviceDef<ScreenDef>()?.setDevice(mContext)
Run Code Online (Sandbox Code Playgroud)

代码B.

with(aMDetail?){
    findByDeviceDef<BluetoothDef>()?.setDevice(mContext)
    findByDeviceDef<WiFiDef>()?.setDevice(mContext)
    findByDeviceDef<ScreenDef>()?.setDevice(mContext)
}
Run Code Online (Sandbox Code Playgroud)

android kotlin

1
推荐指数
1
解决办法
74
查看次数

为什么我需要在Kotlin之前添加空格?

在下面的代码中,我必须在=之前添加空格,为什么?

我认为private val listofMDetail: MutableList<MDetail>= (之前没有空格=)会没问题,但事实上,Android Studio 3.1.3给了我一个错误.

  private val listofMDetail: MutableList<MDetail> =           //I have to add space before =
            try{
                myGson.fromJson<MutableList<MDetail>>(mJson)?: mutableListOf<MDetail>()  //Load
            }catch(e:Exception) {
                e.message?.let{ logError("Paser: "+it)}
                throw Exception(e)
            }
Run Code Online (Sandbox Code Playgroud)

android kotlin

1
推荐指数
1
解决办法
80
查看次数

为什么我可以在Kotlin中不传递参数名称的情况下调用乐趣?

在函数joinToString中有4个带默认值的参数,在我看来,当我省略参数名时我应该按顺序传递参数值.

所以我认为守则 println(letters.joinToString( transform={ it.toLowerCase() } ) )是对的.

但实际上守则println(letters.joinToString { it.toLowerCase() } ) 也是对的,为什么呢?

fun <T> Collection<T>.joinToString(
        separator: String = ", ",
        prefix: String = "",
        postfix: String = "",
        transform: (T) -> String = { it.toString() }
): String {
    val result = StringBuilder(prefix)

    for ((index, element) in this.withIndex()) {
        if (index > 0) result.append(separator)
        result.append(transform(element))
    }

    result.append(postfix)
    return result.toString()
}


fun main(args: Array<String>) {  
    val letters = listOf("Alpha", "Beta")

    println(letters.joinToString { it.toLowerCase() } )               //It's Ok …
Run Code Online (Sandbox Code Playgroud)

android kotlin

1
推荐指数
1
解决办法
77
查看次数

关于Google Play目标API级别要求的问题

从文章https://developer.android.com/distribute/best-practices/develop/target-sdk

从 2018 年 8 月 1 日起,Google Play 将要求新应用至少面向 Android 8.0(API 级别 26),并且从 2018 年 11 月 1 日起,应用更新将面向 Android 8.0。

以下代码来自我的应用程序。

1:是否意味着targetSdkVersion必须大于或等于26?

2:这是否意味着 minSdkVersion 可以是 21 ?

代码

defaultConfig {

        applicationId "info.dodata.mirror"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 9
        versionName "1.09"
        archivesBaseName = "My-V" + versionName
    }
Run Code Online (Sandbox Code Playgroud)

android

1
推荐指数
1
解决办法
2264
查看次数

如何在 Android Studio 3.3.1 中强制推送到 GitHub 中的远程存储库?

我在 Android Studio 3.3.1 中为我的项目使用 Github 我使用以下代码返回本地存储库和远程存储库。

第 1 行可以在 Android Studio 3.3.1 IDE 中启动。

  1. 第 2 行可以在 Android Studio 3.3.1 IDE 中启动吗?如果是这样,我该怎么办?

  2. 还有,是不是说当我使用force参数push时,remote的内容会覆盖remote的内容而不合并?

代码

git reset --hard <commit_hash>
git push origin <branch_name> --force
Run Code Online (Sandbox Code Playgroud)

致陈杰诺:谢谢!

但是强制推送被禁用,您可以看到下图。我在 Windows 10 操作系统中使用 Android Studio 3.3.1。

图片 在此处输入图片说明

git github android-studio

1
推荐指数
1
解决办法
2750
查看次数

为什么在我使用了 LiveData 后还需要启动 notifyDataSetChanged()?

我正在通过https://github.com/googlecodelabs/android-room-with-a-view/tree/kotlin的示例项目 RoomWordsSample 学习 Room

以下代码来自项目。

在我看来,如果观察到数据发生变化,LiveDate 将自动更新 UI。

但是在文件 WordListAdapter.kt 中,我发现notifyDataSetChanged()添加到function setWords(words: List<Word>)? 似乎它必须在数据更改时手动通知 UI。

为什么还需要启动 notifyDataSetChanged()当我使用 LiveData 时,?

主活动.kt

class MainActivity : AppCompatActivity() {

    private val newWordActivityRequestCode = 1
    private lateinit var wordViewModel: WordViewModel

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

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
        val adapter = WordListAdapter(this)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)

        wordViewModel = ViewModelProvider(this).get(WordViewModel::class.java)


        wordViewModel.allWords.observe(this, Observer { words ->         
            words?.let { adapter.setWords(it) }
        })

    }
}
Run Code Online (Sandbox Code Playgroud)

WordViewModel.kt …

android kotlin android-livedata android-jetpack

1
推荐指数
1
解决办法
584
查看次数

我应该在使用 viewModel 时添加 binding.lifecycleOwner=this 吗?

在我看来,我应该binding.lifecycleOwner=this在使用viewModel.

我发现很多项目比如Code A都没有加binding.lifecycleOwner=this,为什么?

代码 A 来自项目https://github.com/enpassio/Databinding

代码 A

class AddToyFragment : androidx.fragment.app.Fragment() {

    private lateinit var binding: AddToyBinding
    ...

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(
            inflater, R.layout.fragment_add_toy, container, false
        )

        setHasOptionsMenu(true)

        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        (requireActivity() as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)

        //If there is no id specified in the arguments, then it should be a new toy
        val chosenToy : ToyEntry? = arguments?.getParcelable(CHOSEN_TOY)

        //Get …
Run Code Online (Sandbox Code Playgroud)

android android-jetpack

1
推荐指数
1
解决办法
2912
查看次数

为什么抽象类可以成为 Kotlin 中的实例?

以下代码来自项目https://github.com/android/sunflower

在我看来,抽象类不能被实例化,AppDatabase代码A中是抽象类。

为什么代码B可以实例化抽象类AppDatabase

代码A

...
abstract class AppDatabase : RoomDatabase() {
    abstract fun gardenPlantingDao(): GardenPlantingDao
    abstract fun plantDao(): PlantDao

    companion object {

        // For Singleton instantiation
        @Volatile private var instance: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {
            return instance ?: synchronized(this) {
                instance ?: buildDatabase(context).also { instance = it }
            }
        }

    ...
}
Run Code Online (Sandbox Code Playgroud)

代码B

fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase {
     return AppDatabase.getInstance(context)
}
Run Code Online (Sandbox Code Playgroud)

kotlin

1
推荐指数
1
解决办法
103
查看次数