EliSys EliSys - 3 months ago 7
Android Question

2 (or more) button views for the same onClick method

I'm a novice android developper and was wondering:

Could I have 2 buttons to be linked into the same, 1 onClick method (which i'll presumably override to accept 2 extra parameter, int btnId and View targetTextView for instance) in order to decide which button is calling the method and then which TextView text to update?

For Example:
btn1 will update the text on text_view_1

and btn2 will update text_view_2.

Except they we will be linked to the same method:

public void generalOnClick(View view, String btnId, String textViewId){...}

Answer
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<TextView
    android:id="@+id/one"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="One"
    android:onClick="btnClick"/>

<TextView
    android:id="@+id/two"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Two"
    android:onClick="btnClick"/>

</LinearLayout>

Button Click Function in your Activity

public void btnClick(View view) {
    TextView tv = (TextView)view;
    int id = tv.getId();
    if(id==R.id.one) {
        tv.setText("One Clicked");
    } else if(id==R.id.two){
        tv.setText("Two Clicked");
    }
}