我的Singleton课程:这是我在官方文档中发现的Singleton课程。

    public class Singleton {
    private static Singleton uniqInstance;
    private Singleton() {
    }
    public static Singleton getInstance() {
        if (uniqInstance == null) {
            {
                if (uniqInstance == null)
                   uniqInstance = new Singleton();
            }
        }
        return uniqInstance;
    }
   }


我的第一个片段:这是我的第一个片段,在这里,我要添加带有对象类名称的ArrayList项。

     public View onCreateView(LayoutInflater inflater, ViewGroup
          container, Bundle savedInstanceState){
          View mView = inflater.inflate(R.layout.fragment_first, container,false);
          RecyclerView rvFirst = mView.findViewById(R.id.rv_first_layout);
          rvFirst.setHasFixedSize(true);
          rvFirst.setLayoutManager(new LinearLayoutManager(mView.getContext()));
          mArrayList = new ArrayList<Names>();
          mArrayList.add(new Names("Hello"));
          mArrayList.add(new Names("This"));
          mArrayList.add(new Names("Is"));
          mArrayList.add(new Names("Android"));

          // HERE I WANT TO SEND ARRAY-LIST DATA TO THE SECOND FRAGMENT
          mAdapter = new NameAdapter(mArrayList);
          rvFirst.setAdapter(mAdapter);
          return mView;
    }


我的第二个片段:这是我的第二个片段,在这里,我试图从第一个片段中获取ArrayList项。

     public View onCreateView(LayoutInflater inflater, ViewGroup
          container,Bundle savedInstanceState){
          View mView = inflater.inflate(R.layout.fragment_second, container,false);
          rvSecond = (RecyclerView) mView.findViewById(R.id.rv_second_layout);
          rvSecond.setHasFixedSize(true);
          rvSecond.setLayoutManager(new LinearLayoutManager(getContext()));
          mArrayList = new ArrayList<Names>();

          // HERE I WANT TO GET ARRAY-LIST FROM FIRST FRAGMENT
          mAdapter = new NameAdapter(mArrayList);
          rvSecond.setAdapter(mAdapter);
     return mView;
   }

最佳答案

首先像这样在单例类中设置arraylist

您的单例课程应该是这样的:

public class Singleton {
private static Singleton uniqInstance;
public ArrayList<Names> names = new ArrayList<Names>();;
private Singleton() {
}
public static Singleton getInstance() {
    if (uniqInstance == null)
         uniqInstance = new Singleton();
    return uniqInstance;
}
public void setArrayList(ArrayList<Names> names)
 {
      this.names = names;

     }
 public ArrayList<Names> getArrayList()
 {
      return this.names;

     }
}



  在列表中添加值后的第一个片段中:-


Singleton.getInstance().setArrayList(mArrayList);



  在您的第二个片段中,如下所示:-


Singleton.getInstance().getArrayList();

07-27 17:28