Reputation: 3059
Is there a way to set one click listener on all views in a hierarchy in one line? I believe we have to do something like the following:
<LinearLayout id="@+id/parent">
<TextView id="@+id/item1" />
<TextView id="@+id/item2" />
<TextView id="@+id/item3" />
</LinearLayout>
OnClickListener listener = ...;
View view = inflater.inflate(R.layout.the_above_layout);
view.setOnClickListener(listener);
view.findViewById(R.id.item1).setOnClickListener(listener);
view.findViewById(R.id.item2).setOnClickListener(listener);
view.findViewById(R.id.item3).setOnClickListener(listener);
...
But that's really a lot of code for a big view hierarchy. I could make a recursive function to do it, but is there something already available by android that does this for us?
Thanks
Upvotes: 0
Views: 1854
Reputation: 2483
Well, this is the way add this line in your xml-
<TextView id="@+id/item1"
android:onClick="myMethod"
/>
And make sure you write this method in your class in which xml is used
public void myMethod(View v){
//content goes here
}
this will trigger your own methods
Upvotes: 0
Reputation: 513
Android just implements the OnClickListener for you when you define the android:onClick="someMethod" attribute in xml.
<LinearLayout id="@+id/parent">
<TextView id="@+id/item1" android:onClick="myFancyMethod" />
<TextView id="@+id/item2" android:onClick="myFancyMethod" />
<TextView id="@+id/item3" android:onClick="myFancyMethod" />
</LinearLayout>
Then in your Activity just define a method like this.
public void myFancyMethod(View v) {
// does something very interesting
}
That is probably the fastest way to do it.
Upvotes: 2
Reputation: 2289
that is nice example i think so bcz i m also finding shortest way to clici refer this site for click listner
public class MyActivity extends Activity implements View.OnClickListener {
Button button1, button2, button3;
@Override
public void onCreate(Bundle bundle) {
super.onCreate();
...
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
// do stuff;
break;
case R.id.button2:
// do stuff;
break;
...
}
}
Upvotes: 0