2

当我选择在可点击的 TextView 上使用 onClick 调用函数时,如何让函数知道哪个 TextView 调用了它?

例如,当我在 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)

和以下文本视图:

           <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" />

有没有办法让 showHideData(View view) 知道哪个 TextView 调用了它?

谢谢

4

1 回答 1

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

这将返回view被点击的 id。所以你可以使用一个switch语句

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;
}
于 2013-04-03T20:21:37.463 回答