Vlad
Vlad

Reputation: 2773

About creating new Intent in android

I am practising some android development. I created a button in the main activity that opens second activity:

I use this code for the button:

 this.detailsBtn = (Button) findViewById(R.id.details_btn);
    this.detailsBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent k = new Intent(arg0.getContext(), DetailsActivity.class); 
            startActivity(k);
        }
    });

This code works properly as it opens the second activity. I also added a button that leads back to main activity in DetailsActivity.

this.mainListBtn = (Button) findViewById(R.id.main_list_btn);
    this.mainListBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent k = new Intent(arg0.getContext(), MainActivity.class); 
            startActivity(k);
        }
    });

This also works properly. My question is should I create new Intent each time I press whatever of the buttons as it is looks like it needs some time to open the new activity?

Is there a way to access the intent which is already created instead of recreating it?

Upvotes: 0

Views: 224

Answers (3)

Rajeev
Rajeev

Reputation: 1404

If you want both the activities to be present and do not want to call finish(), then you can simply bring back existing activity to front using

Intent i = new Intent(getActivity(), B.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);   
getActivity().startActivity(i);

Upvotes: 1

KEYSAN
KEYSAN

Reputation: 885

You can access activity previously opened also you can call by onBackPressed(); function to previous activity.

Upvotes: 1

Pankaj Kumar
Pankaj Kumar

Reputation: 82938

Only call finish() into DetailsActivity

this.mainListBtn = (Button) findViewById(R.id.main_list_btn);
    this.mainListBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
           finish();
        }
    });

This also works properly. My question is should I create new Intent each time I press whatever of the buttons as it is looks like it needs some time to open the new activity?

You current application works fine, I agreed. But what will happen is, new Activity will get added into application stack on each time when button pressed. That should not be happen in your case.

Upvotes: 2

Related Questions