在Fragment中更改TextView会给我NullPointerException

时间:2014-09-16 22:21:36

标签: 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 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>

有人可以帮助我吗?

感谢。

2 个答案:

答案 0 :(得分:2)

onCreateView方法中的

视图是片段的rootView。 因此,只需在onCreateView方法中添加以下代码即可更改TextView的文本:

((TextView)view.findViewById(R.id.tvProfileName)).setText("Your new text");

答案 1 :(得分:0)

试试这个:

tvName = (TextView) view.findViewById(R.id.tvProfileName);

而不是:

 tvName = (TextView) getView().findViewById(R.id.tvProfileName);