Carts
Carts

Reputation: 11

How can I make a button visible in one activity when clicking a button in another? - Android

So I have a simple quiz game where the user writes his answer on an EditText and then click the buton "Check" to check if his answer is correct. If his answer is correct, the button on the other activity will be visible. What i want to know is that, is it possible to control an object on another activity? In vb.net you can just simply do this by "formName.Button1.Visible=true". What about Android? Thanks for your help :)

Upvotes: 1

Views: 448

Answers (1)

dsrees
dsrees

Reputation: 6286

Answers the Question

Add a flag to your starting intent that is consumed by the receiving acitivty

public class ActivityA extends Activity {
    public static final String EXTRA_IS_CORRECT = "extra_is_correct";

    private void startActivityB() {
        Intent intent = new Intent(context, ActivityB.class);
        intent.putExtra(EXTRA_IS_CORRECT, true);
        startActivity(intent);
    }
}

And then in ActivityB where you are displaying the button

@Override
public void onCreate(Bundle savedInstanceState) {
    Intent startingIntent = getIntent();
    boolean isCorrect = intent.getBooleanExtra(ActivityA.EXTRA_IS_CORRECT, false);

    if(isCorrect) {
        // hide/show button
    }
}

What you should do

Look into fragments and have 1 activity hosting 2 fragments. Then the activity can talk directly to each fragment without sending intents.

Upvotes: 1

Related Questions