![](/img/trans.png)
[英]Accessing TextView inside a fragment is giving NullPointerException
[英]Change TextView inside Fragment gives me NullPointerException
我正在尝试在片段内更改Textview的文本,但是它在setName方法上给了我NullPointerException。
我已经尝试了两种方法来做到这一点:
public class MemberFragment extends Fragment {
private TextView tvName;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_member,container, false);
tvName = (TextView) getView().findViewById(R.id.tvProfileName);
return view;
}
public void setName(String name) {
tvName.setText(name);
}
要么:
public class MemberFragment extends Fragment {
private static TextView tvName;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_member,container, false);
return view;
}
public void setName(String name) {
tvName = (TextView) getView().findViewById(R.id.tvProfileName);
tvName.setText(name);
}
但没有一个给我成功。 这是我实例化片段的位置:
MemberFragment fragment = new MemberFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
fragment.setName(map.get(Tags.NAME));
和fragment_member.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@style/ActionBar.Transparent.MyStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="446dp" >
<TextView
android:id="@+id/tvProfileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
</ScrollView>
有人能帮我吗?
谢谢。
onCreateView方法中的view是片段的rootView。 因此,只需在您的onCreateView方法中添加以下代码即可更改TextView的文本:
((TextView)view.findViewById(R.id.tvProfileName)).setText("Your new text");
尝试这个:
tvName = (TextView) view.findViewById(R.id.tvProfileName);
代替 :
tvName = (TextView) getView().findViewById(R.id.tvProfileName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.