如何保存片段 onButtonClick 并在下一个程序启动时加载

How to save fragment onButtonClick and load on next program start

我有一个应用程序,其中 fragment.Let 将其称为 mainScreen。在 mainScreen 中有一个 buttononClick() 打开第二个片段。我们称它为 FragmentHomePage。在 FragmentHomePage 中,我有一个 retrofit。有一个名为 logOut 的按钮。我的问题是,当用户没有点击注销时,我想保存这个片段并加载这个片段。默认情况下,当应用程序启动时,会打开主屏幕,但如果用户未单击注销,我需要在应用程序启动时打开 FragmentHomePage。我该怎么做?

public class FragmentHomePage extends BaseFragment {

View mainView;
TextView fullName, userName, email;
Button logOut;
ApiClient apiClient = ApiClient.getInstance();
SupportObjToken supportopToken = new SupportObjToken();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mainView = inflater.inflate(R.layout.home_page, container, false);

    init(mainView);
    newTokenCall();

    return mainView;
}

private void init(View v) {
    fullName = v.findViewById(R.id.fullName);
    userName = v.findViewById(R.id.user);
    email = v.findViewById(R.id.mail);
    logOut = v.findViewById(R.id.logOut);
}

public void newTokenCall() {

    String clientID = SharedPreferencesManager.getInstance().getClientID();
    String clientSecret = SharedPreferencesManager.getInstance().getClientSecret();
    String refreshToken = SharedPreferencesManager.getInstance().getRefreshToken();
    String newRefreshToken = SharedPreferencesManager.getInstance().getNewRefreshToken();
    final String firstName = SharedPreferencesManager.getInstance().getFirstName();
    final String lastName = SharedPreferencesManager.getInstance().getLastName();
    final String mail = SharedPreferencesManager.getInstance().getEmail();
    final String user = SharedPreferencesManager.getInstance().getUsername();

    supportopToken.setGrantType("refresh_token");
    supportopToken.setClientId(clientID);
    supportopToken.setClientSecret(clientSecret);
    supportopToken.setRefreshToken(refreshToken);

    Call<ResponseBody> newToken = apiClient.newToken(supportopToken);
    newToken.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                try {
                    String newDataAccess = response.body().string();
                    JSONObject obj = new JSONObject(newDataAccess);

                    String newAccessToken = obj.getString("accessToken");
                    String newRefreshToken = obj.getString("refreshToken");

                    SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
                    SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);

                    fullName.setText(firstName + " " + lastName);
                    userName.setText(user);
                    email.setText(mail);

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            } else if (response.code() == 401) {
                supportopToken.setRefreshToken(SharedPreferencesManager.getInstance().getNewRefreshToken());

                Call<ResponseBody> newToken1 = apiClient.newToken(supportopToken);
                newToken1.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.isSuccessful()) {
                            try {
                                String newDataAccess = response.body().string();
                                JSONObject obj = new JSONObject(newDataAccess);

                                String newAccessToken = obj.getString("accessToken");
                                String newRefreshToken = obj.getString("refreshToken");

                                SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
                                SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);

                                fullName.setText(firstName + " " + lastName);
                                userName.setText(user);
                                email.setText(mail);

                            } catch (JSONException | IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
        }
    });
}}

这部分我该怎么做?谢谢。是的,不投反对票。我是这个网站的新手)).

这是我启动片段的 activity。

public class MainActivity extends AppCompatActivity implements FragmentChangeListener {
FragmentActivity fragmentActivity;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ApiClient.initializeInstance("simple web page");

    fragmentActivity = new FragmentActivity();

    this.replaceFragment(fragmentActivity, true);

    SharedPreferencesManager.init(this);
}

@Override
public void replaceFragment(BaseFragment fragment, Boolean isAddToBackStack) {
    String backStateName = fragment.getClass().getName();
    FragmentManager manager = getFragmentManager();

    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.container, fragment, fragment.toString());
    transaction.addToBackStack(backStateName);
    transaction.commit();
}}

在 SharedPreferences 中保存一个布尔值,默认值为 false。

 PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();

当您访问 FragmentHomePage 时,将此值设置为 true。

PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", true).apply();

当用户单击注销按钮时,再次将此值设置为 false。

PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();

来自保存这些碎片的基地Activity, 当您启动 mainScreen 片段时,使用以下代码检查此值:

PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);

如果值为 true,则启动 HomeFragment,否则启动 mainScreen 片段。

使用此函数启动片段:

public void launchFragmentByReplacing(Fragment fragment, String incomingFragmentTag) {

    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(frameLayout.getId(), fragment, incomingFragmentTag);
    transaction.commit();
    manager.executePendingTransactions();
}

在你的情况下,就在 :

this.replaceFragment(fragmentActivity, true);

检查 SharedPref 值。

Boolean isloggedIn = PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);
    if(isloggedIn) //is true
    this.replaceFragment(new FragmentActivity(), true);
    else
    this.replaceFragment(new FragmentHomePage(), true);

在您的主屏幕按钮 onclick 中,像这样向共享首选项添加一个键

 SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
 editor.putString("state", "logged_in");
 editor.apply();

FragmentHomePage 中的注销按钮 onclick 中添加以下代码

 SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
 editor.putString("state", "logged_out");
 editor.apply();

现在在您的第一个片段的 oncreate 中添加这个

SharedPreferences prefs = getSharedPreferences("APP_PREF", MODE_PRIVATE); 
  String state = prefs.getString("state", "state");
  if(state.equals("logged_in"){
   //load second fragment here
  }