Instead of a huge set of calls to findViewById I rather like to use the onClick="methodName" xml attribute. For instance:
<LinearLayout ...> <Button android:text="1" onClick="onButtonClicked" clickable="true" /> <Button android:text="2" onClick="onButtonClicked" clickable="true" /> <Button android:text="3" onClick="onButtonClicked" clickable="true" /> <Button android:text="4" onClick="onButtonClicked" clickable="true" /> </LinearLayout>
In the action where the layout is displayed, just add a method
public void onButtonClicked(View v){
You can also put the onClick and clickable attributes in the res / styles.xml file to save even more input:
<?xml version="1.0" encoding="UTF-8" ?> <resources> <style name="clickable_button" > <item name="android:onClick" >onButtonClicked</item> <item name="android:clickable" >true</item> </style> </resources>
Then your layout is simplified to
<LinearLayout ...> <Button android:text="1" style="@style/clickable_button" /> <Button android:text="2" style="@style/clickable_button" /> <Button android:text="3" style="@style/clickable_button" /> <Button android:text="4" style="@style/clickable_button" /> </LinearLayout>
Rodja source share