gpt4 book ai didi

android - 将 fragment 之间的数据传递给 Activity

转载 作者:可可西里 更新时间:2023-11-01 19:08:47 25 4
gpt4 key购买 nike

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

最佳答案

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

fragment :

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

Activity :

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

关于android - 将 fragment 之间的数据传递给 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14439941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com