我有两门课。第一个是活动,第二个是片段,其中有一些EditText。在活动中,我有一个带有async-task的子类,在方法doInBackground中,我得到了一些结果,我保存到变量中。我怎么能把这个变量从子类“我的活动”到这个片段?


当前回答

我在这里@ stackoverflow.com找到了很多答案,但这绝对是正确的答案:

“发送数据从活动碎片在android”。

活动:

        Bundle bundle = new Bundle();
        String myMessage = "Stackoverflow is cool!";
        bundle.putString("message", myMessage );
        FragmentClass fragInfo = new FragmentClass();
        fragInfo.setArguments(bundle);
        transaction.replace(R.id.fragment_single, fragInfo);
        transaction.commit();

片段:

读取片段中的值

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle bundle = this.getArguments();
        String myValue = bundle.getString("message");
        ...
        ...
        ...
        }

或者只是

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        String myValue = this.getArguments().getString("message");
        ...
        ...
        ...
        }

其他回答

如果你将片段(具体子类)的引用传递给异步任务,你就可以直接访问片段。

将片段引用传递给异步任务的一些方法:

如果你的异步任务是一个完全成熟的类(类FooTask扩展AsyncTask),那么将你的片段传递到构造函数中。 如果您的异步任务是一个内部类,只需在异步任务定义的范围内声明一个最终的Fragment变量,或者作为外部类的字段。您将能够从内部类访问它。

你可以在fragment中创建公共静态方法,在那里你将获得该fragment的静态引用,然后将数据传递给该函数,并将该数据设置为相同方法的参数,并通过getArgument获取fragment的oncreate方法的数据,并将该数据设置为局部变量。

在片段和活动之间传递数据的最聪明的方法是创建一个变量,例如:

class StorageUtil {
  public static ArrayList<Employee> employees;
}

然后通过onActivityCreated方法将数据从fragment传递给activity:

//a field created in the sending fragment
ArrayList<Employee> employees;

@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
         employees=new ArrayList();

       //java 7 and above syntax for arraylist else use employees=new ArrayList<Employee>() for java 6 and below

     //Adding first employee
        Employee employee=new Employee("1","Andrew","Sam","1984-04-10","Male","Ghanaian");
        employees.add(employee);

      //Adding second employee
       Employee employee=new Employee("1","Akuah","Morrison","1984-02-04","Female","Ghanaian");
         employees.add(employee);

        StorageUtil.employees=employees;
    }

现在您可以获得StorageUtil的值。来自各地的员工。 古德勒克!

只是偶然发现了这个问题,而上面的大多数方法都是有效的。 我只是想补充一点,你可以使用事件总线库,特别是在组件(活动或片段)还没有创建的情况下,它适用于所有规模的android项目和许多用例。我个人在我在playstore上的几个项目中使用过它。

将数据从活动类发送到片段的更好方法是通过setter方法传递。就像

FragmentClass fragmentClass = new FragmentClass();
fragmentClass.setMyList(mylist);
fragmentClass.setMyString(myString);
fragmentClass.setMyMap(myMap);

并且很容易从类中获得这些数据。