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 でもクリックイベントが発動するようになる。