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.
Related
MainActivity(without progressBar)
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submitBttn:
if (questionTwo.getText().toString().isEmpty() & questionFour.getText().toString().isEmpty() & questionFive.getText().toString().isEmpty()){
questionTwo.setError("You haven't completed this question!");
questionFour.setError("You haven't completed this question!");
questionFive.setError("You haven't completed this question!");
}else{
if (questionOne.isChecked() & questionThree.isChecked()){
startActivity(new Intent(getApplicationContext(),HomeActivity.class));
Toast.makeText(this, "Received Report", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "The question is not fully answered.", Toast.LENGTH_SHORT).show();
}
}
}
}
Fragment(with progressBar)
progressBar = view.findViewById(R.id.progressBar);
startProgress = view.findViewById(R.id.addProgress);
startProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(),ReportQuestion.class));
}
});
So basically, my starting point is at the Fragment. What I want to do is that I want to save the progress of the Horizontal progress bar, and after I click the button on it will redirect me to the MainActivity where there will be a button where when I click on it, it will increase the progress bar.
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 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 reset button in Activity A and it works fine since it can clear all the text and display null when the save button in Activity B is clicked. But this only works if there are nothing in the textView before pass to B.
It does not works in below cases.
In Activity A, type " Project 123', click next button go to B. Then I back to Activity A again and click the reset button to clear "Project 123". After done go to Activity B and click submit button. It shows "Project 123" instead of "null"...
Activity A
private TextView c;
String result; // 123
String name; // project
reset=(Button)claims.findViewById(R.id.button14); // reset button
Button button = (Button) claims.findViewById(R.id.button8); //next button
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.setText("");
d.setText("");
e.setText("");
f.setText("");
g.setText("");
h.setText("");
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), B.class);
if(c!=null){
intent.putExtra("name", name);
intent.putExtra("result", result);
}
});
return A;
}
Activity B
Name=getIntent().getExtras().getString("name");
Result=getIntent().getExtras().getString("result");
save=(Button)findViewById(R.id.button8);
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if((Name!=null)&&(Result!=null)){
Toast.makeText(getApplicationContext(), Name+Result, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"null", Toast.LENGTH_LONG).show();
}
}
});
This is because you only clear the setText but not the string.
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.setText("");
name="";
result="";
}
});
You have to add name="" and result="" in your reset method. It should works.
Kindly refer clear a value from a string android
Actually, the name is not null but with empty string ""
Try to take replace the Name != null with !TextUtils.isEmpty() in B activity.
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;
});