An example analysis of Button control in Android programming

  • 2020-09-16 07:46:36
  • OfStack

This article illustrates the use of Button control in Android programming. To share for your reference, the details are as follows:

1. Button overview

android.widget.Button inherits directly from android.wdiget.TextView.

The direct subclass is CompoundButton.

Indirect subclasses are: CheckBox, RadioButton Switch, ToggleButton.

The Button class represents a button control. The button control can be pressed or clicked by the user to trigger another action.

2. Use of Button

1 Typical usage:


public class MyActivity extends Activity {
   protected void onCreate(Bundle icicle) {
     super.onCreate(icicle);
     setContentView(R.layout.content_layout_id);
     final Button button = (Button) findViewById(R.id.button_id);
     button.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
         // Perform action on click
       }
     });
   }
}

In addition to binding OnClickListener for Button directly in the Activity class, you can also bind triggered methods in XML files via the android:onClick attribute.

Here's an example:


<Button 
   android:layout_height="wrap_content" 
   android:layout_width="wrap_content" 
   android:text="@string/self_destruct" 
   android:onClick="selfDestruct" />

Now, when the user presses this button, the system calls the selfDestruct(View) method in Activity. In order for this method to be effective, the method must be public and accept only one View argument. When a method is called, the control that was clicked is passed into the selfDestruct(View) method as an argument of type View. Such as:


public void selfDestruct(View view) { 
   // Kabloey 
} 

3. XML properties

The XML attribute of Button is basically the same as TextView1. For those who are interested, please refer to the relevant documents on this site.

4. public method is commonly used

Common public method of Button is basically the same as TextView1.

I hope this article has been helpful in Android programming.


Related articles: