Button and Image Button

The Button View is just a button, printed with some text to identify it, that the user can click to invoke some action. The previous section created a Button and connected it to an OnClickListener method that executes when the Button is clicked.

Android has a very visual, mobile-oriented user interface, so you might want to use a button with an image on it rather than one with text. Android provides the ImageButton View for just that purpose. You can adapt Example 11-2 to use an ImageButton by making one change in the XML file and another in the Java code:

1. In main.xml, replace the Button definition for btnDone with an ImageButton:

<ImageButton android:id="@+id/btnDone" android:layout_width="wrap_content" android:layout_height="wrap_content" />

2. In TextViewDemo.java, redefine btnl as an ImageButton and add a line to set the image to a PNG image in the drawable directory:

private static ImageButton btnl;

/** Called when the activity is first created. */ ^Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

//Get pointers to the Views defined in main.xml txtl = (TextView) findViewById(R.id.txtDemo); etxtl = (EditText) findViewById(R.id.eTxtDemo); btnl = (ImageButton) findViewById(R.id.btnDone);

//Set the image for the Done button btnl.setImageResource(R.drawable.log);

The button now appears as shown in Figure 11-2.

QSGUO 7:44 PM

Figure 11-2. Text boxes with an ImageButton

0 0

Post a comment