Fragment中Firebase获取的用户信息无法在TextView显示问题求助
问题修复方案
根因定位
你在Fragment的onCreateView生命周期方法中重复加载了布局:
- 第一次加载布局得到
view实例后,已经完成了所有TextView的赋值操作 - 方法最终返回时又重新调用
inflater.inflate()生成了一个全新的未做任何数据绑定的布局实例,最终页面展示的是这个空白的新布局,因此看不到赋值内容。
修复代码
修改onCreateView方法的返回值,直接返回已经完成数据绑定的view实例即可,同时可以直接使用方法传入的inflater加载布局,不需要额外获取Activity的LayoutInflater,修改后完整代码如下:
package com.example.testmechin; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.testmechin.Common.Common; public class Userprofile_frag extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 直接使用传入的inflater加载布局 View view = inflater.inflate(R.layout.fragment_userprofile_frag, container, false); TextView username = (TextView) view.findViewById(R.id.usernameedittxt); TextView phonenumber = (TextView) view.findViewById(R.id.phoneedittxt); TextView useremail = (TextView) view.findViewById(R.id.emailedittxt); username.setText(Common.userName()); useremail.setText(Common.currentUser!=null?Common.currentUser.getEmail():""); phonenumber.setText(Common.currentUser!=null?Common.currentUser.getPhonenumber():""); Log.d("userPhone: ",Common.currentUser.getEmail()); // 返回已经完成赋值的view,不要重新加载布局 return view; } }
内容的提问来源于stack exchange,提问作者Mech
相关产品推荐
相关产品推荐

