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;
}
});
}
Related
How to make a button which when pressed would show a toast message asking the user to tap button again to confirm the action. Here is what I have so far,
Button myExitClose = alertLayout.findViewById(R.id.homeExitClose);
ImageView myExitDismiss = alertLayout.findViewById(R.id.homeExitDismiss);
final LinearLayout adContainer = alertLayout.findViewById(R.id.homeExitAdView);
myExitClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
exitDialog.dismiss();
finish();
}
});
myExitDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
exitDialog.dismiss();
}
});
alert.setView(alertLayout);
alert.setCancelable(false);
exitDialog = alert.create();
}
When the button is pressed, record the timestamp of the press. If the button is pressed again, compare the new timestamp to the old one, and perform the special action if the two presses happend close enough together.
private Long lastPressedTime = null;
button.setOnClickListener(v -> {
long currentTime = System.currentTimeMillis();
if (lastPressedTime == null || (currentTime - lastPressedTime) > 2000) {
Toast.makeText(v.getContext(), "Tap again to exit", Toast.LENGTH_SHORT).show();
lastPressedTime = currentTime;
} else {
finish();
}
});
You can change the 2000 to any number you want; 2000 millis is two seconds, but maybe you want a longer window.
Use handler to schedule for setting button action like this:
final OnClickListener listener = new OnClickListener(){
public void onClick(View v) {
Toast.makeText(YourActivity.this,"press back one more time to exit",Toast.LENGTH_SHORT).show();
myExitClose.setOnClickListener(new OnClickListener(){
YourActivity.this.finish();
});
new Handler().postDelay(new Runable(){
myExitClose.setOnClickListener(listener);
},2000); //wait 2 second for the next pressed
}
}
myExitClose.setOnClickListener(listener);
Example of how to exit app on double back press within a defined interval:
private long backPressed;
private static final int TIME_INTERVAL = 2000;
#Override
public void onBackPressed() {
if( backPressed + TIME_INTERVAL > System.currentTimeMillis() ) {
finish();
super.onBackPressed();
return;
} else {
Toast.makeText(this, "Tap again to exit", Toast.LENGTH_SHORT).show();
}
backPressed = System.currentTimeMillis();
}
Paste code to a listener for an onClick().
This is the basic gist of it. Toast.maketext takes a context, string and a duration.
myExitClose.setOnClickListener( (click) -> {
Toast.makeText(getActivity(), "StringRes", Toast.LENGTH_SHORT).show();
});
You could also make a Toast object and manipulate placement etc before you show it.
I have a button with the "btnadd" id ,
Button add = (Button) findViewById(R.id.btnadd);
And a function with two inputs ,
public void CheckNumber (int i , int j) { if (i != j) Toast.makeText(getBaseContext,"i is not equal to j"); }
And I want to set this function for the click event of this button
add.setOnClickListener(CheckNumber(2,4));
This code is not correct, but how can I do this?
You need to define a new View.OnClickListener inside of setOnClickListener.
Try this:
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkNumber(2, 4);
}
});
Complete Solution:
Try something like this:
First, Create a method: (Consider your case)
public void CheckNumber (int i , int j) {
if (i != j)
Toast.makeText(this, "i is not equal to j", Toast.LENGTH_SHORT);
}
Second, declare the button inside onCreate():
Button add = findViewById(R.id.btnadd);
Then finally, add a click listener:
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckNumber(2, 4);
}
});
That's it. Hope it helps.
I want to make a gallery app with previous and next button. I made an array of photos. Whenever I reached the last photo, I have to click the previous button twice to get the previous photo. And also when I get to the first photo, I have to click the next button twice to get to the next photo. My code:
public class MainActivity extends AppCompatActivity {
ImageView ivphoto;
Button btnext;
Button btprevious;
int a=0;
int photoarray[]={R.drawable.cat, R.drawable.dog, R.drawable.duck, R.drawable.elephant, R.drawable.monkey, R.drawable.pig, R.drawable.rabbit, R.drawable.tiger};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivphoto = findViewById(R.id.ivphoto);
btnext = findViewById(R.id.btnext);
btprevious = findViewById(R.id.btprevious);
btnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ivphoto.setImageResource(photoarray[a]);
a++;
if (a==8){
a=7;
Toast.makeText(MainActivity.this, "This is last photo", Toast.LENGTH_SHORT).show();
}
}
});
btprevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ivphoto.setImageResource(photoarray[a]);
a--;
if(a==-1){
a=0;
Toast.makeText(MainActivity.this, "This is first photo.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Any one please help me with this. Thanks.
Try this code in next button:
if(a == photoarray.lenght - 1)
Toast.makeText(MainActivity.this, "This is last photo", Toast.LENGTH_SHORT).show();
else
ivphoto.setImageResource(photoarray[++a]);
And this code in back button:
if(a == 0)
Toast.makeText(MainActivity.this, "This is first photo.", Toast.LENGTH_SHORT).show();
else
ivphoto.setImageResource(photoarray[--a]);
The error is in this line:
btnext:
if (a==8){
a=7;
Toast.makeText(MainActivity.this, "This is last photo", Toast.LENGTH_SHORT).show();
}
If a is 8, it becomes 7. Then on clicking btprevious, image 7 is displayed again, then a becomes 6. On the next click, a becomes 5, and image 6 is shown.
A similar error is present in btprevious.
You need to changea before changing the image.
I have some codes that I need help with. My plan for this code is simple. I have 3 buttons which are the yellowBar, greenBar and redBar. I also have 3 images that is colored yellow, green and red. What I wanted to do is when I start my app, the images I have will randomly pop out and whichever color comes out, I should be able to click the button with the corresponding color. I also have a time, so basically I want to click correctly as much as possible, but my code only runs it one time. my time continues to go down but this code only runs one time. How can I fix this so that it will continue to pop random color images until the time runs out?
while(gameTime > 0){
colorNum = new Random();
colorNumber = colorNum.nextInt(2);
switch (colorNumber){
case 0: colors.setDisplayedChild(0);
break;
case 1: colors.setDisplayedChild(1);
break;
case 2: colors.setDisplayedChild(2);
break;
}
colors.setVisibility(View.VISIBLE);
yellowBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 0){
points ++;
score.setText(String.valueOf(points));
}
}
});
greenBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 1){
points ++;
score.setText(String.valueOf(points));
}
}
});
redBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 2){
points++;
score.setText(String.valueOf(points));
}
}
});
}
The better solution would be to render your graphics onClick event.
When you press a button, you check if the answer was right, then you render the graphics.
using while loop like you do it now is wrong, since your graphics will be rendered all the time (whether button is pressed or not)
Basically (this is not a solution, rather a guideline based on your code):
public void initialize(){
yellowBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 0){
points ++;
score.setText(String.valueOf(points));
updateColors();
}
}
});
greenBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 1){
points ++;
score.setText(String.valueOf(points));
updateColors();
}
}
});
redBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 2){
points++;
score.setText(String.valueOf(points));
updateColors();
}
}
});
}
}
public void updateColors(){
colorNum = new Random();
colorNumber = colorNum.nextInt(2);
switch (colorNumber){
case 0: colors.setDisplayedChild(0);
break;
case 1: colors.setDisplayedChild(1);
break;
case 2: colors.setDisplayedChild(2);
break;
}
colors.setVisibility(View.VISIBLE);
}
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?