Passing ArrayList from Fragment class to Activity

后端 未结 2 801
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 11:54

I have main fragment and I want to pass ArrayList to Activity class, where I will show the result in ListView.

Fragment class:

         


        
相关标签:
2条回答
  • 2020-12-11 12:34

    Create an custom interface in your Fragment:

    public interface OnFragmentInteractionListener {    
        public void onFragmentSetStudents(ArrayList<Student>);         
    }
    

    Implement this interface in your Activity:

    public class YourActivity extends Activity implements YourFragment.OnFragmentInteractionListener {
       private ArrayList<Student> allStudents;
    }
    

    Now you have to override the declared method (in your Activity):

    @Override
    public void onFragmentSetStudents(ArrayList<Student> students) {
      allStudents = students;
    }
    

    Then you just have to start this method with an Listener in your Fragment:

    OnFragmetInteractionListener listener = (OnFragmentInteractionListener) activity;
    listener.onFragmentStudents(allStudents)
    
    0 讨论(0)
  • 2020-12-11 12:38

    In your Activity:

    Bundle bundle = getIntent().getExtras(); 
    ArrayList allStudents = bundle.get("ExtraData");
    

    and I think you need to define your ArrayAdapter as:

    arrayAdapter = new ArrayAdapter<Student>(this, R.layout.student_list, allStudents);
    

    You have the rest of the code, just add the above. It should work.

    0 讨论(0)
提交回复
热议问题