首页 > 解决方案 > How to get an instance of an activity from a fragment in Android?

问题描述

I have a SignInActivity like this:

public class SignInActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        signInButton.setOnClickListener(v -> signIn());

        noAccountButton.setOnClickListener(v -> goToMainActivity());
    }

    private void signIn() {
        //Start auth process
    }
}

My app can be used with or without an account. In both situations the user is redirected to MainActivity. This activity holds a fragment where I display a message such if the users wants to become a user of the app though. I also have a button like this:

public class UserFragment extends Fragment {
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        signInButton.setOnClickListener(v -> {
            instanceOfSingInActivity.signIn();
            //     ^      ^
        });
    }
}

And I need an instance of the SignInActivity so I can call the signIn() method. How can I solve this?

标签: androidandroid-fragmentsandroid-activity

解决方案


推荐阅读