[英]Passing ArrayList from Fragment class to Activity
我有主片段,我想将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) );
现在,我想将“ allStudents”对象发送到新的活动类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);
...
}
}
提前致谢!
在您的Fragment中创建一个自定义界面:
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;
}
然后,您只需要使用Fragment中的Listener来启动此方法:
OnFragmetInteractionListener listener = (OnFragmentInteractionListener) activity;
listener.onFragmentStudents(allStudents)
在您的Activity
:
Bundle bundle = getIntent().getExtras();
ArrayList allStudents = bundle.get("ExtraData");
而且我认为您需要将ArrayAdapter
定义为:
arrayAdapter = new ArrayAdapter<Student>(this, R.layout.student_list, allStudents);
您拥有其余的代码,只需添加上面的代码即可。 它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.