在片段中访问TextView时出现NullPointerException。

3
一个片段定义如下。我正在尝试设置positionTextView的文本。
public class Fragment2 extends Fragment {
    private TextView positionTextView,fragment2TextView;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.layout_fragment2, container, false);
        positionTextView = view.findViewById(R.id.positionTextView);
        fragment2TextView = view.findViewById(R.id.fragment2TextView);

        Toast.makeText(getContext(),"OnCreateView",Toast.LENGTH_LONG).show();
        return  view;

    }

    public void setContentOfTextView( int position) {
        positionTextView.setText(Integer.toString(position));
    }
}

MainActivity 中,我按照如下方式添加了 Fragment2

@Override
public void fragmentRespond(int index) {
    FragmentTransaction transaction =  fragmentManager.beginTransaction();
    Fragment2 fragment2 = new Fragment2();
    transaction.add(R.id.group2,fragment2,"fragment2");
    transaction.commit();
    transaction.addToBackStack("fragment2");
    fragment2.setContentOfTextView(index);
}

我在另一个包含 ListView 的碎片中有一个名为 fragmentRespond 的函数。这个 ListViewonItemClickListener 调用此函数,即 fragmentRespond(int index)

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    String[] quotes = getResources().getStringArray(R.array.quotes);
    CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(getContext(),quotes,null);
    listView.setAdapter(customArrayAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            fragmentCommunicator.fragmentRespond(position);
        }
    });
}

我遇到了以下错误:

java.lang.NullPointerException: 尝试对空对象引用调用方法'void android.widget.TextView.setText(java.lang.CharSequence)'

欢迎提出关于这个问题的任何建议,或者改进代码风格。

非常感谢您的帮助!

1个回答

2
您之所以会收到NPE错误,是因为在您尝试使用活动中的setContentOfTextView函数设置文本时,Fragment的视图尚未加载。

为了加载其中的内容,您需要先膨胀片段中的视图。因此,您应该在片段的onCreateView函数中完成这个步骤。

关于从活动传递信息 - 您可以在从活动启动片段时使用Bundle轻松完成这一点。

以下是如何实现这一点的方法。

在您的活动中,通过传递Bundle来启动片段并传递数据。

@Override
public void fragmentRespond(int index) {

    // Prepare the bundle
    Bundle bundle = new Bundle();
    bundle.putInt("index", index);

    FragmentTransaction transaction =  fragmentManager.beginTransaction();
    Fragment2 fragment2 = new Fragment2();
    fragment2.setArguments(bundle); // Set the arguments here to be passed on to your fragment while loading.

    transaction.add(R.id.group2,fragment2, "fragment2");
    transaction.commit();
    transaction.addToBackStack("fragment2");
}

在你的片段中,从那个Bundle中获取所需的数据并将其加载到你的TextView中。

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view =  inflater.inflate(R.layout.layout_fragment2, container, false);
    positionTextView = view.findViewById(R.id.positionTextView);
    fragment2TextView = view.findViewById(R.id.fragment2TextView);

    // Load the information in your TextView here
    Bundle args = getArguments();
    if (args != null && args.containsKey("index")) {
        setContentOfTextView(args.getInt("index"));
    }

    Toast.makeText(getContext(),"OnCreateView",Toast.LENGTH_LONG).show();
    return  view;
}

我希望你能明白这些内容。

非常感谢您的回复。我会尝试一下。 - Prashanth T P
1
只是评论一下,这是个很棒的答案! - Gaurav Mall
1
谢谢!@GauravMall - Reaz Murshed
是的,它成功地克服了NPE。 - Prashanth T P
1
非常感谢@ReazMurshed。 - Prashanth T P
很好。很高兴知道我能帮忙! - Reaz Murshed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接