如何在Fragment中设置TextView的值? [英] How to set value of a TextView in Fragment?
问题描述
我在动态应用程序中使用片段,其中User.java文件包含值,而 TabbedActivity.java
文件包含三个片段.我想将文本设置为 ProfileFrgament.java
中的 TextView
.因此,我在 fragment_profile.xml
中创建了一个 TextView
,并使用以下代码
I am using fragments in my dynamic application, where the User.java file contains the values and TabbedActivity.java
file contains three fragments. I want to set the text to TextView
in ProfileFrgament.java
. So, I created a TextView
in fragment_profile.xml
and referenced it from TabbedActivity.java
file with the following code
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停止如何解决这个问题?
It does not shows any compilation error, but after opening TabbedActivity.java
, the app stops with NullPointerException at line name.setText(user.getUsername());
How to solve this issue?
这是 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);
}
推荐答案
您的 TextView
位于 fragment_profile.xml
中,而您试图找到该 TextView
TabbedActivity.java
中的code>,因此发生了 NullPointerException
Your TextView
is in fragment_profile.xml
and you trying to find that TextView
in TabbedActivity.java
, so NullPointerException
is occured
将此代码放在 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;
}
这篇关于如何在Fragment中设置TextView的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!