片段交互Android

时间:2014-06-13 22:08:17

标签: android android-fragments fragment

我有一个带有一个按钮的片段类,当我点击按钮时我必须调用load片段并删除我的片段,但我收到了以下错误。

按下按钮后我想加载片段并隐藏我的片段,基本上我想要 替换片段

06-13 15:25:31.665  15440-15440/ E/FragmentManager﹕ (Total messages: 6, idling=false, quitting=false)
06-13 15:25:31.665  15440-15440/E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: , PID: 15440
java.lang.IllegalArgumentException: No view found for id 0x7f0d0023 (Sarver:id/fragment_msg) for fragment LoadingFragment{420ae950 #0 id=0x7f0d0023 “test”}
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:882)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
        at android.app.BackStackRecord.run(BackStackRecord.java:684)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
        at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
        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:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

public class NoTUpdate extends Fragment {

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

    View view = inflater.inflate(R.layout.fragment_msg, container, false);
    Button updateBtn = (Button) view.findViewById(R.id.updateB);
    updateBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.e("buttonClick", "button");
            update();
        }
    });

    return view;
}

2 个答案:

答案 0 :(得分:1)

更改此行:

transaction.add(R.id.fragment_msg, loading, "test");

transaction.replace(R.id.fragment_msg, loading, "test");

答案 1 :(得分:0)

您希望在单击按钮时替换片段,但您在代码中执行的操作是使用以下代码行添加片段:

transaction.add(R.id.fragment_msg, loading, "test");

将此行更改为:

transaction.replace(R.id.fragment_msg, loading, "test"); which does what you want.