为什么 getId 不起作用

why getId doesn't work

我在寻找线性布局的 id child 但是当调用 getid 时它是 return -1

这是我的代码。

LinearLayout layout = (LinearLayout)findViewById(R.id.schedul1);
    for (int i = 0; i < layout.getChildCount(); i++) {
        View child = layout.getChildAt(i);
        int id=layout.getChildAt(i).getId();

我跟踪发现 child 变量不为空,而是 getId return -1。 为什么? 关于获取线性布局视图 child 的 ID 的任何建议。

除非您在布局中设置每个视图的 ID XML,或者当您以编程方式创建 View 时,它将 return 默认值 (-1)。

Views may have an integer id associated with them. These ids are typically assigned in the layout XML files, and are used to find specific views within the view tree.

http://developer.android.com/reference/android/view/View.html

Android 源代码中 getId() 的 javadocs 也清楚地说明了这种行为:

a positive integer used to identify the view or NO_ID if the view has no ID

http://developer.android.com/reference/android/view/View.html#getId()

接着,NO_ID等于-1:

http://developer.android.com/reference/android/view/View.html#NO_ID