Search code examples
androideclipsetextviewclickable

How can a function know which clickable textView has called it with onClick?


When I choose to call a function with onClick on a clickable TextView, how do I get the function to know which TextView has called it?

For example, when I have this in my MainActivity.java:

public void showHideData(View view)
{
    //Log.v("showHideDataA: ",  "Calling package null, local class name: " + this.getLocalClassName() + " request orientation: " + ("" + this.getRequestedOrientation()));
    if (findViewById(R.id.letterContentTextViewArrayB).getVisibility() == View.VISIBLE)
    {
        findViewById(R.id.checkedB).setVisibility(View.GONE);
        findViewById(R.id.notcheckedB).setVisibility(View.VISIBLE);
        findViewById(R.id.letterContentTextViewArrayB).setVisibility(View.GONE);
    }
    else
    {
        findViewById(R.id.checkedB).setVisibility(View.VISIBLE);
        findViewById(R.id.notcheckedB).setVisibility(View.GONE);
        findViewById(R.id.letterContentTextViewArrayB).setVisibility(View.VISIBLE);
    }
} // end of showHideData(0)

and the following TextViews:

           <TextView 
                android:id="@+id/firstLetterTextViewArrayA"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btn_a_label"
                android:clickable="true"
                android:onClick="showHideData"/>
           <TextView 
                android:id="@+id/firstLetterTextViewArrayB"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btn_b_label"
                android:clickable="true"
                android:onClick="showHideData" />

is there a way to get showHideData(View view) to know which TextView called it?

Thank you


Solution

  • public void showHideData(View view)
    {
         view.getId();
         ...
    }
    

    this will return the id of the view that was clicked. So you can use a switch statement

    public void showHideData(View view)
    {
        switch (view.getId()) {
            case R.id.firstLetterTextViewArrayA:
            // logic for this button
            break;
            case R.id.firstLetterTextViewArrayB:
            // logic for this button
            break;
    }