I have a LinearLayout
comprising of a few Button
s and I add this to my activity in the onCreate(..)
method with setContentView(R.layout.myscreen)
. No surprises so far.
How do I get a reference to an iterator to these buttons? I'd like to add listeners to them but I'd rather not directly reference the Button's using their android:id
.
Similar questions have been asked here and here but they don't quite answer my question.
Try something like this provide an id root_layout in xml to LinearLayout
LinearLayout mLayout = (LinearLayout) findViewById(R.id.root_layout);
for(int i = 0; i < mLayout.getChildCount(); i++)
{
Button mButton = (Button) mLayout.getChildAt(i);
mButton.setOnClickListener(this);
}
Where mLayout is object of you Linear Layout and Your activity must implements OnClickListener
and here goes general listener
@Override
public void onClick(View v)
{
Button mButton = (Button)v;
String buttonText = mButton.getText().toString();
}
NOTE: For this to work properly you Linear Layout must only contains button no other views
You should take a look at my answer here.
In short. I'd assign the buttons a listener by setting the onClick
attribute in the XML layout on each Button
.
Inside of your Activity
you'll need a public method like the one below which basically is what you want to do in your listener.
public void myFancyMethod(View v) {
// do something interesting here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With