I'm coding an application that deals with 2 different CheckBoxes. When one CheckBox gets clicked, the color of the tick should be blue (instead of green), whereas the color of the other CheckBox remains green.
This is my code...
CheckBox green = (CheckBox) findViewById(R.id.greenButton);
CheckBox blue = (CheckBox) findViewById(R.id.blueButton);
blue.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if(arg1){
blue.setHighlightColor(Color.BLUE);
Toast.makeText(getBaseContext(), "Question Marked As Partial", 4000).show();
}
}
});
green.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if(arg1){
blue.setHighlightColor(Color.GREEN);
Toast.makeText(getBaseContext(), "Question Marked As Fully Understood!", 4000).show();
}
}
});
However, both the CheckBoxes tick colors remains green, and the Toast message doesn't get displayed, so I am guessing that the OnCheckedChangeListener is never being called.
Could someone offer any advice?
If the Toast isn't appearing, it is possible that your listeners aren't actually being set on the CheckBoxes. In other words, maybe this whole piece of code isn't even being called.
If your code is in a method, make sure you're calling the method to set the listeners on the CheckBoxes, or ensure this code is in one of your main methods such as onCreate().
If you don't know already, it would be a great time to learn how to debug your code - it makes it really quick and easy to determine whether your code is being called or not.
Related
There are 4 checkboxs in a dialog layout. I want to hide or disable to be checked three other ones if the first checkbox is checked. But if all or one of the other three checkboxs is checked, the first checkbox must be hidden or disabled in the layout.
Get the references(ids) using root.findViewById() hold them in the list.
Now in the onCheckChangeListener() loop through the list and uncheck all except the selected one. or do whatever is your requirement with them.
try this:
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked)
{
// hide what you want example chkbox2.setVisibility(View.GONE);
}
else
{
// visualize what you have hidden in the if example chkbox2.setVisibility(View.VISIBLE);
}
}
});
I have an activity where I have elements like, ImageView, Switch, EditText, TextView, when changing screen orientation some elements returned me to their initial value, to solve it use onSaveInstanceState and onRestoreInstanceState to store and retrieve the information when changing the orientation of screen. It seems to work fine except for one detail with a Toast.
I have a TextView called dateOfNotification that shows a date that the user has selected, it starts with visibility = "gone", I also have a Switch with the following code:
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(switch1.isChecked()){
if(dateOfNotification.getVisibility() == View.VISIBLE){
hour.setText("08:00");
}
else{
Toast.makeText(tareas.this, "First enter a date", Toast.LENGTH_SHORT).show();
switch1.setChecked(false);
}
}
}
});
The important thing to note here is that switch1 cannot be activated if dateOfNotification is gone.
Now for the change of screen orientation without losing data I have:
protected void onSaveInstanceState( final Bundle outState ) {
super.onSaveInstanceState(outState);
outState.putInt("visDate", dateOfNotification.getVisibility());
outState.putBoolean("statusSW1", switch1.isChecked());
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
dateOfNotification.setVisibility(savedInstanceState.getInt("visDate"));
switch1.setChecked(savedInstanceState.getBoolean("statusSW1"));
}
The problem is:
When dateOfNotification is visible and switch1 is Checked and I change orientation, values remain dateOfNotification is visible and switch1 is Checked, but I don't know why the Toast "First enter a date" shows me, It is assumed that when dateOfNotification is visible, the Toast should not be shown, the rarer is that to show the Toast, the dateOfNotification is considered to be hidden, but then why doesn't the switch disable me?
else{
Toast.makeText(tareas.this, "First enter a date", Toast.LENGTH_SHORT).show();
switch1.setChecked(false);
}
It does not seem logical to me that only the Toast.makeText(tareas.this, "First enter a date", Toast.LENGTH_SHORT).show(); is executed and that the switch1.setChecked(false); is not executed
EDIT
By testing I understood what is happening, the state of switch1 is always saved with or without onSaveInstanceState, then when rotating the screen dateOfNotification is Gone, but the state of switch1 is retrieved and activated, when setOnCheckedChangeListener sees that switch1 has been activated dateOfNotification is hidden then it shows the Toast and the switch1 is turned off, then with onRestoreInstanceState the visibility of the dateOfNotification and the state of switch1 are recovered, then now it is activated again.
So I would like to know if there is some way to make the state of switch1 not load automatically when rotating the screen, which can only be loaded with onRestoreInstanceState
I'm really not sure where to go with this question because I don't necessarily know how possible it is. I'm still somewhat new to Android Studio and coding overall, but I know enough to be dangerous (perhaps that's my problem - I may be thinking too grandiose for a beginner) but this is what I'm looking to do.
I have a single page app with several buttons. I'm creating an app that is essentially a score counter for an NFL game, and the section where my choices for scoring methods looks as follows:
The above section is a Horizontal LinearLayout with 2 Nested LinearLayouts for the 4 scoring buttons on each side. The vertical toggle buttons are already set to change the text on the bottom button from Fieldgoal to Safety and vice-versa depending on the True/False of the toggle for each side.
teamOneToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
teamTwoToggleButton.setChecked(false);
teamOneSafety.setText("SAFETY");
teamTwoSafety.setText("FIELDGOAL");
} else {
teamTwoToggleButton.setChecked(true);
teamTwoSafety.setText("SAFETY");
teamOneSafety.setText("FIELDGOAL");
} } });
I have that part figured out, but since a Safety scores as 2 points and a fieldgoal scores as 3 points, I need to be able to change the onClick behavior.
I was hoping that there was a Java function that would let me set a new onClick activity much like I can setText, setColor, setAlignment, set(whatever), but I can't find anything close.
I've also played around with trying to define a string based on a .getText() from the button itself, but my application crashes every time.
If anyone has any ideas my full code is here on my Github.
If I understand your question you want to change the OnClickListener.
Currently you define it in your XML:
android:onClick="touchdownClickTeamOne" //This is not recommended practice, now you know.
You should do this in your Java code instead:
Button teamOneTouchDown = findViewById(R.id.team_one_off_td);
teamOneTouchDown.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do stuff
}
});
Now you know how to redefine any button's OnClickListener.
I'm not sure how to set it up in a way to programmatically do "this" if the button displays 'Safety' and do "that" if the button displays 'Fieldgoal'.
Currently you use this method:
public void fieldgoalClickTeamOne (View v) {
scoreTeamOne = scoreTeamOne + 3;
displayForTeamOne(scoreTeamOne);
}
We know the View v is a Button and that's Buttons are TextViews, so let's check the text:
public void fieldgoalClickTeamOne (View v) {
TextView textView = (TextView) v; // Could cast to Button, makes no difference here
if (textView.getText().toString().equals("SAFETY") {
// Do this
} else {
// Do that
}
}
PS I'm happy to see a beginner following coding conventions, your code is very easy to read. I have a few pointers.
First you should take a moment to learn the difference between if, else if, and else. Your AdapterView should only have on if statement and many else ifs.
Second you should take some time to learn about generic coding practices and/or reusability (this concept is a little tricky). Back to your AdapterViews, you only need one OnItemSelectedListener:
OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
final ImageView imageView;
if (adapterView.getId() == R.id.teamOneSpinner)
imageView = (ImageView) findViewById(R.id.team_one_spinner_team_logo);
else
imageView = (ImageView) findViewById(R.id.team_two_spinner_team_logo);
String s=((TextView)view).getText().toString();
if(s.equals("Arizona Cardinals"))
imageView.setImageResource(R.drawable.arizona_cardinals);
else if(s.equals("Atlanta Falcons"))
imageView.setImageResource(R.drawable.atlanta_falcons));
else if(s.equals("Baltimore Ravens"))
//etc, etc
Viola, one listener for multiple spinners. Set it like so:
teamOneSpinner.setOnItemSelectedListener(onItemSelectedListener);
teamTwoSpinner.setOnItemSelectedListener(onItemSelectedListener);
See how much writing I saved you! Many of your methods are repetitive, you can remove 80% of your code with these techniques.
I have a set of EditText fields generated by a for loop. Each time that field is edited, I need to run some calculations and update other text fields (think excel spreadsheet sums).
My logic is working, and I even have it set up to replace the last field's down focus change to the first field (to avoid the "Done" button showing on the keyboard).
However, if the user presses the Back button to dismiss the keyboard, the focus is not changed and the calculations are not done. The entered number is different but now the totals are wrong. I can't find where to detect when the keyboard is dismissed so I can work around this.
What I have now:
final EditText etWeight = new EditText(this);
etWeight.setText("initWt");
etWeight.setSelectAllOnFocus(true);
etWeight.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
//code to update after weight is changed
}
));
llWeightRow.addView(etWeight);
I have also tried putting this code in setOnEditorActionListener, setOnClickListener, and setOnKeyListener.
Aside from some of these not working as expected, none of them appear to trigger if the back button is pressed to dismiss the keyboard. I have searched online but only came up with suggestions on how to manually hide the keyboard with my own button; I can't seem to find anything concerning the back button on the tablet itself.
How can I detect that the keyboard has been dismissed so I can force a focus change (or just re-run the calculation code)?
Update:
Not marking this as answered because this doesn't answer this specific question, but I currently am producing my desired results (other fields always updated) by switching to a onTextChanged method. Now the values are updated whenever any text inside the EditText is changed.
etWeight.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence cs, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence cs, int i, int i1, int i2) {
//calc and update code
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Have you tried to override onBackPressed? You can make your manipulations with focus there.
#Override
public void onBackPressed() {
// Make needed preparations here
super.onBackPressed();
}
try this
InputMethodManager imm = (InputMethodManager) ActivityName.this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isAcceptingText()) {
Log.d(TAG,"Software Keyboard was shown");
} else {
Log.d(TAG,"Software Keyboard was not shown");
}
This is what I'm trying to do. I have 3 text boxes, a submit button and image on the screen. I want the image to go away if any of the text boxes are touched to input data for the login credentials. The reason is that the soft keyboard pushes the image up into the text boxes when the user tries to input anything. I tried the setOnClickListener but it appears that takes two clicks into the field using the AVD. So I'm trying to use OnTouchListener and it's not going well.
It is asking me to remove the qualifier because of an 'expected Class or package'. It wants to remove the login from this line of code.
login.OnTouchListener(new View.OnTouchListener(){
It happens with the other two text boxes which are name 'phone' and 'password'.
Next, if I remove the qualifier then it complains about a Method call expected and wants to do an insert which changes the code to this.
new View.OnTouchListener(new View.OnTouchListener() {
Then it complains about 'OnTouchListener' is abstract; cannot be instantiated' and wants to implement a method, which gives an error at the end about an expected ). When this is added the whole cycle starts over with the same error messages.
Here's the pieces that I believe are important.
The import statement
import android.view.View.OnClickListener;
The variables that I'm using for the OnTouchListner.
final EditText phone = (EditText) findViewById(R.id.phone1);
final EditText login = (EditText) findViewById(R.id.uname);
final EditText pass = (EditText) findViewById(R.id.password);
The onTouchListener that I need so I can make the image invisible and not overlap the text box input.
login.OnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
image.setVisibility(View.INVISIBLE);
return true;
}
return false;
}
});
The method signature you're looking for is login.setOnTouchListener(new View.OnTouchListener() { ... }
The reason this is happening is because OnTouchListener is a class, not a method.
The correct way to add an OnTouchListener is to call
setOnTouchListener( listener )
So, for your code,
login.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
image.setVisibility(View.INVISIBLE);
return true;
}
return false;
}
});