In general have this screen:
How to put conditions from OnClick to onCheckedChanged (radiobutton). It works only with one variable price_53_off in OnClick, but I want when checked other radiobutton (500 gr.) program parses other variable (price_73_off) and calculate other cycle.
Some code below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
ImageView plus;
ImageView minus;
TextView tvResult;
TextView price;
TextView price_53_off;
TextView price_73_off;
RadioGroup radioGroup_price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
plus = (ImageView) findViewById(R.id.plus);
plus.setOnClickListener(this);
minus= (ImageView) findViewById(R.id.minus);
minus.setOnClickListener(this);
tvResult = (TextView) findViewById(R.id.tvResult);
price = (TextView) findViewById(R.id.price);
price_53_off = (TextView) findViewById(R.id.price_53_off);
price_73_off = (TextView) findViewById(R.id.price_73_off);
radioGroup_price = (RadioGroup) findViewById(R.id.radioGroup_price);
radioGroup_price.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radioButton_250:
price.setText("53");
break;
case R.id.radioButton_500:
price.setText("73");
break;
}
}
});
}
#Override
public void onClick(View v) {
int parse_quant;
int parse_price_53;
int num2 = 1;
int result = 0;
int resultprice=0;
parse_quant = Integer.parseInt(tvResult.getText().toString());
parse_price_53 = Integer.parseInt(price_53_off.getText().toString());
switch (v.getId()) {
case R.id.plus:
result = parse_quant + num2;
resultcena= result*parse_price_53;
}
switch (v.getId()) {
case R.id.minus:
result = parse_quant - num2;
if (parse_quant==1){
return;
}
resultprice= result*parse_price_53;
}
tvResult.setText( String.valueOf(result) );
price.setText( String.valueOf(resultprice) );
}
}
In order for result and resultPrice variables to be available in both onCheckChanged and onClick, you need to store them at the class level instead of local inside the onClick method.
Related
I am new to android studio, and I don't understand why my app crash when I start using the seekbar.
Could someone please help me?
public class MainActivity extends AppCompatActivity {
SeekBar seekBar; //declare seekbar object
TextView textView, textView2;
ListView simpleListview;
//declare member variables for SeekBar
int discrete;
int start = 50;
int start_position = 50;
//progress tracker
int temp = 0;
//declare objects for ViewStub
ViewStub stub;
CheckBox checkBox;
ListView lv; //declare Listview object
Button button;
View view;
public MainActivity() {
discrete = 0;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare viewstub object
stub = findViewById(R.id.viewStub1);
#SuppressWarnings("unused")
View inflated = stub.inflate();
stub.setVisibility(View.INVISIBLE);
//ViewStub logic
checkBox = findViewById(R.id.checkBox1);
//handle checkbox click event
checkBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if (isChecked) {
//remove objs from parent view to allow for child view objs
checkBox.setVisibility(View.GONE);
seekBar.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
stub.setVisibility(View.VISIBLE);
}
}
});
//seekbar logic
textView = findViewById(R.id.textview);
textView = findViewById(R.id.textView2);
textView.setText(" Celsius at 0 degrees");
//set default view
seekBar = findViewById(R.id.seekbar);
seekBar.setProgress(start_position);
//create event handler for SeekBar
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (temp == 0) {
//for initial view result
//Toast.makeText(getBaseContext(), "Fahrenheit result: 32 degrees",
//Toast.LENGTH_SHORT).show();
textView2.setText("Fahrenheit result 32 degrees") ;
}
else{
//Toast.makeText(getBaseContext(), "Fahrenheit result: "
//+ String.valueOf(discrete) +
//" degrees",Toast.LENGTH_SHORT).show();
textView2.setText("Fahrenheit result:" + String.valueOf(discrete) + "degrees");
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar){ }
#Override
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
// To convert progress passed as discrete (Fahrenheit) value
temp = progress - start;
discrete = (int) Math.round((((temp * 9.0) /
5.0) + 32));
//convert C to F temp textView.setText(" Celsius at " + temp + " degrees");
textView.setText(" Celsius at " + temp + " degrees");
}
});
textView = findViewById(R.id.textview);
textView = findViewById(R.id.textView2);
textView2 is not initialised here...
Change above code to
textView = findViewById(R.id.textview);
textView2 = findViewById(R.id.textView2);
TextView textView = findViewById(R.id.textview);
TextView textView2 = findViewById(R.id.textView2);
initialize textView2
You seem to have missed that part
XML LAYOUT SCREENSHOT
Trying to calculate the final amount of selected items in an another activity. Need to create order summary in another activity.
Tried introducing multiplication function but also need to hard code the quantity values to auto calculate the final amount.
public class MainActivity extends AppCompatActivity {
EditText pantqty;
EditText pantrate;
TextView result;
Button SUBMIT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pantqty = (EditText) findViewById(R.id.et_pantqty);
pantrate = (EditText) findViewById(R.id.et_pantrate);
SUBMIT = (Button) findViewById(R.id.et_submit);
result = (TextView) findViewById(R.id.et_result);
SUBMIT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int q = Integer.valueOf(pantqty.getText().toString());
float r = Integer.valueOf(pantrate.getText().toString());
float amount = q * r;
result.setText(Float.toString(amount));
}
});
}
}
Need to create a method in OnCLickListener to calculate the amount from the items selected.can if else case be used on OnclickListerButton?
Thanks for the help.
You can do something like this:
public class MainActivity extends AppCompatActivity {
EditText pantqty;
EditText pantrate;
EditText shirtQty;
EditText shirtRate;
TextView result;
Button SUBMIT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pantqty = (EditText) findViewById(R.id.et_pantqty);
pantrate = (EditText) findViewById(R.id.et_pantrate);
shirtQty = (EditText) findViewById(R.id.shirtqtyId);
shirtRate = (EditText) findViewById(R.id.shirtRateId);
SUBMIT = (Button) findViewById(R.id.et_submit);
result = (TextView) findViewById(R.id.et_result);
SUBMIT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calculateSum();
}
});
}
private void calculateSum(){
int q=0;
String pantQty=pantqty.getText().toString().trim();
if(!pantQty.isEmpty() && pantQty!="") {
q=Integer.valueOf(pantQty);
}
float r = Integer.valueOf(pantrate.getText().toString());
int a = Integer.valueOf(shirtQty.getText().toString());
float b = Integer.valueOf(shirtRate.getText().toString());
float amount = (q * r)+(a*b);
result.setText(Float.toString(amount));
Intent intent=new Intent(this,SecondActivity.class);
intent.putExtra("total",amount);
startActivity(intent);
}
}
On the secondActivity you get get the total as:
float total=getIntent().getFloatExtra("total",0.0);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pantqty = (EditText) findViewById(R.id.lo_pantqty);
shirtqty = (EditText) findViewById(R.id.lo_shirtqty);
shareesqty = (EditText) findViewById(R.id.lo_shareesqty);
suitqty = (EditText) findViewById(R.id.lo_suitqty);
result = (TextView) findViewById(R.id.et_result);
SUBMIT = (Button) findViewById(R.id.io_enter);
SUBMIT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calculationSum();
}
});
}
private void calculationSum() {
int q = 0;
String pantQTY = pantqty.getText().toString().trim();
if (!pantQTY.isEmpty()&&pantQTY!=""){
q = Integer.valueOf(pantQTY);
}
int r = 0;
String shirtQTY = shirtqty.getText().toString().trim();
if (!shirtQTY.isEmpty()&&shirtQTY!=""){
r = Integer.valueOf(shirtQTY);
}
int a = 0;
String suitQTY = suitqty.getText().toString().trim();
if (!suitQTY.isEmpty()&&suitQTY!=""){
a = Integer.valueOf(shirtQTY);
}
int b = 0;
String shareesQTY = shareesqty.getText().toString().trim();
if (!shareesQTY.isEmpty()&&shareesQTY!=""){
b = Integer.valueOf(shirtQTY);
}
int amount = (q*30) + (r*35) + (a*220) + (b*60);
result.setText(Integer.toString(amount));
}
}
Is it possible to have multiple buttons calling the same method? I mean the parameters would be the ID of the button. My problem is that I got a really, really long switch case function and every case has the same methods. Here is my code snippet (I have shortened it):
public class HerkunftRind extends Activity implements View.OnClickListener, Animator.AnimatorListener {
private static final String TAG = "HerkunftRind";
ViewFlipper viewFlipper;
ImageButton myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.herkunft_rind);
viewFlipper = (ViewFlipper) findViewById(R.id.herkunft_rinder_view_flipper);
ImageButton imageButton = null;
imageButton = (ImageButton) findViewById(R.id.button_1);
imageButton.setOnClickListener(this);
imageButton = (ImageButton) findViewById(R.id.button_2);
imageButton.setOnClickListener(this);
imageButton = (ImageButton) findViewById(R.id.button_3);
imageButton.setOnClickListener(this);
imageButton = (ImageButton) findViewById(R.id.button_4);
imageButton.setOnClickListener(this);
}
public void setAnimationFade(int id) {
myButton = (ImageButton) findViewById(id);
ObjectAnimator animator = ObjectAnimator.ofFloat(myButton, View.ALPHA, 0.5f, 1f);
animator.setDuration(300); //ms
animator.start();
animator.addListener(this);
}
#Override
public void onAnimationStart(Animator animation) {
myButton.setAlpha(1f);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_1: {
setAnimationFade(R.id.button_1);
text = (TextView) findViewById(R.id.button_1_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_1_text_2);
text.setVisibility(View.VISIBLE);
break;
}
case R.id.button_2: {
setAnimationFade(R.id.button_2);
text = (TextView) findViewById(R.id.button_2_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_2_text_2);
text.setVisibility(View.VISIBLE);
break;
}
case R.id.button_3: {
setAnimationFade(R.id.button_3);
text = (TextView) findViewById(R.id.button_3_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_3_text_2);
text.setVisibility(View.VISIBLE);
break;
}
case R.id.button_4: {
setAnimationFade(R.id.button_4);
text = (TextView) findViewById(R.id.button_4_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_4_text_2);
text.setVisibility(View.VISIBLE);
break;
}
What I don't want is to define it directly in the XML file. Can I make this shorter?
Yes, you can, I personally do that very often.
You can call the method in the xml layout.
i.e.:
<Button
android:onClick="myMethod()"
/>
Mind that myMethod() must have a signature like
public void myMethod(View v)
Inside myMethod you may then want to discern which is the View you clicked (which can also be heterogeneous) and act consequentially.
Just add a switch() where you use v.getId() to determine which is the View which fired the event.
Something like this:
switch(v.getId())
{
case R.id.txtPhone:
{
// Do something
// ...
break;
}
case R.id.txtMenu:
{
// Show options menu
// ...
break;
}
// ...
default:
{
break;
}
}
this here is a little bit redundant:
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_1: {
setAnimationFade(R.id.button_1);
text = (TextView) findViewById(R.id.button_1_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_1_text_2);
text.setVisibility(View.VISIBLE);
break;
}
case R.id.herkunft_rinder_bauer2_button: {
setAnimationFade(R.id.button_2);
text = (TextView) findViewById(R.id.button_2_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_2_text_2);
text.setVisibility(View.VISIBLE);
break;
}
...
why you just dont call setAnimationFade before the hole switch case..??
public void onClick(View v) {
setAnimationFade(v.getId());
switch (v.getId()) {
case R.id.button_1: {
setAnimationFade(R.id.button_1
If you don't want a long onClick method, then you could write an onClick listener to each button.
E.g:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
anotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Basically, there is a text field where the user can input the subtotal of the meal. Then, when they hit done, the done method is supposed to take the tip field value, and multiply it by the subtotal value, so that the total includes the two pieces of data. However, when I hit the done button, the result is actually always equal to the subtotal, and the tip is always ignored. Here is the code:
public class MainActivity extends Activity implements OnRatingBarChangeListener {
// Testing Stuff to show the rating value, will need to use later for maths
static RatingBar rb;
TextView tipsTV;
ImageView greyPlus, greyMinus, greyPlus2, greyMinus2;
TextView peopleDiningTV, peopleDiningTitle;
int peopleDining = 2;
TextView tipValue;
int tipValueInt = 10;
TextView subtotal, total;
TextView subtotalTitle, totalTitle;
TextView epp, eppTitle;
Button done;
// Elements for hiding and such
static RelativeLayout rl;
static Button settingsButton;
public static int rating = 3;
// The Image used as the DropDown button, Rotate code below
ImageView dropDownButton;
Boolean hasRotated = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dropDownButton = (ImageView) findViewById(R.id.dropDownButton);
rb = (RatingBar) findViewById(R.id.ratingBar1);
rb.setRating(rating);
tipsTV = (TextView) findViewById(R.id.textView2);
tipValue = (TextView) findViewById(R.id.tipText);
greyPlus = (ImageView) findViewById(R.id.greyPlus);
greyMinus = (ImageView) findViewById(R.id.greyMinus);
greyPlus2 = (ImageView) findViewById(R.id.greyPlus2);
greyMinus2 = (ImageView) findViewById(R.id.greyMinus2);
peopleDiningTV = (TextView) findViewById(R.id.textViewPeople);
peopleDiningTitle = (TextView) findViewById(R.id.TextView02);
subtotal =(TextView) findViewById(R.id.subtotalText);
subtotalTitle =(TextView) findViewById(R.id.subtotalTitle);
total =(TextView) findViewById(R.id.totalText);
totalTitle =(TextView) findViewById(R.id.totalTitle);
epp = (TextView) findViewById(R.id.eppText);
eppTitle = (TextView) findViewById(R.id.eppTitle);
done = (Button) findViewById(R.id.buttonDone);
greyPlus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tipValueInt++;
tipValue.setText(tipValueInt + "%");
}
});
greyMinus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (tipValueInt >= 1) {
tipValueInt--;
tipValue.setText(tipValueInt + "%");
}
if(tipValueInt == 0){
tipValue.setText("No Tip.");
}
}
});
greyPlus2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
peopleDining++;
peopleDiningTV.setText(peopleDining + "");
}
});
greyMinus2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (peopleDining > 1) {
peopleDining--;
peopleDiningTV.setText(peopleDining + "");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
FragmentManager fm = getFragmentManager();
QuizFragment qf = new QuizFragment();
public void dropDown(View view) {
if (hasRotated == false) {
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
dropDownButton.setRotation(90);
ft.add(R.id.quizFragment, qf);
ft.show(qf);
ft.commit();
hasRotated = true;
// Hiding Elements, so they don't show through the fragment
tipsTV.setVisibility(View.INVISIBLE);
greyPlus.setVisibility(View.INVISIBLE);
greyMinus.setVisibility(View.INVISIBLE);
tipValue.setVisibility(View.INVISIBLE);
greyPlus2.setVisibility(View.INVISIBLE);
greyMinus2.setVisibility(View.INVISIBLE);
peopleDiningTV.setVisibility(View.INVISIBLE);
peopleDiningTitle.setVisibility(View.INVISIBLE);
subtotal.setVisibility(View.INVISIBLE);
subtotalTitle.setVisibility(View.INVISIBLE);
total.setVisibility(View.INVISIBLE);
totalTitle.setVisibility(View.INVISIBLE);
epp.setVisibility(View.INVISIBLE);
eppTitle.setVisibility(View.INVISIBLE);
done.setVisibility(View.INVISIBLE);
} else if (hasRotated == true) {
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_out,
android.R.animator.fade_out);
dropDownButton.setRotation(0);
hasRotated = false;
ft.remove(qf);
ft.commit();
// Hiding Elements, so they don't show through the fragment
tipsTV.setVisibility(View.VISIBLE);
greyPlus.setVisibility(View.VISIBLE);
greyMinus.setVisibility(View.VISIBLE);
tipValue.setVisibility(View.VISIBLE);
greyPlus2.setVisibility(View.VISIBLE);
greyMinus2.setVisibility(View.VISIBLE);
peopleDiningTV.setVisibility(View.VISIBLE);
peopleDiningTitle.setVisibility(View.VISIBLE);
subtotal.setVisibility(View.VISIBLE);
subtotalTitle.setVisibility(View.VISIBLE);
total.setVisibility(View.VISIBLE);
totalTitle.setVisibility(View.VISIBLE);
epp.setVisibility(View.VISIBLE);
eppTitle.setVisibility(View.VISIBLE);
done.setVisibility(View.VISIBLE);
}
}
public void openSettings(View view) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
}
public void done(View view){
int subtotalCost = Integer.parseInt(subtotal.getText().toString());
int tip = tipValueInt / 100;
int totalCost = (subtotalCost * tip) + subtotalCost;
total.setText(totalCost+"");
}
}
You never put an OnClickListener on the button variable done so your clicks are just ignored, that is why the value doesn't change. You should add the listener and then call your done() method in the onClick(). You should also remove the View view parameter of done() since you are not using it at all.
// ...
done = (Button) findViewById(R.id.buttonDone);
// add listener
done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
done();
}
});
// ...
You should probably change the name of the method done() to displayResult() or something more meaningful and not similar to your button variable named done. Actually, you should probably change the names of most of your variables to names that more clearly describe what the variables are used for. For example, variable done that represents the button can be something like btnDone...
You've declared totalCost as int. So, if (subtotalCost * tip) is less than 1, then totalCost = subtotalCost. Try using floats instead of ints, if applicable.
First of all, I'm using Andorid and Java only for a week and I'm a total newbie.
I need to know which button user clicked and then compare it with good or bad answer.
Here is the code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
Integer[] flags = {
R.drawable.flag_albania,
R.drawable.flag_andorra,
R.drawable.flag_angola,
R.drawable.flag_avganistan,
};
String[] questions = {
"What is the flag of Albania",
"What is the flag of Andorra",
"What is the flag of Angola",
"What is the flag of Avganistan",
};
TextView tv = (TextView) findViewById(R.id.textView1);
int arraySize = flags.length;
Random rand = new Random();
ImageButton button1 = (ImageButton) findViewById(R.id.imageButton1);
int index = rand.nextInt(arraySize);
int questionIndex1 = index;
button1.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button2 = (ImageButton) findViewById(R.id.imageButton2);
index = rand.nextInt(arraySize);
int questionIndex2 = index;
button2.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button3 = (ImageButton) findViewById(R.id.imageButton3);
index = rand.nextInt(arraySize);
int questionIndex3 = index;
button3.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button4 = (ImageButton) findViewById(R.id.imageButton4);
index = rand.nextInt(arraySize);
int questionIndex4 = index;
button4.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
Integer[] question = {
questionIndex1,
questionIndex2,
questionIndex3,
questionIndex4
};
int questionArraySize = question.length;
int questionArray = rand.nextInt(questionArraySize);
tv.setText(questions[question[questionArray]]);
My idea is to compare questionIndex that is randomly selected to a button id but I really don't know how to implement it. Every help is appreciated.
Use this reduced code
ImageButton button1,button2,button3,button4;
ImageButton imagebuttons[]={ button1,button2,button3,button4};
int ids[]={R.id.imageButton1,R.id.imageButton2,R.id.imageButton3,R.id.imageButton4};
for(final int i=0;i<imagebuttons.length;i++)
{
imagebuttons[i]=(ImageButton) findViewById(ids[i]);
int index=rand.nextInt(arraySize);
imagebuttons[i].setImageResource(flags[index]);
flags[index] = flags[--arraySize];
indexes.put(i,index);
imagebuttons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( questionArray==indexes.get(i))
{
}
}
});
I hope this will help you
Try out this way:
button1.setOnClickListener(onClickListener);
button2.setOnClickListener(onClickListener);
/**
* Common click listener
*/
OnClickListener onClickListener = new OnClickListener()
{
#Override
public void onClick(View p_v)
{
switch (p_v.getId())
{
case R.id.imageButton1:
//Your logic here.
break;
case R.id.imageButton2:
//Your logic here.
break;
}
}
}
Write below code
public class MainActivity extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
/// Your Above Code ///
tv.setText(questions[question[questionArray]]);
Imagebutton1.setOnClickListener(this);
Imagebutton2.setOnClickListener(this);
Imagebutton3.setOnClickListener(this);
Imagebutton4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == Imagebutton1){
// Write Your Code Here
} else if(v == Imagebutton2){
// Write Your Code Here
} else if(v == Imagebutton3){
// Write Your Code Here
} else if(v == Imagebutton4){
// Write Your Code Here
}
}
}
You can do it this way:
First, make your activity implements onClick Listener:
public class MyActivity extends Activity implements View.OnClickListener{
Then set the action listeners to your buttons:
button1.setOnClickListener(this);
button2.setOnClickListener(this);
.....
then in the listener, check the id:
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
break;
case R.id.imageButton2:
break;
....
}
}
You can do the it this way also. You have to use some int variables to keep the tag value of the button. And also you have to create a onClickListner for the button actions. Coding is as follow
public class MyActivity extends Activity{
//Define the Tag values for image buttons.
private static final int TAG_IMAGE_BTN_1 = 0;
private static final int TAG_IMAGE_BTN_2 = 1;
private static final int TAG_IMAGE_BTN_3 = 2;
private static final int TAG_IMAGE_BTN_4 = 3;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initActivity();
}
private void initActivity(){
//Initialize the image buttons via xml or from the code itself.
//Add the onClickListner_BTN_CLICK and the corresponding tag to the image button
imageBtn1.setTag(TAG_IMAGE_BTN_1);
imageBtn1.setOnClickListener(onClickListner_BTN_CLICK);
imageBtn2.setTag(TAG_IMAGE_BTN_2);
imageBtn2.setOnClickListener(onClickListner_BTN_CLICK);
.......................................................
.......................................................
}
OnClickListener onClickListner_BTN_CLICK = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int iTag = (Integer)v.getTag();
switch (iTag) {
case TAG_IMAGE_BTN_1:
break;
case TAG_IMAGE_BTN_2:
break;
case TAG_IMAGE_BTN_3:
break;
case TAG_IMAGE_BTN_4:
break;
}
}
};
}
The advantages of using the tag values for capture the action,
1)If we use R.id....... then we have to change the value in switch case if we change it in the xml file
2)We can use only one onClickListner for every action in an activity.