我的项目结构如下:我有一个调用片段的活动。我的目标是能够简单地将片段从1切换到另一个。我创建了一个新类来处理我的Clicks,如下所示。我成功输入1
案例,因为它出现在我的logcat中。我的问题发生在由于某种原因我无法切换碎片。我想切换到的片段是聊天框。
我现在正试图抓住片段,所以任何帮助都可以。如有必要,我也可以发布我的Activity类。 谢谢。
10-08 00:43:43.706 32310-32310/com.layoutpractice E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.layoutpractice, PID: 32310
java.lang.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1347)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:597)
at android.app.BackStackRecord.commit(BackStackRecord.java:575)
at com.layoutpractice.ClickityClickClick.addFragments(ClickityClickClick.java:43)
at com.layoutpractice.ClickityClickClick.onClick(ClickityClickClick.java:33)
at android.view.View.performClick(View.java:4456)
at android.view.View$PerformClick.run(View.java:18482)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5097)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
下面是我的onClickListener类:
/**
* Created by Programmer 552 on 10/7/2014.
*/
public class ClickityClickClick implements View.OnClickListener {
public static String DEBUG = "Debug";
private LetsPutInAChatBox activity = new LetsPutInAChatBox();
private ChatFragment chatty = new ChatFragment();
private int test;
public ClickityClickClick(int test) {
this.test = test;
}
@Override
public void onClick(View v) {
switch (test) {
case 1:
Log.d(DEBUG, "IN THE METHOD");
addFragments(chatty);
}
}
public void addFragments(Fragment fragment) {
FragmentManager manager = activity.getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.container, fragment);
ft.commit();
}
}
这是我尝试使用addFragments方法调用的片段:
public class ChatFragment extends Fragment {
LetsPutInAChatBox activity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
activity = new LetsPutInAChatBox();
View rootView = inflater.inflate(R.layout.chat_box, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
this.activity = (LetsPutInAChatBox) activity;
super.onAttach(activity);
}
}
答案 0 :(得分:3)
提交片段时,请确保您的活动没有完成。 所以检查一下:
if (!isFinishing()) {
fragmentTransaction.commit();
}