将ArrayList从Fragment类传递给Activity

时间:2014-06-06 13:23:23

标签: java android android-fragments

我有主片段,我想将ArrayList传递给Activity类,我会在ListView中显示结果。

片段类:

public class StudentActivity extends Fragment implements OnClickListener {
}

我有数据

ArrayList<> allStudents = new ArrayList();
allStudents.add(new Student("H", 99, 93) );    
allStudents.add(new Student("C", 98, 92) );
allStudents.add(new Student("B", 98, 91) );    
allStudents.add(new Student("A", 80, 94) );
allStudents.add(new Student("F", 70, 84) );

现在我想发送&#34;所有学生&#34;对象到新的活动类StudentResult();

我在片段类中使用:

Intent intent = new Intent(getActivity(), StudentResult.class);
intent.putExtra("ExtraData", allStudents);
startActivity(intent);

并在目标类中显示ListView();

中的对象
public class ResultActivity extends Activity {

    public void myData(ArrayList<allStudents> myArray) {
    marjslistview = (ListView) findViewById(R.id.listView1);
    arrayAdapter = new ArrayAdapter<allStudents>(this, R.layout.student_list, myArray);
    ...
    ScoreLV.setAdapter(arrayAdapter);
    ...
    }
}

提前感谢!

2 个答案:

答案 0 :(得分:5)

在片段中创建自定义界面:

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

在您的活动中实施此界面:

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

现在你必须覆盖声明的方法(在Activity中):

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

然后你只需要在片段中使用监听器启动此方法:

OnFragmetInteractionListener listener = (OnFragmentInteractionListener) activity;
listener.onFragmentStudents(allStudents)

答案 1 :(得分:1)

Activity

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

我认为您需要将ArrayAdapter定义为:

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

你有其余的代码,只需添加上面的代码。它应该工作。