Button Controls
• Types of button controls:
• The basic button, the image button, and the toggle button
The Button Control
• The basic button class in Android is android.widget.Button
Xml code
• <Button
android:id="@+id/button1"
android:text="@string/basicBtnLabel"
android:layout_width=“match_parent"
android:layout_height="wrap_content" />
Button Controls
• onClick:- when user clicks a button.
• Add android:onClick attribute to button in xml
• Value of attribute is the name of method to call on click
android:onClick=“sendMessage”
//called when user touches the button
public void sendMessage(View view){
//do button click actions
}
• Another method
• Declare event handler programmatically
• btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//do something
}
}
• The ImageButton Control
• Android provides an image button via android.widget.ImageButton.
xml
• <ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content“
android:layout_height="wrap_content"
android:onClick="myClickHandler"
android:src="@drawable/icon" />
Java
• ImageButton imageButton2 = (ImageButton)this.findViewById(R.id.imageButton2);
imageButton2.setImageResource(R.drawable.icon);
• Button With text and icon
• <Button
android:id="@+id/button1"
android:layout_width=“match_parent"
android:layout_height="wrap_content“
android:text="@string/button_text“
android:drawableLeft="@drawable/icon" />
• The ToggleButton Control
• ToggleButton control, is a two-state button
• This button can be in either the On or Off state.
• ToggleButton’s default behavior is to show a green bar when in
the On state and a grayed-out bar when in the Off state.
• Default behavior also sets the button’s text to On when it’s in the
On state and Off when it’s in the Off state.
• You can modify the text for the ToggleButton if On/Off is not
appropriate for your application
• <ToggleButton android:id="@+id/cctglBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Stop"
android:textOff="Run"/>