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


当前回答

Very old post, still I dare to add a little explanation that would had been helpful for me. Technically you can directly set members of any type in a fragment from activity. So why Bundle? The reason is very simple - Bundle provides uniform way to handle:-- creating/opening fragment -- reconfiguration (screen rotation) - just add initial/updated bundle to outState in onSaveInstanceState() -- app restoration after being garbage collected in background (as with reconfiguration). You can (if you like experiments) create a workaround in simple situations but Bundle-approach just doesn't see difference between one fragment and one thousand on a backstack - it stays simple and straightforward. That's why the answer by @Elenasys is the most elegant and universal solution. And that's why the answer given by @Martin has pitfalls

其他回答

你也可以从片段访问活动数据:

活动:

public class MyActivity extends Activity {

    private String myString = "hello";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        ...
    }

    public String getMyData() {
        return myString;
    }
}

片段:

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        MyActivity activity = (MyActivity) getActivity();
        String myDataFromActivity = activity.getMyData();
        return view;
    }
}

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

有时你可以在你的活动中接收Intent,你需要将信息传递给你的工作片段。 给出的答案是OK,如果你需要启动片段,但如果它仍在工作,setArguments()不是很有用。 如果传递的信息将导致与UI交互,则会出现另一个问题。在这种情况下,你不能调用像myfragment.passData()这样的东西,因为android会迅速告诉只有创建视图的线程可以与之交互。

所以我的建议是使用接收器。这样,您可以从任何地方发送数据,包括活动,但是工作将在片段的上下文中完成。

在你的片段的onCreate():

protected DataReceiver dataReceiver;
public static final String REC_DATA = "REC_DATA";

@Override
public void onCreate(Bundle savedInstanceState) {


    data Receiver = new DataReceiver();
    intentFilter = new IntentFilter(REC_DATA);

    getActivity().registerReceiver(dataReceiver, intentFilter);
}

private class DataReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        int data= intent.getIntExtra("data", -1);

        // Do anything including interact with your UI
    }
}

在你的活动:

// somewhere
Intent retIntent = new Intent(RE_DATA);
retIntent.putExtra("data", myData);
sendBroadcast(retIntent);

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

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

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

如果一个活动需要一个片段在初始化后执行一个动作,最简单的方法是让这个活动调用片段实例上的一个方法。在这个片段中,添加一个方法:

public class DemoFragment extends Fragment {
  public void doSomething(String param) {
      // do something in fragment
  }
}

然后在活动中,使用片段管理器访问片段并调用方法:

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DemoFragment fragmentDemo = (DemoFragment) 
            getSupportFragmentManager().findFragmentById(R.id.fragmentDemo);
        fragmentDemo.doSomething("some param");
    }
}

然后活动可以通过调用此方法直接与片段通信。