Get reference to Views in my Android Activity

12,769

Solution 1

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

Solution 2

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
}
Share:
12,769
Tim
Author by

Tim

Updated on June 04, 2022

Comments

  • Tim
    Tim almost 2 years

    I have a LinearLayout comprising of a few Buttons 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.

  • Tim
    Tim about 13 years
    Thank you for your reply Octavian. Didn't know about that XML setting.However in attempting to keep the initial question short and clear I left out the fact that I also want to attach an onLongClickListener and OnFocusChangeListener to the buttons so I still need to get a reference to the buttons. As a last resort I can just directly reference the Buttons using their android:id but it's a little inflexible. Any ideas? cheers
  • Tim
    Tim about 13 years
    Thank you Tox1c. I hate asking this question but how do you access the Layout from an Activity? This is one of the things that I hate in Android - I know something is in there somewhere to do something but because the API is so vast I just can't find it. There is a setContentView(..) method but no getContentView(..)
  • Tim
    Tim about 13 years
    btw octavian.. I've tried to also vote your answer up as it is useful also but its not letting me as I was messing around. Can you just edit it slightly (add whitespace) so I can re-vote.
  • Veer Shrivastav
    Veer Shrivastav over 11 years
    I used following code: textView.setText(message); worked in my case... may come to your help.
  • Lay González
    Lay González over 9 years
    If I pretend to keep a reference to the view for the whole life of the activity, should I use a weakreference or nah