如何在 Fragment 中设置 TextView 的值?

How to set value of a TextView in Fragment?

我在我的动态应用程序中使用片段,其中 User.java 文件包含值,TabbedActivity.java 文件包含三个片段。我想在 ProfileFrgament.java 中将文本设置为 TextView。因此,我在 fragment_profile.xml 中创建了一个 TextView 并使用以下代码从 TabbedActivity.java 文件中引用它

    name = findViewById(R.id.name);
    //getting the current user
    User user = SharedPrefManager.getInstance(this).getUser();
    //setting values to textviews
    name.setText(user.getUsername());

它没有显示任何编译错误,但在打开 TabbedActivity.java 后,应用程序在第 name.setText(user.getUsername()); 行停止并出现 NullPointerException 如何解决此问题?

这是ProfileFragment.java文件的代码

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    name = getActivity().findViewById(R.id.name);
    //getting the current user
    User user = SharedPrefManager.getInstance(getActivity()).getUser();
    //setting values to textviews
    name.setText(user.getUsername());

    return inflater.inflate(R.layout.fragment_profile, container, false);
}

您的 TextViewfragment_profile.xml 中,而您试图在 TabbedActivity.java 中找到 TextView,所以 NullPointerException 出现了

将此代码放入 ProfileFrgament.java

用这个更改您的代码

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) 
{ 
    final View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
    name = (TextView) rootView.findViewById(R.id.name);
    User user = SharedPrefManager.getInstance(getActivity()).getUser(); 
    name.setText(user.getUsername()); 

    return rootView;
}

与 activity 的 java 文件相比,您需要在片段的 java 文件中执行此操作。 现在用于在片段中查找视图。 替换此代码:

name = findViewById(R.id.name);

至:

name = getActivity().findViewById(R.id.name);

其余代码可以按原样编写。

也将此类操作放在onViewCreated方法中。将此代码放入 onCreateView 可能会使应用程序崩溃。