将ArrayList从Fragment类传递给Activity [英] Passing ArrayList from Fragment class to Activity

查看:124
本文介绍了将ArrayList从Fragment类传递给Activity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have main fragment and I want to pass ArrayList to Activity class, where I will show the result in 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();

Now I want to send "allStudents" object to new activity class StudentResult();

我在片段类中使用:

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

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

and in target class to show the objects in 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);
    ...
    }
}

提前感谢!

推荐答案

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

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)

这篇关于将ArrayList从Fragment类传递给Activity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆