在Fragment之间传递数据到Activity

问题描述 投票:0回答:9

我需要在5个

fragments
到1个
Activity
之间传递数据,当我到达第5个
fragments
时,那些
fragment
会一个接一个地发送数据,那么我需要存储所有5个
fragments
数据,我们怎么办做这个。任何想法都很棒。enter image description here

android android-activity fragment
9个回答
60
投票

将数据从每个fragment传递给activity,当activity获取到所有数据后进行处理。 您可以使用接口传递数据。

片段:

public class Fragment2 extends Fragment {

  public interface onSomeEventListener {
    public void someEvent(String s);
  }

  onSomeEventListener someEventListener;

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
        try {
          someEventListener = (onSomeEventListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
        }
  }

  final String LOG_TAG = "myLogs";

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment2, null);

    Button button = (Button) v.findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        someEventListener.someEvent("Test text to Fragment1");
      }
    });

    return v;
  }
}

活动:

public class MainActivity extends Activity implements onSomeEventListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Fragment frag2 = new Fragment2();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.fragment2, frag2);
        ft.commit();
    }

  @Override
  public void someEvent(String s) {
      Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1);
      ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
  }
}

13
投票

以下链接解释了片段之间通信的设计。

与其他片段通信

为了允许Fragment与其Activity进行通信,您可以在Fragment类中定义一个接口并在Activity中实现它。 Fragment 在其 onAttach() 生命周期方法期间捕获接口实现,然后可以调用接口方法以便与 Activity 进行通信。

这是 Fragment 到 Activity 通信的示例:

public class HeadlinesFragment extends ListFragment {

OnHeadlineSelectedListener mCallback;

// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
    public void onArticleSelected(int position);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

...
}

现在,片段可以通过使用 OnHeadlineSelectedListener 接口的 mCallback 实例调用 onArticleSelected() 方法(或接口中的其他方法)来向 Activity 传递消息。

例如,当用户单击列表项时,将调用片段中的以下方法。 Fragment 使用回调接口将事件传递给父 Activity。

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Send the event to the host activity
    mCallback.onArticleSelected(position);
}

实现接口

为了从片段接收事件回调,托管它的活动必须实现片段类中定义的接口。

例如,以下活动实现了上面示例中的接口。

public static class MainActivity extends Activity
    implements HeadlinesFragment.OnHeadlineSelectedListener{
...

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment
    // Do something here to display that article
}
}

向片段传递消息

宿主 Activity 可以通过使用 findFragmentById() 捕获 Fragment 实例来向 Fragment 传递消息,然后直接调用 Fragment 的公共方法。

例如,假设上面显示的活动可能包含另一个片段,用于显示上面回调方法中返回的数据指定的项目。在这种情况下,活动可以将回调方法中收到的信息传递给将显示该项目的另一个片段:

public static class MainActivity extends Activity
    implements HeadlinesFragment.OnHeadlineSelectedListener{
...

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment
    // Do something here to display that article

    ArticleFragment articleFrag = (ArticleFragment)
            getSupportFragmentManager().findFragmentById(R.id.article_fragment);

    if (articleFrag != null) {
        // If article frag is available, we're in two-pane layout...

        // Call a method in the ArticleFragment to update its content
        articleFrag.updateArticleView(position);
    } else {
        // Otherwise, we're in the one-pane layout and must swap frags...

        // Create fragment and give it an argument for the selected article
        ArticleFragment newFragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putInt(ArticleFragment.ARG_POSITION, position);
        newFragment.setArguments(args);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }
   }
 }

9
投票

我尝试了以上所有方法,但对我不起作用。这就是我让它工作的方式。我使用接口作为将数据从片段发送到活动的手段。

FragmentToActivity.java

public interface FragmentToActivity {
void communicate(String comm);

}

片段一

public class FragmentOne extends Fragment {

private FragmentToActivity mCallback;


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        mCallback = (FragmentToActivity) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString()
                + " must implement FragmentToActivity");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_login, container, 
false);
sendData("Andrews");

return v;
}
@Override
public void onDetach() {
    mCallback = null;
    super.onDetach();
}

public void onRefresh() {
    Toast.makeText(getActivity(), "Fragment : Refresh called.",
            Toast.LENGTH_SHORT).show();
  }
private void sendData(String comm)
    {
    mCallback.communicate(comm);

    }

 }


}

活动一

public class Account extends AppCompatActivity implements 
  FragmentToActivity{

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

@Override
public void communicate(String s) {


    Log.d("received", s);
      }


}

6
投票

您必须将信息返回到片段的活动。并且您的 Activity 将信息分派到其片段:

// In fragment A
((ParentActivity)getActivity()).dispatchInformations("test");

// In ParentActivity
public void dispatchInformations(String mesg){
    fragmentB.sendMessage(mesg);
}

这是一个基本示例


2
投票

您可以使用上面答案中解释的通信器模式。 另外,您可以使用RxJava2。以获得更好的解耦和效率。

1- 创建总线:

public final class RxBus {

    private static final BehaviorSubject<Object> behaviorSubject
        = BehaviorSubject.create();


    public static BehaviorSubject<Object> getSubject() {
        return behaviorSubject;
    }

}

2- 发送者活动或片段

//the data to be passed
MyData  data =getMyData();
RxBus.getSubject().onNext(data) ;

3-接收者活动或片段

private Subscription subscription;

public onCreate(Bundle savedInstanceState){
    subscription = RxBus.getSubject()
                    .subscribe(new Subscriber<Object>() {

            @Override
            public void onNext(Object o) {
                if (o instanceof MyData) {
                    Log.d("tag", (MyData)o.getData();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
}

4-取消订阅以避免内存泄漏:

@Override
protected void onDestroy() {
    super.onDestroy();
 if(subscription!=null){
     subscription.unsubscribe();
   }

}

1
投票

有一种非常简单的方法可以将数据从 Fragment 传递到不是其容器的另一个 Activity。

1)在片段中:当您启动活动时,例如 onButtonClick,在您的意图中传递您想要作为额外传递的数据,如下所示:

     Intent intent = new Intent(getActivity(), MapsActivity.class);
     intent.putExtra("data", dataString);
     startActivity(intent);

2)在接收 Activity 中:在 onCreate 方法中,创建一个 Bundle 来检索传递的信息,如下所示:

Bundle extras = getIntent().getExtras();
    if (extras != null) {
        receivingString = extras.getString("data");
    } else {
        // handle case
    }

希望有帮助:)


1
投票

Fragment 库提供了两种通信选项:

  1. 共享 ViewModel
  2. 片段结果 API。

推荐的选项取决于用例。要与自定义 API 共享持久数据,请使用 ViewModel。对于可放入捆绑包中的数据的一次性结果,请使用片段结果 API。

请阅读此内容 https://developer.android.com/guide/fragments/communicate#java


0
投票

我正在寻找一种将数据从片段传递到活动的解决方案。我就是这样做的,我发现它最适合我的需要。

我发现最好使用全局共享和更新数据

shared ViewModel

在共享 ViewModel 中,我使用可变实时数据存储和更新数据,并将其范围限定在 MainActivity 中。 ViewModel 是一个单例,一直保留在内存中,直到 Activity 生命周期结束。

class SharedViewModel: ViewModel() {

    private val selectedItems: MutableLiveData<List<Product>> =
        MutableLiveData<List<Product>>(listOf())

    fun getItems(): LiveData<List<Product>> {
        return selectedItems
    }

    fun sendSelectedItems(items: MutableList<Product>) {
        selectedItems.postValue(items)
    }
}

MainActivity: AppCompactActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    // scope shared view model to MainActivity
    // I can access and update data from here
        val model = ViewModelProvider(this).get(SharedViewModel::class.java)
    }
}

class MyFragment1: Fragment() {
    // I'm able to get and update data in the SharedViewModel in fragment
    // to activity
    private val sharedModel: SharedViewModel by activityViewModels()
}

此外,您可以向主要活动添加回调。您可以使用界面。

interface IAddListener {
    fun sendItems(items: MutableList<Product>?)
}

class MyFragment: Fragment() {
   
   override fun onAttach(context: Context) {
        super.onAttach(context)

        if (context is IAddListener)
            mCallback = context
    }

    private var mCallback: IAddListener? = null
} 

class MainActivity: AppCompactActivity(), IAddToPrintQueueListener {
    
    override fun sendItems(items: MutableList<Product>?) {
        // update something
    }
}

这里是有关共享数据的文档的链接文档


0
投票

来自 Fragment 版本 1.3.0

在 Activity 中设置结果监听器:

currentFragment.setFragmentResultListener("requestKey") { requestKey, bundle ->
        // We use a String here, but any type that can be put in a Bundle is supported.
        val result = bundle.getString("bundleKey")
        // Do something with the result.
    }

然后在片段中发送结果:

 setFragmentResult("requestKey", bundleOf("bundleKey" to "data"))

更多详细信息:使用 Fragment Result API 获取结果

© www.soinside.com 2019 - 2024. All rights reserved.