`Anko`给出异常AnkoException:未设置ID

时间:2018-08-29 09:57:01

标签: android kotlin anko

我正在尝试使用Anko学习设计布局。我已经使用Anko设置了布局,如下所示

relativeLayout {
        val counterTextView = textView {
            text = "0"
            textSize = 24f

        }
        button {
            onClick {
                count++
                counterTextView.text = count.toString()
            }
        }.lparams {
            below(counterTextView)
        }
    }

我只需要一个相对的布局,其中包含一个TextView和一个位于TextView下方的按钮。

上面的代码给出以下错误

     Caused by: org.jetbrains.anko.AnkoException: Id is not set for android.widget.TextView{d8dedcd V.ED..... ......ID 0,0-0,0}
    at org.jetbrains.anko.RelativeLayoutLayoutParamsHelpersKt.below(RelativeLayoutLayoutParamsHelpers.kt:60)
    at com.example.app.MainActivity.onCreate(MainActivity.kt:29)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)

有人知道如何解决吗?

1 个答案:

答案 0 :(得分:1)

我认为,如果您想使用relativeLayout参数,则必须为视图的真实感创建ID,所以请尝试

relativeLayout {
    val counterTextView = textView {
        id = R.id.counterTextView // add this line
        text = "0"
        textSize = 24f

    }
    button {
        onClick {
            count++
            counterTextView.text = count.toString()
        }
    }.lparams {
        below(counterTextView)
    }
}

并且您必须在值文件夹中创建ids.xml

ids.xml

<resources>
    <item name="counterTextView" format="integer" type="id"/>
</resources>