【问题标题】:Passing ArrayList from Fragment class to Activity将 ArrayList 从 Fragment 类传递给 Activity
【发布时间】:2014-06-06 13:23:22
【问题描述】:

我有主要片段,我想将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);
    ...
    }
}

提前致谢!

【问题讨论】:

  • ArrayList菱形运算符在Android中不可用
  • "public class StudentActivity extends Fragment" 这不可能。
  • 阅读文章developer.android.com/training/basics/fragments/…,你就会明白如何组织活动片段交流。
  • 你在哪里接触到这个?如果您回复将不胜感激:)

标签: java android android-fragments


【解决方案1】:

在你的 Fragment 中创建一个自定义接口:

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

在你的Activity中实现这个接口:

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)

【讨论】:

  • 更正:public void onFragmentSetStudents(ArrayList&lt;Student&gt; students);
【解决方案2】:

在你的Activity

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

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

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

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

【讨论】:

  • @carebro:以前的工作,但你也很完美!但我不能回答其中两个
猜你喜欢
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多