Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android View Parameter for OnClickListener Method

please dont mind if stupid question but please i need to clear my confusion ..

For OnClickListener on a button in android i did put this in main.xml

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:text="Button"
    android:onClick="clicked"
/>

and in java file i did

  public void clicked(View v)
  {
   //  my code here 
  }

my question is why we need to pass View view when we call clicked method .

like image 373
Sikander Avatar asked Mar 31 '13 19:03

Sikander


2 Answers

AFAIK,

Because method is called without getting the Button in onCreate. And in order to access that Button you need to have a view.

i.e View v represents your button view.

If you want to access button , suppose you want to get text on It. How do you get it without getting button by using findViewbyId ? you will get your button like this

Button b=(Button)v;

To get the text

String text=b.getText();

So here we are not getting the button by using findViewById

In general if you want to access the button you need to get that object. But here you'll get that from the view. Without using findViewById.

like image 154
Pragnani Avatar answered Oct 21 '22 08:10

Pragnani


The first reason comes in my mind is that you could attach several views to the same method and using v.getId() you could behave according to the view which was pressed.

Generally speaking, having the view related to the event might be useful for several reasons such as changing some of its attributes.

like image 23
fedepaol Avatar answered Oct 21 '22 09:10

fedepaol