How to change background of button on next click - android

Currently I have a list of TextViews whose background get changed when click for the first time. But I also want when user clicks on the second time its background should again change and vice versa.
With my existing code I am only able to change background for the first click, when I am clicking it again its background is not changing.
Here is my code:
public void onClick(View v) {
switch (v.getId()) {
case R.id.goalText1:
if (count <= 2) {
goals.add(mGoal1.getText().toString());
mGoal1.setTextColor(getResources().getColor(R.color.black));
mGoal1.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText2:
if (count <= 2) {
goals.add(mGoal2.getText().toString());
mGoal2.setTextColor(getResources().getColor(R.color.black));
mGoal2.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText3:
if (count <= 2) {
goals.add(mGoal3.getText().toString());
mGoal3.setTextColor(getResources().getColor(R.color.black));
mGoal3.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText4:
if (count <= 2) {
goals.add(mGoal4.getText().toString());
mGoal4.setTextColor(getResources().getColor(R.color.black));
mGoal4.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText5:
if (count <= 2) {
goals.add(mGoal5.getText().toString());
mGoal5.setTextColor(getResources().getColor(R.color.black));
mGoal5.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText6:
if (count <= 2) {
goals.add(mGoal6.getText().toString());
mGoal6.setTextColor(getResources().getColor(R.color.black));
mGoal6.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText7:
if (count <= 2) {
goals.add(mGoal7.getText().toString());
mGoal7.setTextColor(getResources().getColor(R.color.black));
mGoal7.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnGoal:
Intent intent = new Intent(this, fiteness_level_selection.class);
try {
obj.put("SelectedGoal", goals);
} catch (Exception e) {
e.printStackTrace();
}
intent.putExtra("GoalJson", obj.toString());
startActivity(intent);
break;
}
So can anybody suggest me any easy way to achieve it.

Set a boolean array in your activity.
//suppose you've 3 textviews within listview
public boolean isTransparent[] = {false,false,false};
And then do this in your onClick method.
public void onOnclick(View v){
switch (v.getId()) {
//foreach textview do this
case R.id.textView1 :
int color;
if (isTransparent[0])
color = getResources().getColor(android.R.color.transparent);
else
color = getResources().getColor(R.color.white);
isTransparent[0]=!isTransparent[0];
textview1.setBackgroundColor(color);
break;
case R.id.textView2:
// now check for isTransparent[1]
and so on ...
...
}
}

As What I am understand is you want Change background for that you have take bool variable and in Button click you have to check the bool value.
Boolean click_firsttime = false;
Inside your Button click
use this way
If(click_firsttime == false){
//perform task
// and set bool value to true
click_firsttime = true;
}else{
// perform task and set bool value
click_firsttime = false;
}

First create a boolean :
private boolean foo = true;
Then change your code like this :
public void onClick(View v) {
switch (v.getId()) {
case R.id.goalText1:
if (foo) {
goals.add(mGoal1.getText().toString());
mGoal1.setTextColor(getResources().getColor(R.color.black));
mGoal1.setBackgroundColor(getResources().getColor(R.color.white));
count++;
foo = false;
} else {
// set background to another color
foo = true;
}
break;

Related

Headset buttons controls

Now what is happening is it is also controlling other music players. If i have a default music player after starting that if i start playing using my music player and then i press play/pause button in headset it controls default music player.
i have implemented a heaset broadcastreceiver like this,
switch (keyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_HEADSETHOOK:
Log.d("TAG", "TAG: KEYCODE_HEADSETHOOK");
if (MusicService.isPlaying()) {
MusicService.player.pause();
} else {
MusicService.player.start();
}
new MusicService().showNotification();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
Log.d("TAG", "TAG: KEYCODE_MEDIA_PLAY");
if (MusicService.isPlaying()) {
MusicService.player.pause();
} else {
MusicService.player.start();
}
new MusicService().showNotification();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY:
break;
case KeyEvent.KEYCODE_MEDIA_PAUSE:
Log.d("TAG", "TAG: KEYCODE_MEDIA_PAUSE");
break;
case KeyEvent.KEYCODE_MEDIA_STOP:
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
Log.d("TAG", "TAG: KEYCODE_MEDIA_NEXT");
if (MusicService.player.isPlaying()) {
MusicService.player.stop();
}
if (MusicService.songPosn < (MusicService.song.size() - 1)) {
MusicService.songPosn = MusicService.songPosn + 1;
if (SingleInstance.getInstance().getIndexCount()>= 1)
SingleInstance.getInstance().setIndexCount(SingleInstance.getInstance().getIndexCount()-1);
} else {
// play first song
MusicService.songPosn = 0;
}
new MusicService().playSong(true);
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
Log.d("TAG", "TAG: KEYCODE_MEDIA_PREVIOUS");
if (MusicService.player.isPlaying()) {
MusicService.player.stop();
}
if (MusicService.songPosn > 0) {
MusicService.songPosn = MusicService.songPosn - 1;
} else {
// play last song
MusicService.songPosn = MusicService.song.size() - 1;
}
new MusicService().playSong(true);
break;
}
If you are trying to get the hedsethook event in a activity follow the below code :
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HEADSETHOOK:
// Headset key detected
// Do your stuff here
return true;// To let the os know that the event is consumed here
}
}
return super.dispatchKeyEvent(event);
}
Make sure to returt true to consume the event .To get it done in a service use BroadCast receiver as follows:
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
filter.setPriority(1000); //Sets receiver priority
registerReceiver(r, filter);

Display toast for empty fields when user submits data

I have an activity in which there are three EditTexts: First Name, Middle Name, Last Name, and a Submit button. If the user submits with a field blank, a different toast appears for different field. Here's is an example when button will be clicked!:
I'll assume you can figure out how to use a button listener yourself. Inside that button listener, you can use this code:
// create EditText references
EditText etFirstName = (EditText)findViewById(R.id.firstName);
EditText etMiddleName = (EditText)findViewById(R.id.middleName);
EditText etLastName = (EditText)findViewById(R.id.lastName);
// boolean variables that each represent whether or not the each field is blank
// if the EditText length is 0, it's true (blank); otherwise, it's false (filled)
boolean firstNameBlank = etFirstName.length() == 0;
boolean middleNameBlank = etMiddleName.length() == 0;
boolean lastNameBlank = etLastName.length() == 0;
if (firstNameBlank && middleNameBlank && lastNameBlank) {
// toast all three blank
}
else if (firstNameBlank && middleNameBlank) {
// toast just first and middle are blank
}
else if (firstNameBlank && lastNameBlank) {
// toast just first and last are blank
}
else if (middleNameBlank && lastNameBlank) {
// toast just middle and last are blank
}
else if (firstNameBlank) {
// toast just first is blank
}
else if (middleNameBlank) {
// toast just middle is blank
}
else if (lastNameBlank) {
// toast just last is blank
}
else {
// none are blank
}
Try this way
EditText e = (EditText)findViewById(R.id.EDITTEXT));
if(e.getText().length == 0){
//Show Toast
}else{
//continue your code
}
implement onClick() event of your submit button as below:
#Override
public void onClick(View view) {
super.onClick(view);
switch (view.getId()) {
case R.id.btnSubmit:
if(edtFirstName.getText().toString().length() < 1){
Toast.makeText(this, "please fill all boxes.",Toast.LENGTH_LONG).show();
}else if(edtSecondName.getText().toString().length() < 1){
Toast.makeText(this, "please fill middle name and last name.",Toast.LENGTH_LONG).show();
} else if(edtLastName.getText().toString().length() < 1){
Toast.makeText(this, "please fill last name.",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "please wait...processing.",Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}

password minimum and maximum character

I'm trying to have the maximum character of password that i want to set in my android apps. What would be the best way to code it ? I only have the minimum of 6 character and i want to have maximum of 10 character set password. Here is my attempt:
public void UserSignUp() {
if(ET_PASSWORD_SIGNUP.getText().length() >0 && ET_CONFIRM_PASSWORD_SIGNUP.getText().length() >0 &&
ET_PASSWORD_SIGNUP.getText().length() >5 && ET_CONFIRM_PASSWORD_SIGNUP.getText().length() >5)
{
if(ET_PASSWORD_SIGNUP.getText().toString().equals(ET_CONFIRM_PASSWORD_SIGNUP.getText().toString())) {
String SignUpResult = "";
db = DBMANAGER.getWritableDatabase();
SignUpResult = CONTENTMANAGER.saveUserPassword(ET_PASSWORD_SIGNUP.getText().toString(),this);
Toast.makeText(getApplicationContext(), SignUpResult, Toast.LENGTH_SHORT).show();
ActivityLogIn();
} else {
Toast.makeText(getApplicationContext(), "Confirm Password and Password did not match!",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid Input", Toast.LENGTH_SHORT).show();
}
}
Not an answer as such but another solution,
Have a look at https://github.com/ragunathjawahar/android-saripaar, nice annotation library.
You can annotate your password fields and it will handle the logic for you...
#Password(order = 1, minLength = 4, maxLength = 10)
private EditText passwordEditText;
#ConfirmPassword(order = 2)
private EditText confirmPasswordEditText;
private boolean checkPW(String pw, String pw2) {
if(!pw.equals(pw2)){
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_pws_do_not_match), Toast.LENGTH_LONG).show();
return false;
}
if (pw.length() < 4) {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_pw_too_short), Toast.LENGTH_LONG).show();
return false;
}
if(pw.length() > 10){
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_pw_too_long), Toast.LENGTH_LONG).show();
return false;
}
//continue here
return true;
}
});
}
Check this code..
if (ET_PASSWORD_SIGNUP.getText().toString().length() < 6
|| ET_PASSWORD_SIGNUP.getText().toString().length() > 10) {
ET_PASSWORD_SIGNUP.requestFocus();
ET_PASSWORD_SIGNUP.setError("Password should be between 6 to 10 characters long");
}
you can write this code:
// check password
public boolean checkPassword(String password, String confirmPassword) {
boolean state = false;
int passLength = password.length();
if (passLength >= 6) {
if (confirmPassword.length() != 0) {
if (password.equals(confirmPassword)) {
state = true;
} else {
makeToast("Password does't match!");
inputConfirmPassword.setText("");
inputPassword.setText("");
inputPassword.requestFocus();
}
} else {
Toast.makeText(this, "Please enter confirm password",
Toast.LENGTH_SHORT).show();
inputConfirmPassword.setText("");
inputConfirmPassword.requestFocus();
state = false;
}
} else {
Toast.makeText(this, "Please enter 6 digit password",
Toast.LENGTH_SHORT).show();
inputPassword.setText("");
inputPassword.requestFocus();
state = false;
}
return state;
}

Android: check the edit text isempty and submit issue

In my app i have dailog with edittext and submit button, if the edittext is empty
i gave a toast message "please enter something" ..my code is below
Button reviewPost = (Button) dialog.findViewById(R.id.submit);
reviewPost.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
v.setEnabled(false);
EditText ratingComment = (EditText) dialog
.findViewById(R.id.reviewcomment);
String comment = ratingComment.getText().toString();
String postStatus = "Y";
if (spinner.getSelectedItemPosition() > 0) {
postStatus = "N";
}
RadioGroup rating = (RadioGroup) dialog
.findViewById(R.id.customrating);
int radioButtonID = rating.getCheckedRadioButtonId();
View radioButton = rating.findViewById(radioButtonID);
int ratingNo = rating.indexOfChild(radioButton);
String ratingValue = (ratingNo + 1) + "";
if (comment != null && !comment.equalsIgnoreCase("")){
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
activity.finish();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}
Constants.rivewDialog = new ProgressDialog(activity);
Constants.rivewDialog.setCanceledOnTouchOutside(false);
Constants.rivewDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Constants.rivewDialog.setMessage(activity.getString(R.string.postingrivew));
Constants.rivewDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Constants.rivewDialog.show();
dialog.dismiss();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
But even if the edittext is empty it is submitting which should not happen.i am checking the condition as follows but its not working
if (comment != null && !comment.equalsIgnoreCase("")){
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
activity.finish();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}
use comment.trim().equals("") instead of comment.equalsIgnoreCase("")
or put a check on comment string length that it should exceed the minimum characters.
use
if(comment != null && !comment.isEmpty())
You can used this.
if(comment != null && !comment.isEmpty() && comment.length()!=0){
//your task
}else{
//give some message
}
Solved with below code..the problem is with the v.setEnabled(false);...i moved it into the if condition
if (comment != null && !comment.equalsIgnoreCase("")){
v.setEnabled(false);
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
Constants.rivewDialog = new ProgressDialog(activity);
Constants.rivewDialog.setCanceledOnTouchOutside(false);
Constants.rivewDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Constants.rivewDialog.setMessage(activity.getString(R.string.postingrivew));
Constants.rivewDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Constants.rivewDialog.show();
dialog.dismiss();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}

Program Execution is not in proper way

When I click on button in my program without entering data it shows both errors parallely (I have Highlighted in below prog). here i need to get only one error at a time i mean when it is null it has show appropriate one.vice versa..
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v==findViewById(R.id.button1)) {
et1 = (EditText) findViewById(R.id.editText1);
if(et1.getText()!=null ) {
try {
radius = Double.valueOf(et1.getText().toString());
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
if(radius==0.0) {
Toast.makeText(getApplicationContext(), "Value cannot be 0", Toast.LENGTH_SHORT).show();
}
try {
output = (double) Math.round(Math.PI * radius * radius);
String s = Double.toString(output);
tv1.setText(s);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
}
});
do not make things more complicated as they actually are. You can be sure that a correct value was entered without any try/catch blocks. Possible approach:
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Pattern p = Pattern.compile("([0-9]*)");
if (et1.getText().toString().trim().length() > 0) {
Matcher m = p.matcher(et1.getText().toString().trim());
if (m.matches()) {
radius = Double.valueOf(et1.getText().toString());
output = (double) Math.round(Math.PI * radius
* radius);
tv1.setText(Double.toString(output));
} else
Toast.makeText(getApplicationContext(),
"incorrect value", Toast.LENGTH_SHORT)
.show();
} else
Toast.makeText(getApplicationContext(),
"input is empty", Toast.LENGTH_SHORT).show();
break;
default:
}
}
});
In the above code you check if there was any text entered. The second if checks whether the input is numeric using a java regex. When both requirements are met you can be sure the output is calculated correctly.
BTW, using switch-case is a better approach for click listeners

Categories

Resources