java - Is there a way in android to set a field via xml android:id into a custom view -


for instance have custom button , want connect seekbar:

public class seekbarbutton extends imagebutton {      seekbar seekbar;      public seekbarbutton(context context) {         super(context);     }      public seekbarbutton(context context, attributeset attrs) {         super(context, attrs);     }      public seekbarbutton(context context, attributeset attrs, int defstyleattr) {         super(context, attrs, defstyleattr);     }      public void setseekbar(seekbar seekbar) {         this.seekbar = seekbar;     }      public seekbar getseekbar() {         return seekbar;     } } 

i can in code:

sbb = (seekbarbutton) rootview.findviewbyid(r.id.minus_red); sbred = (seekbar) rootview.findviewbyid(r.id.sbred); sbb.setseekbar(sbred); 

but 8 buttons give lot of boilerplate, , want like:

    <com.whatever.views.seekbarbutton         ...         whattoputhere:seekbar="@+id/sbred"  // this? whattoputhere?         android:id="@+id/minus_red" />      <seekbar         android:id="@+id/sbred"          ... /> 

the easiest way create custom viewgroup contains both button , seekbar. if cannot that, reason, here's solution:

there few steps make work. first must define custom xml attribute can reference , use.

edit (or create) res/values/attrs.xml. add:

<declare-styleable name="seekbarbutton">     <attr name="seekbarid" format="integer" /> </declare-styleable> 

then, in seekbarbutton, call constructors:

private void init(context context, attributeset attrs, int defstyleattr) {     if (attrs != null) {         typedarray = context.obtainstyledattributes(attrs,                 r.styleable.seekbarbutton, defstyleattr, 0);         mseekbarid = a.getresourceid(r.styleable.seekbarbutton_seekbarid, 0);         a.recycle();     } } 

finally, in root viewgroup of layout file, add

xmlns:app="http://schemas.android.com/apk/res-auto" 

then,

<com.whatever.views.seekbarbutton     android:id="@+id/minus_red"     app:seekbarid="@+id/sbred"     ... />  <seekbar     android:id="@+id/sbred"     ... /> 

note need call ((viewgroup) getparent()).findviewbyid(mseekbarid) in seekbarbutton instantiate seekbar, getparent() null in seekbarbutton constructors. so, delay findviewbyid() until need seekbar.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -