Referencing views with the same id in different la

2019-04-26 21:18发布

问题:

In my Android project I have two layouts: num_info and num_info_pack. Both have views with id "circle". So I thought referencing those views by layout_name.circle would solve the problem:

val inetView = activity.layoutInflater.inflate(R.layout.num_info_pack, parent, false)
    inetView.circle.setBackgroundResource(background)

But circle is underlined with red and it says:

Overload resolution ambiguity. All these functions match.

public val View.circle: View! defined in kotlinx.android.synthetic.main.num_info_pack.view

public val View.circle: RelativeLayout! defined in kotlinx.android.synthetic.main.num_info_inet_plus_pack.view

Why is it confused about which circle I'm talking about if I'm specifically saying inetView.circle?

回答1:

The solution here is in the imports. You must be importing two layouts like

import kotlinx.android.synthetic.main.num_info_pack

and

import kotlinx.android.synthetic.main.num_info_inet_plus_pack

Remove one of them and keep one with the appropriate layout file that you want to import. It should work fine.



回答2:

In addition to the already very good answers, if you have the same IDs in multiple layouts in your project, it shouldn't matter which one you pick. Similar IDs, regardless of which layout it is defined, end up pointing to the same view. So, you can discard the other imports, leaving only the layout(s) that matters to you in the current activity/fragment/view

Hope that helps



回答3:

I don't have android studio in hand now but I think this will solve your problem:

package XXX

import kotlinx.android.synthetic.main.num_info_inet_plus_pack.view.circle as inetViewCircle
import kotlinx.android.synthetic.main.num_info_pack.view as circle
//...
val inetView = activity.layoutInflater.inflate(R.layout.num_info_pack, parent, false)
inetViewCircle.setBackgroundResource(background)

Don't know if this will works because I can't test it right now. Please let me know whether it's working.

The problem is a name clash, so I think import alias may help.