The elseif(v == button2) line gives an error saying that "Syntax error on token '==', delete this token". I got the idea of using this from the topic "Variable OnClick listener android" from this website. Can anyone please tell me how to use it?
Here is my code:
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick(View v){
if( v == button1){
new AlertDialog.Builder(this)
.setTitle("Paracettamol")
.setMessage("This medicine is generally used to cure Fever")
.setNeutralButton("OK", null)
.show();}
}
elseif( v == button2){
new AlertDialog.Builder(this)
.setTitle("sertraline")
.setMessage("This medicine is generally used to cure Head aches")
.setNeutralButton("OK", null)
.show();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
} ;
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
The answer of the asked question mentioned above has the following code:
Button btn1, btn2;
public void onCreate(Bundle b)
{
// here you do normal things like assigning a
// content view to the activity, initiate buttons, etc.
// then you assign the same listener to both buttons
btn1.setOnClickListener(yourListener);
btn2.setOnClickListener(yourListener);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick (View v){
if( v == btn1 ){
// do something
}
elseif( v == btn1 ){
// do another thing
}
}
};
You might missed space between else and if - "elseif( v == button2) "
ah...
Your code sample is a mess...
I've re-formatted it and correct errors. Now it should work.
View.OnClickListener yourListener = new View.OnClickListener() {
public void onClick(View v) {
if (v == button1) {
new AlertDialog.Builder(v.getContext())
.setTitle("Paracettamol")
.setMessage(
"This medicine is generally used to cure Fever")
.setNeutralButton("OK", null).show();
} else if (v == button2) {
new AlertDialog.Builder(v.getContext())
.setTitle("sertraline")
.setMessage(
"This medicine is generally used to cure Head aches")
.setNeutralButton("OK", null).show();
}
}
};
Could you be more accurate asking question next time?
Related
I have 1 button in activity. i want to use this 1 button for multiple task.
So how can i do ?
If i pressed 1st time this button then it's change 2 button
if i pressed 2nd time then it's update my data
but it's only work 1st time 2nd time it's not work
see my code what i tried
Intent extras = getIntent();
{
if (extras.hasExtra("edit")) {
if (extras.getStringExtra("edit").equals("home")) {
etCompanyName.setEnabled(false);
etWebsite.setEnabled(false);
etEmail.setEnabled(false);
etPhoneHome.setEnabled(false);
etPhonePrimary.setEnabled(false);
etAddressLine1.setEnabled(false);
etAddressLine2.setEnabled(false);
etCity.setEnabled(false);
spStates.setEnabled(false);
etZip.setEnabled(false);
spContries.setEnabled(false);
//1st time use hear
txtSave.setText(getResources().getString(R.string.label_edit));
txtClose.setText(getResources().getString(R.string.label_back));
txtSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtSave.setText(getResources().getString(R.string.label_add));
txtClose.setText(getResources().getString(R.string.label_cancel));
etCompanyName.setEnabled(true);
etWebsite.setEnabled(true);
etEmail.setEnabled(true);
etPhoneHome.setEnabled(true);
etPhonePrimary.setEnabled(true);
etAddressLine1.setEnabled(true);
etAddressLine2.setEnabled(true);
etCity.setEnabled(true);
spStates.setEnabled(true);
etZip.setEnabled(true);
spContries.setEnabled(true);
}
});
if (extras != null) {
Company value = (Company) extras.getSerializableExtra("company");
etCompanyName.setText(value.getName());
etWebsite.setText(value.getWebsite());
etEmail.setText(value.getEmail());
etPhoneHome.setText(value.getPhoneHome());
etPhonePrimary.setText(value.getPhonePrimary());
etAddressLine1.setText(value.getAddressLine1());
etAddressLine2.setText(value.getAddressLine2());
etCity.setText(value.getCity());
etZip.setText(value.getZipcode());
}
} else {
//2nd time use hear
txtSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Company company = new Company();
company.setName(etCompanyName.getText().toString().trim());
company.setWebsite(etWebsite.getText().toString().trim());
company.setEmail(etEmail.getText().toString().trim());
company.setPhoneHome(etPhoneHome.getText().toString().trim());
company.setPhonePrimary(etPhonePrimary.getText().toString().trim());
company.setAddressLine1(etAddressLine1.getText().toString().trim());
company.setAddressLine2(etAddressLine2.getText().toString().trim());
company.setZipcode(etZip.getText().toString().trim());
company.setCity(etCity.getText().toString().trim());
company.setState(spStates.getSelectedItem().toString());
company.setCountry(spContries.getSelectedItem().toString());
company.setDate(Util.getInstance(AddCompanyActivity.this).getCurrentDate());
long isUpdated = myDb.updateCompany(company);
if (isUpdated != -1) {
Toast.makeText(getApplicationContext(), "Company Update Successfully: " + isUpdated, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Something wrong", Toast.LENGTH_SHORT).show();
}
finish();
}
});
}
}
}
You can see my above code i can used txtSave button for perform 2 task but it's only change two buttons and i'll change data and click on button then it's can't perform
Try this way, first declare global variable on your activity class file like below :
int count = 0;
After that add your click listener like that:
yourButton.setOnClickListener(v -> {
if (count == 0) { // the first click
count++;
// do your stuff
}else { // the second click
count = 0; // initialize the count to limit the button click just for the first and the second time only
// do your stuff
}
});
You should not create multiple OnClickListener for Button , Create only 1 and use it
example:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(btn.getText().equals("1")){
//perform action for 1
btn.setText("2");
//change button1 to button2
}else if(btn.getText().equals("2")){
//perform action for 2
btn.setText("3");
}
}
});
you could use single onclicklistener with switch case
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
swtich(extras.getStringExtra().toLowerCase(){
case "1":
// do something
break;
case "2":
// do something else
break;
}
});
}
I have a "DialogHelper" class wherein a bunch of static methods are used in various contexts to make using Dialogs easier. One such method is a "three choice dialog" where the user has three buttons to choose from to go forward:
public static AlertDialog createThreeChoiceDialog(final MyActivity activity, String title, String firstChoiceText,
String secondChoiceText, String thirdChoiceText, View.OnClickListener firstChoiceListener, View.OnClickListener secondChoiceListener,
View.OnClickListener thirdChoiceListener) {
final View dView = activity.getLayoutInflater().inflate(R.layout.three_choice_dialog, null);
final TextView explanatoryTV = (TextView) dView.findViewById(R.id.explanatoryTV);
final TextView firstChoiceTV = (TextView) dView.findViewById(R.id.firstChoiceTV);
final TextView secondChoiceTV = (TextView) dView.findViewById(R.id.secondChoiceTV);
final TextView thirdChoiceTV = (TextView) dView.findViewById(R.id.thirdChoiceTV);
explanatoryTV.setText(title);
firstChoiceTV.setText(firstChoiceText);
secondChoiceTV.setText(secondChoiceText);
thirdChoiceTV.setText(thirdChoiceText);
firstChoiceTV.setOnClickListener(firstChoiceListener);
secondChoiceTV.setOnClickListener(secondChoiceListener);
thirdChoiceTV.setOnClickListener(thirdChoiceListener);
AlertDialog = etc...
return alertDialog;
}
And I call it like this:
private void doSomething() {
final AlertDialog alert = DialogHelper.createThreeChoiceDialog(activity, "title", "choice1", "choice2", "choice3",
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something 1
alert.dismiss();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something 2
alert.dismiss();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something 3
alert.dismiss();
}
});
alert.show();
}
However, the "alert.show()" method rings up the error:
variable 'alert' might not have been initialized yet
My question is, what is the best way to handle this situation? I want to dismiss the dialog when the user selects a choice.
This is my current workaround:
private void doSomething() {
final ArrayList<AlertDialog> alerts = new ArrayList<>(); //<-- added ArrayList of AlertDialogs
final AlertDialog alert = DialogHelper.createThreeChoiceDialog(activity, "title", "choice1", "choice2", "choice3",
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something 1
alerts.get(0).dismiss(); //<-- accessed via ArrayList
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something 2
alerts.get(0).dismiss(); //<-- accessed via ArrayList
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something 3
alerts.get(0).dismiss(); //<-- accessed via ArrayList
}
});
alerts.add(alert); //<-- add alert to ArrayList
alert.show();
}
It works, but there's no way that this can be a best practice. I've run into this problem a few times, so I finally decided to ask what the best way to handle it is.
You are basically trying to reference an instance of a class while declaring and creating that instance - this is not possible.
I see your options as the following:
1. Wrap AlertDialog
This is basically your work-around which uses an ArrayList, but you can create you own class for this purpose also.
2. Make AlertDialog a member
Declare alert be a private member of the class which contains the doSomething method, instead of declaring it in the method itself.
3. Replace your DialogHelper with a Builder
There are several advantages (and 1 disadvantage) to this approach.
The first advantage is that it will solve your problem. The second is because it's good coding practice: in general, having methods with take many parameters is considered dirty. In the case of them being constructor methods, Clean Code conventions recommend replacing them with builders.
The disadvantage of the implementation I am about to suggest is that the Dialog behaviour is that clicking an option will always dismiss the dialog.
public class MyDialogBuilder {
private AlertDialog alert;
public MyDialogBuilder withActivity(Activity activity){
final View dView = activity.getLayoutInflater().inflate(R.layout.three_choice_dialog, null);
alert = ...;
return this;
}
public MyDialogBuilder withFirstChoice(String choiceText, final ChoiceAction action){
final TextView firstChoiceTV = (TextView) alert.findViewById(R.id.firstChoiceTV);
firstChoiceTV.setText(choiceText);
firstChoiceTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
action.perform();
alert.dismiss();
}
});
return this;
}
// Similar implementations for the other methods here...
public AlertDialog create() {
return alert;
}
interface ChoiceAction {
void perform();
}
}
Your calling code would be like
MyDialogBuilder builder = new MyDialogBuilder();
AlertDialog alert = builder.withActivity(activity)
.withTitle("Dialog title")
.withFirstChoice("choice 1", new MyDialogBuilder.ChoiceAction() {
#Override
public void perform() {
//do something 1
}
})
.withSecondChoice("choice 2", new MyDialogBuilder.ChoiceAction() {
#Override
public void perform() {
//do something 2
}
})
.withThirdChoice("choice 3", new MyDialogBuilder.ChoiceAction() {
#Override
public void perform() {
//do something 3
}
})
.create();
I would recommend the third approach, as I think in most cases you want to close the Dialog when the user selects an option. If you want to show some progress bar in the dialog, you can create additional methods on MyDialogBuilder which would call alert.dismiss() in a callback. Hope this helps.
In the below code i tried to change the image on first click(working). But on second click it should change back to original state. Likewise it should change on every click simultaneously. Please explain me the logic. i am new to android. Thanks in advance
ib_accordion1 = (ImageButton)findViewById(R.id.ib_accordion1);
ib_accordion1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ib_accordion1.setImageResource(R.drawable.minus_icon);
}
});
Just use a simple boolean value to determine it's state.
boolean isOriginal = true;
ib_accordion1 = (ImageButton)findViewById(R.id.ib_accordion1);
ib_accordion1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
isOriginal = !isOriginal;
ib_accordion1.setImageResource(isOriginal ? R.drawable.original : R.drawable.minus_icon);
});
boolean original = true;
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
original = !original;
img.setBackgroundResource(original ? R.drawable.ic_action_new_light
: R.drawable.ic_action_chat_light);
}
});
Actually, I have edited above comment and worked for me thanks to Sai Chakradhar Sana.
I'm new to Java (coming from Python) and I'm trying to pass a method as a parameter in order to convert this code:
Button button1;
Button button2;
...
Button buttonN;
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button1(v);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button2(v);
}
});
(...)
buttonN = (...)
To something like:
public AssignListener( integer tButton, Method tMethod )
{
button_view = (Button) findViewById(tButton);
button_view.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
tMethod(view);
}
}
}
(...)
AssignListener( R.id.button1, onClick_button1 );
AssignListener( R.id.button2, onClick_button2 );
(...)
AssignListener( R.id.buttonN, onClick_buttonN );
I've read that you can't pass methods to functions, and some advice to wrap my function using Runnable to achieve this.
I have not clear idea about how to do it. Any idea on how do it easily? :?
Thanks.
EDIT: Should I wrap "AssignListener" in its own class and pass the class itself? :?
You can call findViewById() and seOnClickListener into onCreate method, and OnClickListenet outside the onCreate.
Button button1 = (Button)findViewById(R.id.button1);
or
findViewById(R.id.button1).seOnClickListener(mClickListener);
findViewById(R.id.button2).seOnClickListener(mClickListener);
findViewById(R.id.button3).seOnClickListener(mClickListener);
findViewById(R.id.button4).seOnClickListener(mClickListener);
private OnClickListener mClickListener = new View.OnClickListener(
public void onClick(View view){
switch(view.getId()){
case R.id.button1:
//button1 click handle here...
break;
case R.id.button2:
//button2 click handle here...
break;
case R.id.button3:
//button3 click handle here...
break;
case R.id.button4:
//button4 click handle here...
break;
}
});
Try it, hope it will helpful to you.
You could define and pass an onClickListener like this:
public AssignListener( integer tButton, OnClickListener listener ){
tButton.setOnClickListener(listener);
}
The simplest way is to create listener implementation for each button, as is written in your first snippet.
I don't see any reasonable benefit of having universal method like AssignListener(). Don't reinvent bicycle, use existing setOnClickListener() method and pass listener specific for button.
An easy solution would be to create a function called tMethod that takes a button id, and has a switch statement that allows for a certain action to be performed for the given button id. This would then be called inside the onClick function like tMethod(view.getId()).
Btw, Python has methods. Java has functions. Pedant mode turned off!
public class MyClass implements OnClickListener, OnLongClickListener {
Button button1;
Button button2;
...
Button buttonN;
. . .
setButtonsListener(findViewById(<your top view id>));
. . .
void setButtonsListener(ViewGroup vg) {
int count = vg.getChildCount();
Button btn;
View v;
for(int i=0; i < count ; i++) {
v = vg.getChildAt(i);
if( v instanceof Button ) {
btn = (Button)v;
btn.setOnClickListener(this);
btn.setOnLongClickListener(this);
} else if( v instanceof ViewGroup ) {
setButtonsListener((ViewGroup) v);
}
}
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
I'm creating a quiz. I have 3 buttons (options) in the activity and its corresponding questions. Now, my problem is I want to show the toast message, when the user chose the correct answer the toast message will appear in a few seconds, but when the user choose the wrong answer it will again display the toast message. I do not know how to do that.
I have done many research and read forums, but seems I don't understand and it don't meet my needs. Can someone please help? thanks in advance!
So far, here is the code. But it doesn't work.
Please correct me which code is wrong. Thanks deeply.
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Button btn1 = (Button) findViewById(R.id.btnopt1_a);
btn1.isClickable();
switch(arg0.getId()){
case R.id.btnopt1_a:
if(btn1.isPressed()){
Toast.makeText(getBaseContext(), "Your answer is correct!" , Toast.LENGTH_SHORT ).show();
}
else btn1.setText("Your answer is wrong!, The correct answer is: Frog");
break;
}
}
});
To show toast message when you click button, use the following code. If you want to do some validations then use the code in your onclicklistener of button:
Button btn1 = (Button) findViewById(R.id.btnopt1_a);
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Your answer is correct!" , Toast.LENGTH_SHORT ).show();
}
});
Try this, First implements Your Activity OnClickListener . And then each end every click check condition you will get solution.
public class Deals extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.yourxml);
//declare ur buttons here
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.menu: {
// Do your stuff here
// call method
if (isright) {
Toast.makeText(getBaseContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Your answer wrong!", Toast.LENGTH_SHORT ).show();
}
}
}
}
}
If you have many conditions in which you have to show toast. Then it would be better to make a method which shows it.
private void showToast(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
And call the above method in the onClick() or wherever you want to show.
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
..................
..........................
case R.id.btnopt1_a:
if (btn1.isPressed()) {
showToast("Your answer is correct!");
} else {
showToast("Your answer is wrong!, The correct answer is: Frog");
}
break;
});