How to compare images in Android (java) - java

I recently started learning to code with Android Studio. And I wanted a button when clicked to toggle between two images, but I cant seem to compare them.
I tried comparing them but it doesn't think they are the same.
ImageView dog = new ImageView(this);
dog.setImageResource(R.drawable.dog);
ImageView goofy = new ImageView(this);
goofy.setImageResource(R.drawable.goofydog);
if(img==dog)
{
img.setImageResource(R.drawable.goofydog);
}
else{
img.setImageResource(R.drawable.dog);
}

You can only compare primitive types (String, Int, Double...) in If statements, if you compare object it will compare the instance of each object which in your case is different.
If you want to toggle between two images based on what your imageView is actually displaying you should compare the Int resources that is displayed like that :
Image img = findViewById(R.id.image_view);
Button button = findViewById(R.id.button);
String current = "";
button.setOnClickListener(new View.OnClickListener( v-> {
#Override
void onClick(View v){
if (img.getDrawable() == ResourcesCompat.getDrawable(getResources(),
R.drawable.dog, null)) {
img.setImageResource(R.drawable.goofyDog);
} else {
img.setImageResource(R.drawable.dog);
}
}
}));
If you want to learn more about using objects in If statement, you can learn more about instance of object here : https://en.wikipedia.org/wiki/Instance_(computer_science)

You can't compare images the way you are doing. If you want to toggle between two images using a button, you can simple do:
Image img = findViewById(R.id.image_view);
Button button = findViewById(R.id.button);
String current = "";
button.setOnClickListener(new View.OnClickListener( v-> {
#Override
void onClick(View v){
if (current = "Dog") {
img.setImageResource(R.drawable.dog);
current = "Dog";
} else {
img.setImageResource(R.drawable.goofydog);
current = "Goofy";
}
}
}));

Related

Reset Button to default background

I know that was already asked but it is outdated:
I have 2 buttons that represent 2 choices and if one is selected the background color gets changed to yellow. But if i want to change the choice i need to somehow reset the button:
I already try to set it back but some old design comes out. Can you provide me the id of the modern button style? And show me how to implement it?
int myChoice;
if (view == findViewById(R.id.choice1)){
myChoice = 1;
choice1.setBackgroundColor(getResources().getColor(R.color.highlightButton));
choice2.setBackgroundResource(android.R.drawable.btn_default);
}
else if (view == findViewById(R.id.choice2)){
myChoice = 2;
choice2.setBackgroundColor(getResources().getColor(R.color.highlightButton));
choice1.setBackgroundResource(android.R.drawable.btn_default);
}
}
Use Tags with getBackground(). This will assure you are always setting back to original.
Add following in beginning of function
if (v.getTag() == null)
v.setTag(v.getBackground());
Then instead of setBackgroundResource, use
v.setBackground(v.getTag());
Starting from here, you can store the default color of the button into a Drawable and grab the selection color (Yellow in your case) into anther Drawable, then toggle background colors of buttons with these Drawable variables
please check below demo
public class MainActivity extends AppCompatActivity {
private Drawable mDefaultButtonColor;
private Drawable mSelectedButtonColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn1 = findViewById(R.id.btn1);
final Button btn2 = findViewById(R.id.btn2);
mDefaultButtonColor = (btn1.getBackground());
mSelectedButtonColor = ContextCompat.getDrawable(this, R.color.buttonSelected);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleButton(btn1, true);
toggleButton(btn2, false);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleButton(btn1, false);
toggleButton(btn2, true);
}
});
}
private void toggleButton(Button button, boolean isSelected) {
button.setBackground(isSelected ? mSelectedButtonColor : mDefaultButtonColor);
}
}

Removing and adding values in Array or ArrayList (efficiently) - Android/Java

I'm a bit stuck with an exercise I'm making.
I basically have 4 buttons and have to hide one if a checkbox is checked.
I don't know why but I just can't figure out how to do this, should I make an arrayList instead of an array and remove/add the value constantly or is there another way to 'hide' or not use a value?
Hope my explanation is a bit clear, thanks in advance! :)
Here's the code MainActivity.java code (not including imports):
public class MainActivity extends AppCompatActivity {
String globalColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setColor();
}
private int randomColor(int length){
return (int) Math.floor(Math.random()*length);
}
private void setColor(){
String [] colors = {"Green", "Blue", "Red", "Magenta"};
//ArrayList<String> colors = new ArrayList<String>();
int rndColor = randomColor(colors.length); //color name for text
int rndColor2 = randomColor(colors.length); //color for text color
if(rndColor2 == rndColor){
rndColor2 = randomColor(colors.length);
}
globalColor = colors[rndColor];
TextView v = (TextView) findViewById(R.id.color);
v.setText(colors[rndColor]);
v.setTextColor(Color.parseColor(colors[rndColor2]));
}
public void checkColor(View v){
Button b = (Button)v;
String buttonText = b.getText().toString();
TextView txtview = (TextView) findViewById(R.id.result);
if(buttonText.equals(globalColor)){
txtview.setText("Yaay");
setColor();
} else {
txtview.setText("Booo");
setColor();
}
}
private void hideMagenta(){
CheckBox checkbox = (CheckBox)findViewById(R.id.checkbox);
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
//this is where my problem is; I want to remove magenta as an option
//is it better to do this with an arraylist and to remove and add magenta to the arraylist
//or is there a different, more efficient way
}
}
});
}
}
You have tons of options. You can use an ArrayList like you suggested, you can pass the list of available colors to the setColor method. Maybe you can pass the color you don't want to use and then when randoming do if(randomedColor == colorYouDontWant) then random again. You can even use Map<String, Color> and put all the colors in there and then just delete them from this map, randoming would be quite weird tho. Or Map<String, Boolean> where key would be color and value would be if color is available or not (true if available, false otherwise). I suggest using ArrayList.
btw. this fragment:
if(rndColor2 == rndColor){
rndColor2 = randomColor(colors.length);
}
I understand that you don't want colors to be the same, but what if randoming again is gonna give the same result? You should do:
while(rndColor2 == rndColor)

Loop through each child element and compare its text in java

I am trying to build an android app that gets some questions from a database and its possible answers (the answers are created dynamically as UI buttons). What I have managed so far is that once the user clicks on an answer, if the answer is right the button's colour becomes green, and if the answer is wrong the colour becomes red. What I want to achieve is in case the answer was wrong, change the button's colour to red and find the button with the correct answer and change it's colour to green. I am currently trying to do this by looping through every child element of the clicked button's parent, and comparing its text with the right answer given from the database. This is what my code looks like:
final TableRow textRow = new TableRow(this);
textRow.addView(questionText, rowParamsQuestions);
layout.addView(textRow, layoutParams);
for(final String option : currentQuestion.getOptions())
{
final Button button = new Button(this);
button.setText(option);
button.setTextSize(16);
button.setBackgroundResource(R.drawable.rounded_shape);
button.setTextColor(Color.WHITE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button clicked = (Button) v;
if (!answeredQuestions.containsKey(currentQuestion)) {
answeredQuestions.put(currentQuestion, clicked.getText().toString());
if (clicked.getText().equals(currentQuestion.getAnswer())) {
clicked.setBackgroundResource(R.drawable.right_answer);
} else {
clicked.setBackgroundResource(R.drawable.wrong_answer);
for (int i = 0; i < textRow.getChildCount(); i++) {
View child = textRow.getChildAt(i);
if (child instanceof Button) {
if (((Button) child).getText().equals(currentQuestion.getAnswer())) {
child.setBackgroundResource(R.drawable.right_answer);
}
}
}
}
Thank you very much!

Overriding default screen contents in android

I am developing a quiz app and my activity looks like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//click this button to go to the next question
mButton = (Button)findViewById(R.id.nextButton);
//open the DB
openDB();
//Check if the table has data
if(!(myDb.checkDataExists())) {
insertRows();
}
//display a random question
displayQuestion();
}
private void displayQuestion() {
randomNumber = getRandomNumber();
//check if number used or not
if (isNumberNew(String.valueOf(randomNumber))) {
Cursor cursor = myDb.getRow(randomNumber);
displayRecordSet(cursor, optionAnswer);
mOptionButton1.setBackgroundColor(color);
mOptionButton2.setBackgroundColor(color);
mOptionButton3.setBackgroundColor(color);
mOptionButton4.setBackgroundColor(color);
flag = true;
}
}
private void displayRecordSet(Cursor cursor, Map<String, String> optionAnswer) {
int id = 0;
String question = "", option = "", rightAnswer = "";
ArrayList<String> optionList = new ArrayList<String>();
mImageView = (ImageView)findViewById(R.id.storyImageView);
mQuestionTextView = (TextView)findViewById(R.id.questionTextView);
mOptionButton1 = (Button)findViewById(R.id.button);
mOptionButton2 = (Button)findViewById(R.id.button2);
mOptionButton3 = (Button)findViewById(R.id.button3);
mOptionButton4 = (Button)findViewById(R.id.button4);
}
if (cursor.moveToFirst()) {
do {
id = cursor.getInt(0);
question = cursor.getString(1);
option = cursor.getString(3);
rightAnswer = cursor.getString(5);
optionList.add(option);
optionAnswer.put(option,rightAnswer);
} while (cursor.moveToNext());
mQuestionTextView.setText(question);
mOptionButton1.setText(optionList.get(0));
mOptionButton2.setText(optionList.get(1));
mOptionButton3.setText(optionList.get(2));
mOptionButton4.setText(optionList.get(3));
}
cursor.close();
}
The displayQuestion method is supposed to get a random question from the db and then override the values of the option buttons and the question text view. However, when the app starts, the first question is still the one that I hardcoded in my view. In other words, when I call the setContentView(R.layout.activity_quiz); ... I am putting default values in for the option buttons and the question text view. But, I don't want to display those values because they are just place holders. I want to display the question from the database, which I get through dipslayQuestion method.
Does anyone know how to fix this?
There doesn't seem to be enough info to help you. What does displayRecordSet do and how are mOptionButtonX defined? Maybe you intended to change the text of buttons, not the background color?
Also, 2 things. Try to use more descriptive variable names instead of "flag" and such. Secondly, you shouldn't hardcode text into layout files you never want to use. Just set the text to "", you'll overwrite it anyway.

how do i get imageViews to be able to go back and forth between imageviews?

not sure if i should use switch and case or if statements or what???
ImageView m1 = (ImageView) findViewById(R.id.imageView1);
m1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(on=true)
{
v.setBackgroundResource(R.drawable.music2);
on=false;
}
if(on=false)
{
v.setBackgroundResource(R.drawable.music);
on=true;
}
If on is a boolean, you can just do that:
if(on){
v.setBackgroundResource(R.drawable.music2);
}else{
v.setBackgroundResource(R.drawable.music);
}
on = !on;
NOTE: I guess your code is not working now because of this: if(on=true), here you are setting a value on on, if you want to compare, you should actually use ==. In this case, with a boolean, you don't even need to compare.

Categories

Resources