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


当前回答

从Activity中,你用Bundle发送数据为:

Bundle bundle = new Bundle();
bundle.putString("data", "Data you want to send");

// Your fragment
MyFragment obj = new MyFragment();
obj.setArguments(bundle);

并在Fragment的onCreateView方法中获取数据:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
    String data = getArguments().getString("data");// data which sent from activity  
    return inflater.inflate(R.layout.myfragment, container, false);
}

其他回答

有时你可以在你的活动中接收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);

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

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

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

我在使用最新的导航体系结构组件时遇到了类似的问题。通过从我的调用活动传递一个包到Fragment,尝试了上述所有代码。

紧跟Android最新发展趋势的最佳解决方案是使用View Model (Android Jetpack的一部分)。

在父Activity中创建并初始化一个ViewModel类,请注意这个ViewModel必须在Activity和fragment之间共享。

现在,在片段的onViewCreated()中,初始化相同的ViewModel并设置观察者来监听ViewModel字段。

如果你需要,这里有一个有用的,深入的教程。

https://medium.com/mindorks/how-to-communicate-between-fragments-and-activity-using-viewmodel-ca733233a51c

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 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");
    }
}

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