gpt4 book ai didi

java - 如何使用 setArguments/getArguments 创建 fragment

转载 作者:太空狗 更新时间:2023-10-29 12:52:59 26 4
gpt4 key购买 nike

我正在使用来自的信息在我的应用程序中创建标签 epidemian answer

我创建了处理选项卡的主类,该类扩展了 TabActivity 并创建了选项卡:

    Resources res = getResources();
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;

intent = new Intent().setClass(this, stackA.class);
spec = tabHost.newTabSpec("tab1").setIndicator("Tab 1",
res.getDrawable(android.R.drawable.ic_menu_search))
.setContent(intent);
tabHost.addTab(spec);

intent = new Intent().setClass(this, stackB.class);
spec = tabHost.newTabSpec("tab2").setIndicator("Tab 2",
res.getDrawable(android.R.drawable.ic_menu_search))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);

然后为每个选项卡创建 FragmentActivity,这使得在每个选项卡中创建堆栈成为可能。我的 fragment 已创建:

protected void navigateTo(Fragment newFragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content, newFragment);
ft.addToBackStack(null);
ft.commit();
}

public class fragmentA extends Fragment{
private LinearLayout ll;
private FragmentActivity fa;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

fa = super.getActivity();
ll = (LinearLayout) inflater.inflate(R.layout.fragmenta, container, false);
Button next = (Button) ll.findViewById(R.id.button1);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
((ActivityInTab) getActivity()).navigateTo(new fragmentB());
}
});
return ll;
}
}

这是有效的。当我在选项卡 1 和 fragment B(堆栈中的第一个 fragment 是 A)时,旋转我的设备然后它返回到 fragment A 有什么问题。

epidemian 说了一些关于方向和使用 setArguments/getArguments 的事情,但我是 android 编程的新手,所以我真的不知道该怎么做:

Finally, if you need to survive orientation changes, it's important that your fragments are created using setArguments/getArguments. If you set instance variables in your fragments' constructors you'll be screwed. But fortunately that's really easy to fix: just save everything in setArguments in the constructor and then retrieve those things with getArguments in onCreate to use them.

最佳答案

int x;

Bundle args = new Bundle();

args.putString("variable", x);

FragmentManager fragmentManager = getFragmentManager();

FragmentTransaction ft = fragmentManager.beginTransaction();

Fragment fragment = Fragment.instantiate(getActivity(), MyFragment.class.getName(), args);

ft.replace(R.id.layout1, fragment);

ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

ft.addToBackStack(null);

ft.commit();

比在 fragment 中:

getArguments().getInt("variable");

关于java - 如何使用 setArguments/getArguments 创建 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10171460/

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