0

I want to add some extra data that is not found in the ImageButton in the xml resource file and to be able to read it through the code

just like that

<ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            app:angle="0"
            app:titletext="imageButton1"/>

where can I define these data to be accessable and not cause an error in XML

Thanks in Advance

Amira Elsayed Ismail
  • 9,216
  • 30
  • 92
  • 175

3 Answers3

1

I don't think it's possible in Android SDK. Because ImageButton elements need to be predefined.

What kind of data do you need to define and why do you want to define in xml? Is strings.xml not enough?

Ogulcan Orhan
  • 5,170
  • 6
  • 33
  • 49
  • each button will change the text of textview and i have many buttons so i want to define an extra propriety and attach it to the button to be able to get it through the code – Amira Elsayed Ismail Feb 12 '12 at 22:00
  • erm each button already has this... android:id="@+id/imageButton1" so the id is: "imageButton1"? You can access it in code ImageButton myButton = (ImageButton) findViewById(R.id.imageButton1); – Graham Smith Feb 12 '12 at 22:20
1

There is a defined way in Android to do this by defining your own namespace in XML and then reading the values in code by reading the attributes passed in when the object is created.

I am not going to go into this in huge detail as this question has been asked before and there are lots of good articles on it.

You might want to read the following articles:

Community
  • 1
  • 1
Graham Smith
  • 25,627
  • 10
  • 46
  • 69
0

Instead of looking for hiding data in ImageButton, you can subclass it and have your own data field, and if you still want to use ImageButton have a wrapper class for it which has a ImageButton as field variable, like this:-

class ButtonWrapper{
   ImageButton button;
   int app_angle=0;
   String app_titletext="imageButton1"
}
0xC0DED00D
  • 19,522
  • 20
  • 117
  • 184
  • This is great, but after I declare my own button wrapper can I use this new type to declare UI element in main.xml file? and if yes How to do that ? – Amira Elsayed Ismail Feb 12 '12 at 22:13
  • The class button wrapper is just a wrapper, you can use the actual ImageButton and instead of using object of ImageButton, you can use buttonWrapper(object of wrapper).button to access the button. If u want to set the field app_angle, you can use app_angle=10 or the setter if you prefer encapsulation. There's only one way to use XML for that, creating your own custom ImageButton and that is not worth the extra code, cause you just want to have some extra fields. – 0xC0DED00D Feb 12 '12 at 22:48