So I'm have two RadioGroups, one for gender, one for unit type. User has to select value for both RadioGroups, but value of first selected group affects the value of secont group.
For example, if user is male and uses metric unit type one layout will be shown to him. If he's male but uses imperial unit, another layout will be shown to him.
My question is, how to have RadioButton onClick method inside of RadioButton onClick method?
Sorry, I don't know how to explain this better.
Here's the code:
public void dialogBodyFatMuskarciRadioButtonKliknut(View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()){
case R.id.radioButtonDialogBodyFatSpolMuski:
if (checked)
public void dialogBodyFatRadioMetrickaJedinica(View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()){
case R.id.radioButtonDialogBodyFatSpolMuski:
if (checked)
}
}
Didnt test this, but you could implement the logic something like this.
In your Manifest:
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gender_RadioGroup"
<RadioButton android:id="#+id/male"
android:text="#string/male"
android:onClick="onGenderRadioButtonClicked"/>
<RadioButton android:id="#+id/female"
android:text="#string/female"
android:onClick="onGenderRadioButtonClicked"/>
</RadioGroup>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/unit_type_RadioGroup"
<RadioButton android:id="#+id/metric_unit_type"
android:text="#string/metric_unit_type"
android:onClick="onMetricRadioButtonClicked"/>
<RadioButton android:id="#+id/imperial_unit_type"
android:text="#string/imperial_unit_type"
android:onClick="onMetricRadioButtonClicked"/>
</RadioGroup>
You would need to maintain the View instance of view_gender and view_unit_type inside your class. onCreate is a good place to do it using findViewById.
protected void onCreate(Bundle savedInstanceState) {
view_gender = (RadioGroup) findViewById(R.id.gender_RadioGroup);
view_unit_type = (RadioGroup) findViewById(R.id.unit_type_RadioGroup);
}
public void onGenderRadioButtonClicked(View view) {
if(((RadioButton) view).isChecked())
chooseLayout(view, view_unit_type );
}
public void onMetricRadioButtonClicked(View view) {
if(((RadioButton) view).isChecked())
chooseLayout(view_gender, view);
}
public void chooseLayout(View View1, View View2){
if (View1.getId()==R.id.male && View2.getId()==R.id.metric_unit_type)
// show male metric type layout
else if (View1.getId()==R.id.male && View2.getId()==R.id.imperial_unit_type)
// show male imperial type layout
else if (View1.getId()==R.id.female && View2.getId()==R.id.metric_unit_type)
// show female metric type layout
else
// show female imperial type layout
}
Related
I was interested in making an APP for Android with 30 personality profile questions, where each question will have two alternatives of choice. I thought about using RadioButton, but since there are 30 questions I would not like to include them all on the screen at once, I would like to display only one question with two alternatives and each selection of one of the alternatives already called the other question.
Is it possible to do this without creating 30 activities?
I saw that it might be possible to do array, but I do not know how to run it from one issue to another.
Thank you so much!!!
This code achieves the required functionality. It is very basic and can be improved as per your need. Simply add this activity and layout to your project.
Java File: This code uses a single layout and recreate the view for next question on Radio Button Click
public class QuestionsActivity extends AppCompatActivity implements
RadioGroup.OnCheckedChangeListener{
LinkedHashMap<String,RadioGroup> questionList;
LinkedHashMap<String,String> answerList;
ArrayList<String> keys=new ArrayList<>();
int keyCounter=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
questionList=new LinkedHashMap<>(); //This Map contains all the questions with two radio button (options)
answerList=new LinkedHashMap<>(); //This Map will contain question along with selected answer.
initQuestions(); //This method will add 30 questions with options
keys.addAll(questionList.keySet());
showQuestions(keys.get(keyCounter));//This method will show the first question
}
private void showQuestions(String key) {
TextView textView=(TextView)findViewById(R.id.tv_question);
textView.setText(key);
LinearLayout layout =(LinearLayout)findViewById(R.id.questionsLayout);
layout.removeAllViews();
RadioGroup rg=questionList.get(key);
rg.setOrientation(LinearLayout.HORIZONTAL);
layout.addView(rg);
rg.setOnCheckedChangeListener(this);
}
private void initQuestions() {
for (int i = 1; i <=3; i++) {
RadioGroup rg=new RadioGroup(this);
RadioButton rb1 =new RadioButton(this);
rb1.setText("Q "+i+" RadioButton 1");
RadioButton rb2 =new RadioButton(this);
rb2.setText("Q "+i+" RadioButton 2");
rg.addView(rb1);rg.addView(rb2);
questionList.put("Question "+i,rg);
}
}
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
RadioButton rb=(RadioButton) findViewById(group.getCheckedRadioButtonId());
if(keyCounter<questionList.size()) {
answerList.put(keys.get(keyCounter),rb.getText().toString()); // Putting the question and selected answer to 'answerList' map.
keyCounter++;
if(keyCounter<questionList.size()) {
showQuestions(keys.get(keyCounter));// showing the next question.
}
}else {
Toast.makeText(this, "You've answered all the questions.", Toast.LENGTH_SHORT).show();
}
for (String s : answerList.keySet()) {
System.out.println("Q--> "+s+", A--> "+answerList.get(s)); // Here you can see all the questions and selected answers on your logs(AndroidMonitor).
}
}
}
layout file : This file contains a textView which will be used to show question and a linear layout which contains the RadioGroup
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="edios.endlessscrollrecycler.QuestionsActivity">
<TextView
android:id="#+id/tv_question"
android:layout_marginTop="10dp"
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:orientation="horizontal"
android:id="#+id/questionsLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"></LinearLayout>
</LinearLayout>
I make a Button and I want to make onClick method in XML
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="#+id/button2"
android:onClick="maysara"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/button"
android:layout_alignStart="#+id/button"
android:layout_marginTop="63dp" />
Then I go to Java code to make the method "maysara"
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void maysara(View v){
**if(v.getId()==findViewById(R.id.button2))**
Toast.makeText(this,"button2",Toast.LENGTH_SHORT).show();}}
But I got an error in if statement >>> I really dont know why #?!
Check the return type of findViewById() which is a view and you are comparing with v.getId() which is id. You should not compare this.
public View findViewById (int id)
Just use like this
public void maysara(View v){
Toast.makeText(this,"button2",Toast.LENGTH_SHORT).show();
}
It help you.
I know this has an answer, but I thought I'd add one.
You are declaring
android:onClick="maysara"
as the onClick method in your xml for this button.
There is no need to do a check on which button is clicking, as you have explicitly defined this in your xml.
So within your mayasara method, you only need to show what you want to do, not a check on the button clicking.
public void maysara(View v){
<Button
android:id="#+id/button1"
android:onClick="maysara"
<Button
android:id="#+id/button2"
android:onClick="maysara"
A switch statement is a much better option, as you do not need to check for the value of R.id.button2 as you have in your if statement. Checking those values for this type of function is a clumsy way of programming.
public void maysara(View v){
switch(v.getId()) {
case R.id.button1:
// to do
break;
case R.id.button2:
// to do
break;
I'm new to programming so I have a really easy question. Since I do not really know the terms I couldn't find any topic on my problem, so excuse me if this question has been asked before.
My problem is as follows: I'm running an app, created with Eclipse, on an Android machine. On the first screen I have just a list of buttons:
layout_main:
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/alpha"
android:onClick="alpha" />
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/beta"
android:onClick="beta" />
If I press a button then the corresponding activity will start. I programmed the main activity as follow in order to do that:
main activity:
public void alpha(View view) {
Intent intent = new Intent(this, AlphaActivity.class);
startActivity(intent); }
public void beta(View view) {
Intent intent = new Intent(this, BetaActivity.class);
startActivity(intent); }
Since I have many buttons, I will have as many times the operation public void as seen above. Isn't there any way to program it more efficient? For example: Start new activity, if alpha was selected then start activity alpha, if beta was selected start activity beta, else do nothing.
You could apply the same listener to each button, not really sure if it's more efficient or even better style, but this will probably work. Something like:
public void buttonListen(View view)
{
Class clas;
int id = view.getId();
switch(id)
{
case R.id.alpha:
clas = AlphaActivity.class;
break;
case R.id.alpha:
clas = BetaActivity.class;
break;
...
case R.id.zeta:
clas = ZetaActivity.class;
break;
}
startActivity(new Intent(this, clas));
}
and assign the corresponding id in the XML as the next answer states.
you can give every button an id like this :
<Button
android:id="#+id/alpha"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/alpha"
/>
<Button
android:id="#+id/beta"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/beta"
/>
then in the main activity you can findviewbyid() to find the two buttons and give buttons onclicklistener,then you implements the onclicklistener like this :
public void onClick(View v) {
Intent i = new Intent();
switch(v.getid()){
case: R.id.alpha:
i.setClass(context,AlphaActivity.class);
break;
case: R.id.beta:
i.setClass(context,BetaActivity.class);
break;
}
startActivity(i);
}
hope that helps.
There are many different ways to achieve this and make it simpler. Not a single method will be "the best". What you are doing is probably down the list of "what I would not do".
Don't assign things in XML, it's harder to work with, cannot be really changed at running time and make it less portable when you have to maintain a lot of different layouts. Instead…
This is just ONE way to do it:
Instead of defining the onClick method in the XML, do it programatically.
Add an android id to your Views:
<Button
android:id="#+id/alpha_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/alpha" />
(the same for all the other buttons)
Note: don't use fill_parent, use match_parent (the former is deprecated and both do the same).
The in your Activity onCreate() method, right before you setContentView(R.layout.your_above_layout_with_the_buttons);
You can obtain a reference to each button:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_above_layout_with_the_buttons);
final TextView alphaButton = (TextView) findViewById(R.id.alpha_button);
//etc for the rest
// now add click listeners:
alphaButton.setOnClickListener(this);// more on this later
betaButton.setOnClickListener(this);
// etc.
}
Now your activity should be:
public class YourActivity extends Activity implements View.OnClickListener {
and somewhere in your activity you have to implement:
#Override
public void onClick(final View view) {
// which button was clicked? Different ways to tell… a simple one:
Intent intent;
switch (v.getId()) {
case R.id.alpha_button:
intent = new Intent(this, AlphaActivity.class);
break;
case R.id.beta_button:
intent = new Intent(this, BetaActivity.class);
break;
//etc.
}
if (intent != null) {
startActivity(intent);
}
}
There are many ways you could accomplish your goal.
Note: the best solution would be to add android:id to your layout file, but if for some reason you can't do that, you could use the button text.
A very simple (although not great) way to do it without changing your layout file much would be to look at the text on the button, if all buttons have unique text, and perform the action based on that.
public void onButtonClick(View view)
{
//Cast the click View into a Button
Button selectedButton = (Button) view;
Intent intent = new Intent();
String buttonText = selectedButton.getText().toString();
if(buttonText.equals("beta"))
{
intent = new Intent(this, BetaActivity.class);
}
else if(buttonText.equals("alpha"))
{
intent = new Intent(this AlphaActivity.class);
}
startActivity(intent);
}
Make sure to set the onClick for each button in the layout file to call this method
android:onClick="onButtonClick"
For your specific situation, you could could change the way you handle the calls from your buttons, for example, you could give the buttons IDs and check the IDs of the buttons in a single method.
<Button
android:id="#+id/alpha_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/alpha"
android:onClick="onButtonClick" />
<Button
android:id="#+id/beta_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/beta"
android:onClick="onButtonClick" />
public void onButtonClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.alpha_button:
intent = new Intent(this, AlphaActivity.class);
break;
case R.id.beta_button:
intent = new Intent(this, BetaActivity.class);
break;
default:
return;
}
startActivity(intent);
}
However, I would suggest that your current code is clear and concise so just leave it as it is. There are many ways to solve a problem, especially when it comes to designing software.
In general though, programming languages try to balance making code (and more importantly it's function or purpose) easy to read/understand while trying to keep the syntax as concise as possible. In time you will learn about the advantages and disadvantages of each language and it's syntax, some will be better at solving certain types of problem while being too verbose for solving others. For now just learn how Java works and try to understand why they have implemented each keyword and syntax element.
I made a very simple test application with one activity and one layout. The onClick doesn't trigger the first time it is pressed, as it should.
The activity:
package com.example.mytest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText ed1 = (EditText) findViewById(R.id.editText1);
ed1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG)
.show();
}
});
}
}
The layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1"
android:ems="10" />
</RelativeLayout>
If you run this application, and click on the second editText and then back on the first one, it will not trigger the onClick. You can keep selecting back and forth and it will not trigger the onClick at all. I need this basic functionality, but haven't been able to think of a way to get it to work. Ideas?
Notice
I have tried all of the methods recommended on my API level 16 physical device and my API level 8 emulator, but I get the same problem.
Clarification
When editText1 is focused and is clicked on, then the onClick method fires. If editText2 is focussed, and then editText1 is clicked, it doesn't fire. Big problem.
Overview, when a user interacts with any UI component the various listeners are called in a top-down order. If one of the higher priority listeners "consumes the event" then the lower listeners will not be called.
In your case these three listeners are called in order:
OnTouchListener
OnFocusChangeListener
OnClickListener
The first time the user touches an EditText it receives focus so that the user can type. The action is consumed here. Therefor the lower priority OnClickListener is not called. Each successive touch doesn't change the focus so these events trickle down to the OnClickListener.
Buttons (and other such components) don't receive focus from a touch event, that's why the OnClickListener is called every time.
Basically, you have three choices:
Implement an OnTouchListener by itself:
ed1.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(MotionEvent.ACTION_UP == event.getAction())
editTextClicked(); // Instead of your Toast
return false;
}
});
This will execute every time the EditText is touched. Notice that the listener returns false, this allows the event to trickle down to the built-in OnFocusChangeListener which changes the focus so the user can type in the EditText.
Implement an OnFocusChangeListener along with the OnClickListener:
ed1.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
editTextClicked(); // Instead of your Toast
}
});
This listener catches the first touch event when the focus is changed while your OnClickListener catches every other event.
(This isn't a valid answer here, but it is a good trick to know.) Set the focusable attribute to false in your XML:
android:focusable="false"
Now the OnClickListener will fire every time it is clicked. But this makes the EditText useless since the user can no longer enter any text...
Note:
getApplicationContext() can create memory leaks. A good habit is to avoid using it unless absolutely necessary. You can safely use v.getContext() instead.
I'm probably too late to the party, but here is a code snipped which fixes the issue with onClick() not being called:
ed1.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP && !v.hasFocus()) {
// onClick() is not called when the EditText doesn't have focus,
// onFocusChange() is called instead, which might have a different
// meaning. This condition calls onClick() when click was performed
// but wasn't reported. Condition can be extended for v.isClickable()
// or v.isEnabled() if needed. Returning false means that everything
// else behaves as before.
v.performClick();
}
return false;
}
});
make edit text clickable..
In XML android:clickable="true"
or in code
ed1.setClickable(true);
then do
ed1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "1",Toast.LENGTH_SHORT).show();
}
});
This happens because the first tap gains the focus into the view. The next tap triggers the click.
If you are inflating the view dynamically, do this:
android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false"
If this doesn't work, try applying it on the parent view as well.
Its the most simplest way to work with date picker.
private DatePickerDialog datePickerDialog;
EditText etJoiningDate;
etJoiningDate=(EditText)findViewById(R.id.etJoiningDate);
etJoiningDate.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
datePickerDialog = new DatePickerDialog(TestActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
etJoiningDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
datePickerDialog.show();
break;
}
return false;
}
});
public class TestProject extends Activity implements OnClickListener {
TextView txtmsg;
EditText ed1, ed2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtmsg = (TextView) findViewById(R.id.txtmsg);
ed1 = (EditText) findViewById(R.id.edt1);
ed2 = (EditText) findViewById(R.id.edt2);
ed1.setOnClickListener(this);
ed2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v==ed1){
txtmsg.setText("1");
Toast.makeText(this, "first",Toast.LENGTH_SHORT).show();
}
if(v==ed2){
txtmsg.setText("2");
Toast.makeText(this, "second",Toast.LENGTH_SHORT).show();
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/edt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10" />
<EditText
android:id="#+id/edt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/edt1"
android:layout_marginTop="14dp"
android:ems="10" />
<TextView
android:id="#+id/txtmsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/edt2"
android:layout_below="#+id/edt2"
android:layout_marginRight="22dp"
android:layout_marginTop="160dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Took me a minute to figure this out one time when this happened to me. My ImageButton with a setOnClickListener and onClick didn't seem to fire and then I realized it was actually underneath another element in my xml layout, so I turned this:
<RelativeLayout>
<ImageButton>
<LinearLayout></LinearLayout>
</RelativeLayout>
into this:
<RelativeLayout>
<LinearLayout></LinearLayout>
<ImageButton>
</RelativeLayout>
and suddenly the ImageButton was not being overlapped by the other layout since it was now added later to the parent layout and was now on top and works every time. Good luck, always fun when basic stuff suddenly seems to stop working
Avoid using a FocusChangeListener since it will behave erratically when you don't really need it (eg. when you enter an activity). Just set an OnTouchListener along with your OnClickListener like this:
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
view.requestFocus();
break;
}
return false;
}
This will cause your EditText to receive focus at first, and your onClick to function properly the first time.
Simple, Reuseable Kotlin Solution
I started with two custom extension functions:
val MotionEvent.up get() = action == MotionEvent.ACTION_UP
fun MotionEvent.isIn(view: View): Boolean {
val rect = Rect(view.left, view.top, view.right, view.bottom)
return rect.contains((view.left + x).toInt(), (view.top + y).toInt())
}
Then listen to touches on the Edittext. This will only fire if initial ACTION_DOWN event was originally on the Edittext, and still is.
myEdittext.setOnTouchListener { view, motionEvent ->
if (motionEvent.up && motionEvent.isIn(view)) {
// Talk your action here
}
false
}
I started program little bit in android,
I have 3 buttons in a single activity.
I saw some example codes that assign the same OnClick event to all the buttons (even if they perform completely different action) and in the method Switch(id) case case case...
What is the better approach? one onClick method and switching or a lot of methods, one for each button?
Thanks.
Use this way:
#Override
public void onCreate(Bundle savedInstanceState) {
button1.setOnClickListener(onClickListener);
button2.setOnClickListener(onClickListener);
button3.setOnClickListener(onClickListener);
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
//DO something
break;
case R.id.button2:
//DO something
break;
case R.id.button3:
//DO something
break;
}
}
};
If you want to reduce the coding lines then use View's OnClick() with switch statement and if you want to handle separately all click (for easily understanding and maintaining code) then use separate all button's onClick().
Update:
If you have declared Buttons in your Activity layout xml file, than write attribute android:onClick="" with same method name for all buttons and implement that method in your activity. Now you have one method for all buttons and in that method differentiate buttons with id.
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button android:id="#+id/button1"
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 1" />
<Button android:id="#+id/button2"
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 2" />
<Button android:id="#+id/button3"
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 3" />
</LinearLayout>
Now in your Activity implement buttonOnClick like,
public void buttonOnClick(View view)
{
switch(view.getId())
{
case R.id.button1:
// Code for button 1 click
break;
case R.id.button2:
// Code for button 2 click
break;
case R.id.button3:
// Code for button 3 click
break;
}
}
Or you can apply same switch case for dynamically added buttons in your activity,
like instead of buttonOnClick you have to use implemented View's OnClickListerner's onClick.
this.btnAddFriedtoFacebook = (Button) this.findViewById(R.id.btnAddFriedtoFacebook);
this.btnAddFriedtoFacebook.setOnClickListener(this.backButtonClickListener);
public OnClickListener backButtonClickListener = new OnClickListener()
{
public void onClick(final View view)
{
if (view == MatchInfoActivity.this.btnBack)
{
MatchInfoActivity.this.finish();
}
if( view == MatchInfoActivity.this.btnAddFried){
Intent i = new Intent(Intent.ACTION_VIEW);
MatchInfoActivity.this.startActivity(i);
}
if( view == MatchInfoActivity.this.btnAddBuddy){
Intent i = new Intent(Intent.ACTION_VIEW);
MatchInfoActivity.this.startActivity(i);
}
}
};
Here is the good way.
I think registering onClick in xml (layout) is better approach.
EDIT:
Found related threads :
Best practice for defining button events in android
best practices for handling UI events
Registered onClick event in the XML layout and then handle it in the code. This is how I would do it:
<Button
android:id="#+id/btplus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:onClick="onBtnClicked">
Method in .class
public void onBtnClicked(View v) {
switch (v.getId()) {
case R.id.btplus:
Toast.makeText(getApplicationContext(), "Plus is clicked" + "+", Toast.LENGTH_SHORT).show();
break;
case R.id.btminu:
Toast.makeText(getApplicationContext(),"Minus is clicked" + "-", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
Little addition to #Nguyen answer.
findViewById(R.id.buttonOne).setOnClickListener(buttonClickListener);
.... .... .... ....
findViewById(R.id.buttonN).setOnClickListener(buttonClickListener);
private View.OnClickListener buttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonOne:
// do something
break;
.... .... .... ....
case R.id.buttonN:
// do something
break;
}
}
};
This could be useful, if you don't want to initialize the button variable, but want to track button click event. Thanks!