一个片段定义如下。我正在尝试设置
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
的函数。这个 ListView
的 onItemClickListener
调用此函数,即 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)'
欢迎提出关于这个问题的任何建议,或者改进代码风格。
非常感谢您的帮助!