开发者

Store additional info with button

开发者 https://www.devze.com 2023-03-01 03:23 出处:网络
How can I attach additional information to a button programmatically? I can mButton.setText(\"new text\") to change the text but I want to be able to add a few more fields so that when you click the b

How can I attach additional information to a button programmatically? I can mButton.setText("new text") to change the text but I want to be able to add a few more fields so that when you click the button you can grab those extra fields and use the data. How mig开发者_如何学运维ht I do that?


Use View.setTag(int key, Object tag).

You can retrieve it later with getTag(int key).

In your xml:

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

In your code:

//I'd like to store String s and Boolean b in the button.
button.setTag(R.id.string_key, s);
button.setTag(R.id.boolean_key, b);

//Now, I'd like to retrieve the data in new fields.
String new_s = (String) button.getTag(R.id.string_key);
Boolean new_b = (Boolean) button.getTag(R.id.boolean_key);


You can always extend Button class and add the fields and methods you need


you can use the Tag property. assign a string to it[ if you have more than one value use the pipe character (|) and split it later on] or you can assign an object.

0

精彩评论

暂无评论...
验证码 换一张
取 消