Java 在片段内部更改TextView会给我NullPointerException

Java 在片段内部更改TextView会给我NullPointerException,java,android,android-fragments,nullpointerexception,findviewbyid,Java,Android,Android Fragments,Nullpointerexception,Findviewbyid,我试图在片段中更改Textview的文本,但它在setName方法中为我提供了一个NullPointerException 我已经尝试了两种方法: public class MemberFragment extends Fragment { private TextView tvName; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedI

我试图在片段中更改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);
}
或:

但是没有人给我成功。下面是我实例化片段的地方:

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方法中的视图是片段的根视图。 因此,只需在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);

它仍然会导致NullPointerException:/它可以工作,但是由于文本字符串位于MainActivity上,如何更改那里的文本?我应该在片段构造函数上传递文本吗?是的,我会将文本传递给片段。所有UI更改都应该在那里完成。因此,将参数放在一个包中,并将它们添加到片段中。在活动中:Bundle args=new Bundle();args.putString(“您的_文本”,值);Fragment newFragment=新片段();setArguments(args);获取片段中的参数:Bundle b=getArguments();String yourText=b.getString(“your_text”);
 tvName = (TextView) getView().findViewById(R.id.tvProfileName);