Question

I have an idea to set android:onClick="myClickMethod" for several TextView's.

<TextView
    android:id="@+id/search_suggestion_1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:onClick="myClickMethod"                
    android:clickable="true"/>

<TextView
    android:id="@+id/search_suggestion_2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:onClick="myClickMethod"                
    android:clickable="true"/>

<TextView
    android:id="@+id/search_suggestion_3"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:onClick="myClickMethod"                
    android:clickable="true"/>

How can i differ from which TextView myClickMethod() is called?

Was it helpful?

Solution

you can do it by using the id's of each text-view. Use Switch-Case inside your myClickMethod based on text-view Id's. Also you can differentiate text-views by tag's.

OTHER TIPS

You can set a tag for each of them. This way, for example, for the first View use android:tag="1" and so on.

In your onClick method, simply use v.getTag() and you'll able to distinguish them.

You can use a simple switch case

public void myClickMethod(View v)
{
  switch(v.getId()) /
  // id is an int value. use getId to get the id of the view
  {
         case R.id.search_suggestion_1:
             // search suggestion 1
         break 
         case R.id.search_suggestion_2 :
             // search suggestion 2
         break; 
         case R.id.search_suggestion_3:
             // search suggestion 3
         break;
  }
} 

when you make a function in activity like:

public void onClickMethod(View view){
//Input argument is the view on which click is fired.
//Get id of that view

int id = view.getId();

switch(id){
// your logic
}
}
public void myClickMethod(View v)
{
  switch(v.getId())
  {

    case R.id.search_suggestion_1:
   //code here
     break;
    case R.id.search_suggestion_2:
   //code here
     break;
    case R.id.search_suggestion_3:
   //code here
    break;
    default: break;
  }
} 

You can use switch-case to make decision which Textview is pressed by comparing their id.

public void myClickMethod(View v) {

    switch(v.getd()) {

        case R.id.search_suggestion_1:
           //code here
           break;

        case R.id.search_suggestion_2:
           //code here
           break;

       case R.id.search_suggestion_3:
          //code here
          break;
   }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top