How to change the image of a button

2019-07-27 13:56发布

问题:

My problem here is how to display a new image for button after it was clicked but the condition is from the other class. Im a newbie here and I want to know how to connect the class from other class. I tried the Intent ...

Here is my code

This is the class of our Question...

@Override
// TODO Auto-generated method stub
public void onClick(View v) {
    String answer = "Marianas Trench";
    String answer2 = "marianas trench";
    String answer3 = "MARIANAS TRENCH";

    String check = input.getText().toString();
    if (check.contentEquals(answer)){
        tvresult.setText("Correct");
        Intent myIntent= new Intent("com.turtleexploration.LEVEL1");
        startActivity(myIntent);
    }else if (check.contentEquals(answer2)){
        tvresult.setText("Correct");
        Intent myIntent= new Intent("com.turtleexploration.LEVEL1");
        startActivity(myIntent);
    }else if (check.contentEquals(answer3)){
        tvresult.setText("Correct");
        Intent myIntent = new Intent("com.turtleexploration.LEVEL1");
        startActivity(myIntent);
    }else{
        tvresult.setText("Wrong");
    }

    Intent intObj = new Intent(Question.this, Level1.class);
    intObj.putExtra("ANSWER", answer);
    startActivity(intObj);          
}

And this is the Question Selection class..

ImageButton l1 = (ImageButton) findViewById(R.id.l1);
    TextView t1 = (TextView) findViewById(R.id.t1);
    Intent intename = getIntent();
    String mainans = "Marianas Trench";
    String ans = (String) intename.getSerializableExtra("ANSWER");
    if (ans == mainans){
        l1.getBackground().equals(getResources().getDrawable(R.drawable.m1));
        t1.setText("Correct");
    }else{

    }

The button is in the Question Selection menu...

回答1:

it seems that you did not use the Bundle which carries the data. Intent only calls for the next activity. Bundle must be included.

like:

Bundle b = new Bundle();
b.putString("ANSWER", answer);

Intent intObj = new Intent(Question.this, Level1.class);
b.putExtras(b);
startActivity(intObj);

and in the next class. use this to get the data passed:

    Bundle b = new Bundle();

    b = getIntent().getExtras();
   String Gotanswer = b.getString("ANSWER");

and use the string Gotanswer to use it.

BUT one more thing, if you wanna pass the string ANSWER to the next class, it would be impossible in this code because inside your every condition, there is a line that starts the next class such as:

Intent myIntent = new Intent("com.turtleexploration.LEVEL1");
        startActivity(myIntent);

doing this will start the next class without passing through the intObj code below. this is if I'm not mistaken. :)

plus, instead of using If-Else-If , switch is much better for this kind.

Explain your issue further when you see this answer.

Kaya yan pre! haha