gpt4 book ai didi

java - 从 Activity 中的按钮打开的 fragment

转载 作者:行者123 更新时间:2023-12-01 09:46:18 27 4
gpt4 key购买 nike

MainActivity.java

btn_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentOne fragment = new FragmentOne();
fragmentTransaction.add(R.id.layoutFragmentContainer, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});

...

FragmentOne.java

public class FragmentOne extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list,container,false);
}
}

当我单击搜索按钮时,会出现 fragment ,但是当我再次单击它时,应用程序崩溃了。有人可以帮忙吗,我是 Android 新手,无法解决这个问题。

....日志:

 Process: com.example.user1.volleyballmanager, PID: 26892
java.lang.IllegalStateException: commit already called
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:625)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:617)
at com.example.user1.volleyballmanager.MainActivity$2.onClick(MainActivity.java:52)---
line 52 : fragmentTransaction.commit();
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

最佳答案

将此方法放入您的主要 Activity 中

//FRAGMENT BACK STACK
public void getFragmentWithTag(Fragment fragment, String tag) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.replace(R.id.activityFrame, fragment, tag).commit();
}

您可以像这样从 fragment 中调用它..

activity.getFragmentWithTag(Fragment, FragmentTag)

关于java - 从 Activity 中的按钮打开的 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37991066/

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