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


当前回答

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

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

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

其他回答

我在使用最新的导航体系结构组件时遇到了类似的问题。通过从我的调用活动传递一个包到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

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

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

使用以下接口在活动和片段之间进行通信

public interface BundleListener {
    void update(Bundle bundle);
    Bundle getBundle();
}

或者使用下面这个通用监听器进行双向通信使用接口

 /**
 * Created by Qamar4P on 10/11/2017.
 */
public interface GenericConnector<T,E> {
    T getData();
    void updateData(E data);
    void connect(GenericConnector<T,E> connector);
}

片段显示法

public static void show(AppCompatActivity activity) {
        CustomValueDialogFragment dialog = new CustomValueDialogFragment();
        dialog.connector = (GenericConnector) activity;
        dialog.show(activity.getSupportFragmentManager(),"CustomValueDialogFragment");
    }

你也可以在onAttach(context)中将你的上下文转换为GenericConnector

在你的活动中

CustomValueDialogFragment.show(this);

在你的片段中

...
@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        connector.connect(new GenericConnector() {
            @Override
            public Object getData() {
                return null;
            }

            @Override
            public void updateData(Object data) {

            }

            @Override
            public void connect(GenericConnector connector) {

            }
        });
    }
...
    public static void show(AppCompatActivity activity, GenericConnector connector) {
            CustomValueDialogFragment dialog = new CustomValueDialogFragment();
            dialog.connector = connector;
            dialog.show(activity.getSupportFragmentManager(),"CustomValueDialogFragment");
        }

注意:千万不要像"".toString().toString().toString();道路