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


当前回答

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

活动:

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

其他回答

最好和最方便的方法是调用片段实例并发送数据。 每个片段默认都有实例方法

例如: 如果你的片段名称是MyFragment

所以你会像这样调用你的fragment from activity:

getSupportFragmentManager().beginTransaction().add(R.id.container, MyFragment.newInstance("data1","data2"),"MyFragment").commit();

* R.id。container是我的框架布局的id

所以在MyFragment.newInstance("data1","data2")你可以发送数据到fragment,在你的fragment你得到这个数据在MyFragment newInstance(String param1, String param2)

public static MyFragment newInstance(String param1, String param2) {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

然后在fragment的onCreate方法中,你会得到数据:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

现在mParam1有data1 mParam2有data2 现在你可以在你的片段中使用这个mParam1和mParam2。

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

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();道路

芬兰湾的科特林版:

在活动:

val bundle = Bundle()
bundle.putBoolean("YourKey1", true)
bundle.putString("YourKey2", "YourString")

val fragment = YourFragment()
fragment.arguments = bundle
val fragmentTransaction = parentFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.your_container, fragment, fragment.toString())
fragmentTransaction.commit()

在onCreate()片段中:

var value1 = arguments?.getBoolean("YourKey1", default true/false)
var value2 = arguments?.getString("YourKey2", "Default String")

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 TheFragment setData(TheData data) {
    TheFragment tf = new TheFragment();
    tf.data = data;
    return tf;
}

通过这种方式,我可以确保在任何其他可能需要使用它的操作之前,我需要的所有数据都在Fragment中。 而且在我看来它看起来更干净。