2013-07-09

【Android】TextViewにonClickイベントを付与する

Android4.2にて。 TextView属性にXMLファイルからonClick属性を付与したもののクリックイベントが発動しなかった。Buttonなどでは普通に動いていたので、TextViewに原因があるようだった。

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Test"
    android:onClick="testToast" />
// アクティビティ
public void testToast(View view) {
    Toast.makeText(getApplicationContext(), "Test OK!", Toast.LENGTH_SHORT).show();
}

→クリックイベントが発動しない

これの解決策は、TextViewのandroid:clickable属性にtrueを与えること。

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Test"
    android:clickable="true"
    android:onClick="testToast" />

これで、TextViewでもクリックイベントが発動するようになる。

※参考 http://yuubiseiharukana.blog.shinobi.jp/Entry/561/