收到改造响应后调用片段(文本视图和按钮在片段内为空)

Calling fragment after recieved retrofit response (textview and button are null inside fragment)

我正在学习 Android 并且遇到了非常奇怪的行为。我在 android 中使用 Retrofit2 作为 REST 库(使用异步调用)。我想按照 Google 在我的服务器上建议的方式发送 authCode 和 TokenId。当我检查用户是否设置了密码时,我会做出回应。如果我 return 代码 206 表示用户尚未在我的后端服务器上设置密码。 所以我想开始一个用户将输入密码的片段(我还说我定义了 LoginFragment 和 RegistrationFragment 都在这个 Activity 上工作)。但这是诀窍,Fragment 被调用,当我的 onCreateView 在那里执行时,但 TextView 和 Button 具有 null 值,这是为什么?我假设存在问题,因为这是后台线程上的 运行 但我可能弄错了。有没有更好的方法来实现我想要的?

这应该可以解决它:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    super.onCreate(savedInstanceState);

    View rootView =  inflater.inflate(R.layout.fragment_set_password, container, false);
    return rootView;
}

@Override
public void onViewCreated(View view){
Button setPasswordButton = (Button) view.findViewById(R.id.btn_set_password_ok);
    TextView textView = (TextView) view.findViewById(R.id.set_password_message);


    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    String username = prefs.getString("username", "User");

    textView.setText(String.format(getString(R.string.set_password_message), username));

    setPasswordButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setPasswordValidate();
        }
    });

}

注意:我不太记得 onViewCreated 方法的确切参数,但视图肯定在那里。所以我想这应该可行。

我知道我的问题描述并没有指出我发现的真正问题,但我仍然会 post 它,因为它可能会对某人有所帮助。我的情况是 xml 文件中的问题我刚刚删除了 android:fillViewport="true" 或将其设置为 false 并且有效。