Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reference to Views in my Android Activity

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.

like image 559
Tim Avatar asked Dec 29 '22 00:12

Tim


2 Answers

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

like image 95
ingsaurabh Avatar answered Jan 15 '23 04:01

ingsaurabh


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
}
like image 43
Octavian A. Damiean Avatar answered Jan 15 '23 03:01

Octavian A. Damiean