Thursday, December 15, 2011

How to use buttons in Android code

This is how I used to code for buttons.

onCreate() {

..
View silentButton = findViewById(R.id.silent_button);
silentButton.setOnClickListener(this);
....
}

public void onClick(View view) {
switch (view.getId()) {
case R.id.silent_button:
mAudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
case R.id.normal_button:
mAudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
break;

}

And this is how one should code


However, instead of applying an OnClickListener to the button in your activity, you can assign a method to your button in the XML layout, using the android:onClick attribute. For example:

 

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

Now, when a user clicks the button, the Android system calls the activity's selfDestruct(View) method. In order for this to work, the method must be public and accept a View as its only parameter. For example:

 public void selfDestruct(View view) {

// Kabloey
}

The View passed into the method is a reference to the widget that was clicked.

I knew this because I have started working on Catroid. Thanks





public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);





0 comments:

Post a Comment