如何从自身中删除片段

How to remove a fragment from within itself

在我的应用程序中,我有一个片段 ActivityFragment 的实例,当按下按钮 addActivity 时动态添加该片段。每个 ActivityFragment 中都有一个 delete_button,我在 ActivityFragment class 中为这个按钮设置了一个 onClickListener。按下 delete_button 时,我想从 onClick 方法中删除片段。当我创建 ActivityFragment 对象并将其添加到片段 class 之外的方法中的 activity 时,我将如何着手执行此操作?我应该为 .remove() 使用哪个字段?

注意 delete_button 应该只删除它所在片段的实例。

这是我的 MainActivity.javaActivityFragment class。 addActivity 按钮在底部:

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public static class ActivityFragment extends Fragment {
        // @Nullable is used because the method may return a null value
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
            final View fragment1 = inflater.inflate(R.layout.activity_fragment, container, false);

            Button edit_button = (Button) fragment1.findViewById(R.id.edit_button);
            Button delete_button = (Button) fragment1.findViewById(R.id.delete_button);

            edit_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TextView activityText = (TextView) getView().findViewById(R.id.activity_text);
                    activityText.setText("success");
                }
            });

            delete_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getFragmentManager().beginTransaction()
                            .remove().commit();
                }
            });

            return fragment1;
        }
    }

    public void addActivity(View view) {
        ActivityFragment myFragment = new ActivityFragment();
        getFragmentManager().beginTransaction()
                .add(R.id.fragment_container, myFragment).commit();
    }

}

您可以像这样删除片段实例

delete_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().beginTransaction()
                    .remove(ActivityFragment.this).commit();
        }
    });

可以这样删除片段:

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
MyFragment myFragment = new MyFragment();
fragmentTransaction.remove(myFragment).commit();

此处 myFragment 是您要从当前上下文或当前 activity.

中删除的 "FRAGMENT"