revised background image comparison - java

i know the brainy people wont like my petty questions but im trying to learn
I,m trying to make a pairs game i have been using int so far on my apps but this game needs a different approach ive created the pairs game with ints but confusing code and a floor that pushing same button twice will delete the pair as below ive been trying with tags the code all looks clean as in no errors
public class MainActivity extends Activity {
//added Tag here for the if (pic2.getTag()==(beck));
Tag beck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton pic1 = (ImageButton ) findViewById(R.id.imageButton1);
final ImageButton pic2 = (ImageButton ) findViewById(R.id.imageButton2);
pic1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pic1.setBackgroundResource(R.drawable.becks);
pic1.setTag(R.drawable.becks);
if (pic2.getTag() == pic1.getTag()){
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);}
}});
pic2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pic2.setBackgroundResource(R.drawable.becks);
pic2.setTag(R.drawable.becks);
if (pic1.getTag() == pic2.getTag()){
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);
}
}});
}}
ive tried since my original post to work out how to do ive shown code for 2 buttons all i want to do is compare and make invisible after the second button is clicked
if (pic1.getTag().equals(pic2.getTag())){
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE); }
the .equals crashes the app
pic1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pic1.setBackgroundResource(R.drawable.becks);
pic1.setTag(beck);
if (pic2.getTag()==(beck));{
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);}
}});
this works with or without semi but both buttons dissapear when either button clicked
if (pic1.getTag()==(pic2.getTag())){
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE); }
this changes the image but the buttons don,t disappear when second image clicked trying to not use ints if possible
this line works with comma to
if (pic1.getTag()==(pic2.getTag()))
if (pic1.getTag()==(pic2.getTag()));
with effect of both button disappear on 1 click of either button dread moving to the else if lol
Also can a Tag be removed if the pair of images compared if false eg
if no match remove the button tag and reset all remaining images to Default image as when i put all 24 buttons on i need a reset method
i,m finding the semi colon at end of if statement has different effects to not having can anyone point correct way when and when not to use semi colons

Use tags for saving your image-id:
pic1.setTag(R.drawable.becks);
pic2.setTag(R.drawable.becks);
You can then check and compare those by calling getTag() on the buttons that have been clicked:
public boolean isMatch(View x, View y) {
return x.getTag() == y.getTag();
}

Related

i have made one app to get ascii value of my character that i am going to put in my edit text but when i press my button to conver my app gets closed

i have made one app to get ascii value of my character that i am going to put in my edit text. i have made the code as-> `
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.button);
TextView textview=findViewById(R.id.textView2);
EditText edittext=findViewById(R.id.editTextTextPersonName);
String sipla=edittext.getText().toString();
Button button2 = findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int t=sipla.charAt(0);
textview.setText("THE ASCII value of your character = "+t);
}
});`
but when i click my button my app gets closed. one more think
when i make certain changes in my code and put String sipla=edittext.getText().toString(); in my button setonclick function it works and everything is normal please tell me why my app was not working prevously .
The reason your app is crashing is because sipla is empty, and you try to get the first character from an empty string. The reason it is empty is that you get it in onCreate, before the user has had a chance to enter anything in the EditText. Even if they enter something later, you never update the value of sipla.
The fix for this is simple - don't get the value from the EditText until you are actually ready to use it and the user would have had time to enter something - so get it inside onClick.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// This code runs as the activity is getting set up
Button button=findViewById(R.id.button);
TextView textview=findViewById(R.id.textView2);
EditText edittext=findViewById(R.id.editTextTextPersonName);
Button button2 = findViewById(R.id.button2);
// if you get the value of edittext here it will always be empty,
// at this point the user hasn't even seen the screen yet
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// This code runs much later, when the user
// clicks the button
// Don't get the string until you are ready to process it, this code
// doesn't run until the user clicks the button, at which
// time edittext may also have a user value in it
String sipla = edittext.getText().toString();
if( !sipla.isEmpty() ) {
int t=sipla.charAt(0);
textview.setText("THE ASCII value of your character = "+t);
}
else {
textview.setText("You didn't enter anything");
}
}
});
}
Also, if your app crashes, look in the Logcat tab to see the full error message and stack trace. Learn to read that - it is an invaluable debugging skill. Also, learn to use Log/print statements in your code to help you understand what values are being used and what order things are run in when you are confused.

How to select a button by default on activity run?

I want to include two simple buttons in my activity, for example, "Start" and "End".
Now i want "Start" button to be selected by default (with any background color) when i run my activity. How to do that through java in Android studio?
Note:- i am not talking about radio button's small circle. I am talking about simple button.
use setBackgroundColor method.
btn1.setBackgroundColor(Color.GREEN);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// your code here
}
});

How Do I Change the onClick() Behavior of a Button?

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.

Can a ToggleButton change the functionality of other buttons in the same Activity?

Summed up, can a ToggleButton change what other buttons in the activity do when toggled? If so, a more specific explanation of what I want to do is below:
Basically there are three buttons and a togglebutton. When the togglebutton is toggled, pressing any of the three buttons will take a picture and 'save it' for that button. When untoggled, pressing any of the three buttons simply displays their images. I think I can figure out the camera capture part, but I need some direction when it comes to the togglebutton.
Any help is appreciated and I can explain further if necessary.
What I would do is keep a couple flags for each state at the class level, like this:
public class MyClass {
private static final int STATE_SAVE = 0;
private static final int STATE_DISPLAY = 1;
private int currentState = STATE_DISPLAY;
// I made this default for the example,
// you should use what makes sense to your project.
}
Then, inside your toggle button, you can set the flag. Paraphrasing this code since I don't have an editor open:
toggleButton.setOnToggleListener(new OnToggleListener() {
#Override
public void onToggled(boolean toggled) {
if(toggled) {
currentState = STATE_SAVE;
} else {
currentState = STATE_DISPLAY;
}
});
Now, when the buttons are clicked, you can switch based on the state to do an action:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(currentState == STATE_SAVE) {
// Save the image.
} else if (currentState == STATE_DISPLAY) {
// Display the image.
}
});
Create a boolean such as isToggleOn that is true or false depending on the ToggleButton. Then for each of your buttons, you can simply do:
Button button1 = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isToggleOn){
//do one thing
} else {
//do other thing
}
}
});
Yes, you definitely can. Very rarely is anything impossible with code!
All you have to do is to change the listener of the three buttons when the togglebutton is pressed. You keep alternating between the listeners each time you toggle.
For your purpose, I'd suggest defining two sets of listeners - two for each of the three buttons and then keep changing between them.

Android onClickListener - Android Studio bug or my own mistake?

The previous snippet of code has been written down by the aid of random sites and answers from StackOverflow, but somehow not working. I should add that I am an absolute beginner at making apps and my experience with Java is very limited as well.
The errors is the following:
"setOnClickListener": Marked red.
"public void onClick(View v) {": Here "v" is marked red, for some
reason. It continues being red in "String text = v.toString();".
The program also finds my semicolon redundant at the end of the
snippet.
I am using the beta of Android Studio on Elementary OS, using OpenJDK.
Button button_1 = (Button) findViewById(R.id.btn_1);
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text = v.toString();
displayPassword(text);
}
});
I could have made any number of mistakes, that's for sure. But any nudge in the right direction would be very appreciated.
My suggestion is:Set the onClick in the XML file, and create the method in the current class.
<Button
android:id="#+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click" />
public void click(View arg0) {
}
Agree with Graph that you should have to #Override the onClick method. Not sure what's wrong with it there. In fact, when I typed your example into Android Studio, I got 3 letters into OnClickListener and it automatically filled in the rest, including the #Override.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = v.toString();
// do something with the text.
}
});
Also, I don't think v.toString() is going to get you any useful information. If you want the text off the button, you're going to want to cast it to a button then call getText():
Button button = (Button) v;
String text = button.getText().toString();
or, you could do:
String text = ((Button)v).getText().toString();
Simply calling v.toString() is going to get you a description of that button, not the text on it.
I believe you need to #Override the onClick method.
Button button_1 = (Button) findViewById(R.id.btn_1);
button_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = v.toString();
displayPassword(text);
}
});
Just press " ctrl+shift+o " and add 1 library which you shows on screen prob solved

Categories

Resources