1

I am building a custom view. I am able to successfully get resources using format="reference". However, I now want to pass the id of another view as an attribute and I want following restrictions on that similar to the relative layout.

  1. This must be id or reference to a view - not drawable or color or any other value.
  2. the layout with the id that is supplied must exist inside the current XML file.
  3. I should be able to get a reference to that view and should be able to pass that view to other methods.

For example in relative layout, if you enter layout_below = "@id+/someid" and if someid isn't suitable it shows warning or error.

How to achieve this, please help.

Update

This is how i define the attribute

<attr name="myView" format="reference"/>
<attr name="dimen" format="dimension"/>

this is how I define view in layout xml

....
xmlns:custom="http://schemas.android.com/apk/res-auto"
.....
<myPackage.mycustomView android:id = "@+id/myId"
     custom:dimen = "10dp" ///-- this one works fine
     custom:myView = "@+id/id_of_another_view_in_xml" //-- I am not able to retrive this view
     ....
/>
Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
  • https://stackoverflow.com/questions/3277196/can-i-set-androidlayout-below-at-runtime-programmatically i guess this could somehow will elaborate your problem. – Raza Dec 08 '18 at 05:34
  • Thanks but I don't find any relevance, what I am doing is creating my own custom view. – Mayank Kumar Chaudhari Dec 08 '18 at 05:37
  • okay i understand. You are creating your own view type like relativelayout with such properties. – Raza Dec 08 '18 at 05:39

1 Answers1

2

This must be id or reference to a view - not drawable or color or any other value.

When you specify an attribute for your custom view in an attrs.xml file for an ID, all you need is the reference type.

the layout with the id that is supplied must exist inside the current XML file.

The red warning you see in Android Studio when you enter an invalid ID is a lint warning. If the ID does exist, just not in the layout file, it will still compile.

If you want to achieve the same thing for you custom view, you probably need to add your own lint rule.

I should be able to get a reference to that view and should be able to pass that view to other methods.

Not entirely sure what you're asking. Once you've inflated the custom view and obtained the values from the XML attributes, you should have the ID reference, which you can then use in the custom view to do a findViewById. If that doesn't answer your question, please clarify.

EDIT: Code example, inside your custom view constructor:

mIdReference = a.getResourceId(R.styleable.MyCustomView_my_view, 0)
if (mIdReference != 0) {
    View subView = findViewById(mIdReference)
}

Hope that helps!

dominicoder
  • 9,338
  • 1
  • 26
  • 32