[英]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.