Here is an example for multiple buttons, even we can handle multiple buttons with single method(onClick(View)) or with unanimous object of OnClickListener interface,
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity" >
<Button
android:id="@+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_save" />
<Button
android:id="@+id/button_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_cancel" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Multiple Buttons Example</string>
<string name="button_save">Save</string>
<string name="button_cancel">Cancel</string>
</resources>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity" >
<Button
android:id="@+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_save" />
<Button
android:id="@+id/button_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_cancel" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Multiple Buttons Example</string>
<string name="button_save">Save</string>
<string name="button_cancel">Cancel</string>
</resources>
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.swamy.multiplebuttonsexample.R;
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_save = (Button) findViewById(R.id.button_save);
Button button_cancel = (Button) findViewById(R.id.button_cancel);
button_save.setOnClickListener(this);
button_cancel.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_save:
Toast.makeText(getApplicationContext(),
"You have clicked on Save button", Toast.LENGTH_SHORT)
.show();
break;
case R.id.button_cancel:
Toast.makeText(getApplicationContext(),
"You have clicked on Cancel button", Toast.LENGTH_SHORT)
.show();
break;
}
}
}
No comments:
Post a Comment