首页 > 解决方案 > 将意图从活动发送到片段

问题描述

我想将意图从活动发送到片段。我知道如何像这样从片段发送到活动

Intent chatIntent = new Intent(getContext(), ChatActivity.class);
                                            chatIntent.putExtra("user_id", user_id);
                                            chatIntent.putExtra("user_name", userName);
                                            startActivity(chatIntent);

但现在我想从活动发送到片段。我不一定需要启动片段,我只想让我的活动中的 id 之一在我的片段中可访问。

标签: androidandroid-fragments

解决方案


从您的activity,您发送您的数据,使用bundle

Bundle newBundle = new Bundle();
newBundle.putString("key", "text");
YourFragment objects = new YourFragment();
objects.setArguments(newBundle);

fragment的功能类onCreateView

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    if(getArguments() != null){
        String yourText = getArguments().getString("key");  
    }
    return inflater.inflate(R.layout.your_fragment, container, false);
}`

推荐阅读