androidandroid-buttonandroid-custom-attributes

In Android how to I set a custom attribute with new Button()?


I'm declaring a button using:

Button btn = new Button(this);
btn.setText(itemSet[i]);
btn.setId(i);

I need to add a custom attribute that will be used upon click.

Is there a way to accomplish this?


Solution

  • You can attach any data as a tag of the button using setTag.

    String attribute = "Hello";
    btn.setTag(attribute);
    

    You can then get back the tag later with getTag.

    String attribute = (String) btn.getTag();
    

    If you need to bind multiple values to a View, declare IDs in values/tags.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <item name="tag_first" type="id" />
        <item name="tag_second" type="id" />
    </resources>
    

    And use them as the first parameter of setTag.

    btn.setTag(R.id.tag_first, "First");
    btn.setTag(R.id.tag_second, "Second");
    

    You can then get the bound values as follows:

    String first = (String) btn.getTag(R.id.tag_first);
    String second = (String) btn.getTag(R.id.tag_second);